基准时间限制:1 秒 空间限制:131072 KB 分值: 20
难度:3级算法题
有N个任务需要执行,第i个任务计算时占R[i]个空间,而后会释放一部分,最后储存计算结果需要占据O[i]个空间(O[i] < R[i])。
例如:执行需要5个空间,最后储存需要2个空间。给出N个任务执行和存储所需的空间,问执行所有任务最少需要多少空间。
Input
第1行:1个数N,表示任务的数量。(2 <= N <= 100000) 第2 - N + 1行:每行2个数R[i]和O[i],分别为执行所需的空间和存储所需的空间。(1 <= O[i] < R[i] <= 10000)
Output
输出执行所有任务所需要的最少空间。
Input示例
20 14 1 2 1 11 3 20 4 7 5 6 5 20 7 19 8 9 4 20 10 18 11 12 6 13 12 14 9 15 2 16 15 17 15 19 13 20 2 20 1
Output示例
135
这道题目也是一个贪心的题目。解题的关键在于数据的处理,排序很重要,第一把a-b大的排在前面,第二按b大的排在前面,然后线性扫一遍即可。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
struct point{
int s,e;
}p[100005];
bool cmp(struct point a,struct point b){
if(a.s-a.e!=b.s-b.e)
return a.s-a.e>b.s-b.e;
return a.e>b.e;
}
int main()
{
int i,j,n,x;
long sum;
// freopen("test.txt","r",stdin);
while(~scanf("%d",&n)){
for(i=0;i<n;i++){
scanf("%d %d",&p[i].s,&p[i].e);
}
sort(p,p+n,cmp);//排序,按间隔大的排序,其中右端点大的放在前面
// for(i=0;i<n;i++)
// printf("%d %d\n",p[i].s,p[i].e);
// printf("\n");
sum=p[0].s;
x=p[0].s-p[0].e;
for(i=1;i<n;i++){
if(x<p[i].s){
sum=sum+p[i].s-x;
x=p[i].s-p[i].e;
}
else{
x=x-p[i].e;
}
// printf("%ld %d\n",sum,x);
}
printf("%ld\n",sum);
}
return 0;
}