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;
}
相关推荐
程序员老陆9 分钟前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
信奥卷王27 分钟前
[GESP202609 六级] 分树规划
算法
夏幻灵34 分钟前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG2 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z3 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛3 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记3 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练
半杯咖啡半行码3 小时前
C++ 编程与 STL 模板:从泛型编程到内存安全详解
开发语言·c++
浮链序3 小时前
怎么证明"你这个模型是偷我的"——把蒸馏变成取证工具
算法·安全·llm