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;
}
相关推荐
机器学习之心33 分钟前
多目标鲸鱼优化算法(NSWOA),含46种测试函数和9个评价指标,MATLAB实现
算法·matlab·多目标鲸鱼优化算法·46种测试函数·9个评价指标
西阳未落1 小时前
C++基础(21)——内存管理
开发语言·c++·面试
max5006001 小时前
基于Meta Llama的二语习得学习者行为预测计算模型
人工智能·算法·机器学习·分类·数据挖掘·llama
超级大福宝1 小时前
使用 LLVM 16.0.4 编译 MiBench 中的 patricia遇到的 rpc 库问题
c语言·c++
wangjialelele2 小时前
Linux中的线程
java·linux·jvm·c++
王哥儿聊AI3 小时前
Lynx:新一代个性化视频生成模型,单图即可生成视频,重新定义身份一致性与视觉质量
人工智能·算法·安全·机器学习·音视频·软件工程
hsjkdhs3 小时前
万字详解C++之构造函数析构函数
开发语言·c++
SELSL4 小时前
SQLite3的API调用实战例子
linux·数据库·c++·sqlite3·sqlite实战
什么半岛铁盒4 小时前
C++项目:仿muduo库高并发服务器-------Channel模块实现
linux·服务器·数据库·c++·mysql·ubuntu
手握风云-4 小时前
优选算法的寻踪契合:字符串专题
算法