[USACO08NOV]时间管理Time Management(排序,贪心)

题目描述

作为一名忙碌的商人,约翰知道必须高效地安排他的时间.他有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.

说明

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.

思路:

一道大水题,然而我还是错了……

我们知道他的持续时间和结束时间,那么我们肯定要在结束之前完成所有(否则输出-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;
}

 

转载于:https://www.cnblogs.com/ztz11/p/9260211.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值