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;
}
相关推荐
稚辉君.MCA_P8_Java13 分钟前
Gemini永久会员 Java中的四边形不等式优化
java·后端·算法
稚辉君.MCA_P8_Java24 分钟前
通义 插入排序(Insertion Sort)
数据结构·后端·算法·架构·排序算法
无限进步_1 小时前
C语言动态内存的二维抽象:用malloc实现灵活的多维数组
c语言·开发语言·数据结构·git·算法·github·visual studio
Swift社区1 小时前
LeetCode 432 - 全 O(1) 的数据结构
数据结构·算法·leetcode
逝玄1 小时前
关于图灵停机问题不可判定性证明
算法·计算机科学
低客的黑调2 小时前
为你的项目选择一个适合的[垃圾收集器]
java·jvm·算法
芬加达2 小时前
leetcode34
java·数据结构·算法
资深web全栈开发2 小时前
LeetCode 1015. 可被 K 整除的最小整数 - 数学推导与鸽巢原理
算法·leetcode·职场和发展
dragoooon342 小时前
[优选算法专题八.分治-归并 ——NO.46~48 归并排序 、数组中的逆序对、计算右侧小于当前元素的个数]
数据结构·算法·排序算法·分治