基准时间限制: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
这道题 我几乎是试出来的。。。
后来想了想,说一下自己的理解。
第n个任务有两个参数,一个是执行空间oper,一个是存储时间strore。根据题意可知,oper>=store。
假设只有两个任务,那么就两种结果,先执行a,后执行b。或者先执行b,后执行a。
前者的结果是 max(a.oper,a.store+b.oper)
后者的结果是 max(b.oper,b.store+a.oper)
这个时候可以知道,结果一定是min( a.store+b.oper , b.store+a.oper )
假设a.store + b.oper < b.store + a.oper 。产生这样结果的原因是 先执行a,后执行b的顺序
所以有b.oper - b.store < a.oper - a.store。所以可知,排序的时候要将 store-oper 这个差值大的放前面,让它先执行,这样就能取到最小值。
代码:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#pragma warning(disable:4996)
using namespace std;
int n;
struct no
{
int store;
int oper;
}node[100005];
bool cmp(no n1, no n2)
{
if (n1.oper - n1.store != n2.oper - n2.store)
{
return n1.oper - n1.store > n2.oper - n2.store;
}
else
{
return n1.oper >= n2.oper;
}
}
int main()
{
//freopen("i.txt", "r", stdin);
//freopen("o.txt", "w", stdout);
int i;
int sum, maxn;
scanf("%d", &n);
sum = 0;
maxn = 10005;
for (i = 0; i < n; i++)
{
scanf("%d%d", &node[i].oper, &node[i].store);
sum += node[i].store;
}
sort(node, node + n, cmp);
int already = 0;
int temp;
for (i = 0; i < n; i++)
{
temp = already + node[i].oper;
already += node[i].store;
sum = max(sum, temp);
}
printf("%d\n", sum);
//system("pause");
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。