题号:NC210102 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 262144K,其他语言524288K 64bit IO Format: %lld 题目描述 Ever the maturing businessman, Farmer John realizes that he must manage his time effectively. He has N jobs conveniently numbered 1..N (1 <= N <= 1,000) to accomplish (like milking the cows, cleaning the barn, mending the fences, and so on). To manage his time effectively, he has created a list of the jobs that must be finished. Job i requires a certain amount of time T_i (1 <= T_i <= 1,000) to complete and furthermore must be finished by time S_i (1 <= S_i <= 1,000,000). Farmer John starts his day at time t=0 and can only work on one job at a time until it is finished. Even a maturing businessman likes to sleep late; help Farmer John determine the latest he can start working and still finish all the jobs on time.

N个工作,每个工作其所需时间,及完成的Deadline,问要完成所有工作,最迟要什么时候开始.

输入描述:

  • Line 1: A single integer: N

  • Lines 2..N+1: Line i+1 contains two space-separated integers: T_i and S_i

输出描述:

  • Line 1: The latest time Farmer John can start working or -1 if Farmer John cannot finish all the jobs on time.

代码:

#include<bits/stdc++.h>
using namespace std;
struct job
{
	int t;
	int end;
};
job jobs[1000001];
int n;
bool cmp(job a, job b);
bool ok(int time) {
	for(int i=0;i<n;i++) {
		if(jobs[i].t+time<=jobs[i].end)time+=jobs[i].t;
		else return false;
	}
	return true;
}
bool cmp(job a,job b) {
	return a.end<b.end;
}
int main() 
{
	int r=1000000000,l=0,mid;
	int ans=-1;
	cin>>n;
	for(int i=0;i<n;i++)cin>>jobs[i].t>>jobs[i].end;
	sort(jobs,jobs+n,cmp);
	while(l<=r) {
		mid=l+(r-l)/2;
		if(ok(mid)) {
			ans=mid;
			l=mid+1;
		} 
		else r=mid-1;
	}
	cout<<ans;
	return 0;
}