题目描述
做为一名忙碌的商人,约翰知道必须高效地安排他的时间.他有N工做要 作,好比给奶牛挤奶,清洗牛棚,修理栅栏之类的.ios
为了高效,列出了全部工做的清单.第i分工做须要T_i单位的时间来完成,而 且必须在S_i或以前完成.如今是0时刻.约翰作一份工做必须直到作完才能停 止.优化
全部的商人都喜欢睡懒觉.请帮约翰计算他最迟何时开始工做,可让全部工做按时完成.(若是没法完成所有任务,输出-1)spa
输入输出格式
输入格式:指针
* Line 1: A single integer: Ncode
* Lines 2..N+1: Line i+1 contains two space-separated integers: T_i and S_iblog
输出格式:排序
* Line 1: The latest time Farmer John can start working or -1 if Farmer John cannot finish all the jobs on time.it
说明
Farmer John has 4 jobs to do, which take 3, 8, 5, and 1 units of time, respectively, and must be completed by time 5, 14, 20, and 16, respectively.io
Farmer John must start the first job at time 2. Then he can do the second, fourth, and third jobs in that order to finish on time.ast
思路:
一道大水题,然而我仍是错了……
咱们知道他的持续时间和结束时间,那么咱们确定要在结束以前完成全部(不然输出-1)
因此咱们按照结束时间排序
由于题目让你求最晚何时开始,因此咱们尽量地将任务日后放
对应过来就是从最大的开始,时光倒流
用一个time指针维护上一个开始的时刻
若是time比当前一个的结束点早,那么当前一个的实际结束点就是time
反之实际结束点就是最晚结束点
o(n)扫一遍便可
加上排序时间复杂度总共是O(nlogn+n)
很优化
代码:
#include<iostream> #include<cstdio> #include<algorithm> #define rii register int i using namespace std; struct deal{ int keep,start,last; }x[100005]; int n,time; bool cmp(deal ltt,deal kkk) { return ltt.last>kkk.last; } int main() { // freopen("manage.in","r",stdin); // freopen("manage.out","w",stdout); scanf("%d",&n); for(rii=1;i<=n;i++) { scanf("%d%d",&x[i].keep,&x[i].last); x[i].start=x[i].last-x[i].keep; } sort(x+1,x+n+1,cmp); time=x[1].start; for(rii=2;i<=n;i++) { if(x[i].last<time) { time=x[i].start; } else { time=time-x[i].keep; } } if(time<0) { printf("-1"); return 0; } printf("%d",time); return 0; }