题目大意:
有N个工作被编号为1..N (1 ≤ N ≤ 1,000)
完成第i个工作需要T_i (1 ≤ T_i ≤ 1,000)的时间
第i个工作需在S_i (1 ≤ S_i ≤ 1,000,000)前结束
若能按时完成则输出 最晚开始工作的时间 若不能则输出 -1
Input
* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains two space-separated integers: T_i and S_i
Output
* Line 1: The latest time Farmer John can start working or -1 if Farmer John cannot finish all the jobs on time.
Sample Input
4
3 5
8 14
5 20
1 16
Sample Output
2
Hint
INPUT DETAILS:
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.
OUTPUT DETAILS:
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.
#include <bits/stdc++.h> #define INF 0x3f3f3f3f using namespace std; struct job { int s,e; }a[1005]; bool cmp(struct job a,struct job b) { return a.e<b.e; } int main() { int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d%d",&a[i].s,&a[i].e); sort(a+1,a+1+n,cmp); /// 按最晚结束时间排序 int ans=INF; for(int i=n;i>=1;i--) /// 从最晚结束的事件开始遍历 ans=min(ans,a[i].e)-a[i].s; /* 最晚开始时间与前一件事的最晚结束时间取更早的一个 最终推出第一件事的最晚开始时间 若无法按时完成 则时间会被推到0之前 也就是ans<0 */ if(ans<0) printf("-1 "); else printf("%d ",ans); return 0; }