Tasks and Deadlines(Sorting and Searching)

题目描述

You have to process n tasks. Each task has a duration and a deadline, and you will process the tasks in some order one after another. Your reward for a task is d-f where d is its deadline and f is your finishing time. (The starting time is 0, and you have to process all tasks even if a task would yield negative reward.)

What is your maximum reward if you act optimally?

输入

The first input line has an integer n(1 ≤ n ≤ ): the number of tasks.

After this, there are n lines that describe the tasks. Each line has two integers a and d(1 ≤ a,d ≤ ): the duration and deadline of the task.

输出

Print one integer: the maximum reward.

样例输入
cpp 复制代码
3
6 10
8 15
5 12
样例输出
复制代码
2
思路分析

贪心、排序。

本题排序原则可以用数学表达式解释。

设起始时间T。

对于任务a和任务b,先a后b的情况下reward为a.deadline-T+b.deadline-(T+a.duration);

先b后a的情况下reward为b.deadline-T+a.deadline-(T+b.duration)。

化简约分下来发现,如果b.duration>a.duration,则a排在b前面。

代码
cpp 复制代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n,a,d,ans;
struct node{
    ll duration,deadline;
};
vector<node>task;
bool cmp(node&a,node&b){
    return b.duration>a.duration;
}
int main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a>>d;
        task.push_back({a,d});
    }
    sort(task.begin(),task.end(),cmp);
    ll t=0;
    for(node i:task){
        t+=i.duration;
        ans+=i.deadline-t;
    }
    cout<<ans;
    return 0;
}
相关推荐
Larry_Yanan15 小时前
QML学习笔记(四十二)QML的MessageDialog
c++·笔记·qt·学习·ui
寂静山林15 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway15 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
R-G-B15 小时前
【35】MFC入门到精通——MFC运行 不显示对话框 MFC界面不显示
c++·mfc·mfc运行 不显界面·mfc界面不显示
Madison-No716 小时前
【C++】探秘vector的底层实现
java·c++·算法
晚风残16 小时前
【C++ Primer】第十二章:动态内存管理
开发语言·c++·c++ primer
Swift社区16 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫16 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
liu****16 小时前
8.list的模拟实现
linux·数据结构·c++·算法·list
保持低旋律节奏16 小时前
C++ stack、queue栈和队列的使用——附加算法题
c++