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;
}
相关推荐
变量未定义~4 小时前
单调栈-四元组问题
数据结构·算法
冷小鱼5 小时前
AI Agent 核心算法:任务规划(Planning)的深度技术解析
人工智能·算法·planning
杜子不疼.5 小时前
【C++ 在线五子棋对战】- 会话管理模块实现
开发语言·c++
退休倒计时5 小时前
【每日一题】LeetCode 78. 子集 TypeScript
算法·leetcode·typescript
有点。5 小时前
C++深度优先搜索(DFS)的概念(一)
开发语言·c++·深度优先
旖-旎5 小时前
《LeetCode 978 最长湍流子数组 || LeetCode 139 单词拆分》
c++·算法·leetcode·动态规划
aaPIXa6225 小时前
C++大型项目模块化拆分实战记录
开发语言·c++
cxr8285 小时前
第16章 跨域迁移与能力融合——从专家到通才
人工智能·算法·智能体·hermes
石山代码5 小时前
C++23 新特性在 CLion 中的实战体验
开发语言·c++·c++23
学究天人5 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(补充卷9)
人工智能·线性代数·算法·数学建模·动态规划·原型模式·抽象代数