LUOGU P2920 [USACO08NOV]时间管理Time Management

题目描述

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工作要 做,比如给奶牛挤奶,清洗牛棚,修理栅栏之类的.

为了高效,列出了所有工作的清单.第i分工作需要T_i单位的时间来完成,而 且必须在S_i或之前完成.现在是0时刻.约翰做一份工作必须直到做完才能停 止.

所有的商人都喜欢睡懒觉.请帮约翰计算他最迟什么时候开始工作,可以让所有工作按时完成.(如果无法完成全部任务,输出-1)
输入输出格式
输入格式:

  • 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.

输入输出样例
输入样例#1: 复制

4
3 5
8 14
5 20
1 16

输出样例#1: 复制

2

说明

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.

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.

解题思路

考试题,二分答案斜挂。。。我真的是个人才, 发现必须要有ans,不能直接输出l,否则会有些奇奇怪怪的错误。我的做法是将原数列按S排序,然后二分答案,时间复杂度O(nlogn),100000还是可以过的。

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>

using namespace std;
const int MAXN = 100005;

inline int rd(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}
    while(ch>='0' && ch<='9') {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
    return x*f;
}

int n,ans=0;

struct Time{
    int st,ed;
}t[MAXN];

inline bool cmp(Time a,Time b){
    return a.ed<b.ed;
}

inline bool check(int x){
    int k=x;
    for(register int i=1;i<=n;i++){
        k+=t[i].st;
        if(k>t[i].ed) return false;
    }
    return true;
}

int main(){
//  freopen("manage.in","r",stdin);
//  freopen("manage.out","w",stdout);
    n=rd();
    for(register int i=1;i<=n;i++)
        t[i].st=rd(),t[i].ed=rd();
    sort(t+1,t+1+n,cmp);
    int l=0,r=t[1].ed-t[1].st;
//  for(register int i=1;i<=n;i++) cout<<t[i].st<<" "<<t[i].ed<<endl;
    if(r<0) {puts("-1");return 0;}
    while(l<=r){
        int mid=(l+r)>>1;
//      cout<<l<<" "<<r<<" ";
//      cout<<mid<<endl;
        if(check(mid)) {l=mid+1;ans=mid;}
        else r=mid-1;
    }
    if(ans==0 && !check(0)) puts("-1");
    else printf("%d",ans);
    return 0;
}

/*
4
3 5
8 14
5 20
1 16
*/


/*
3
1 100
100 105
110 300
*/
posted @ 2018-07-03 18:47  Monster_Qi  阅读(130)  评论(0编辑  收藏  举报