【区间计数】Milking Cows 挤牛奶 (milk2) Usaco_Training 1.2

来源:互联网 发布:炉石传说帐号淘宝 编辑:程序博客网 时间:2024/06/10 08:40

Milking Cows 挤牛奶
(milk2)

Milking Cows

Three farmers rise at 5 am each morning and head for the barn to milk three cows. The first farmer begins milking his cow at time 300 (measured in seconds after 5 am) and ends at time 1000. The second farmer begins at time 700 and ends at time 1200. The third farmer begins at time 1500 and ends at time 2100. The longest continuous time during which at least one farmer was milking a cow was 900 seconds (from 300 to 1200). The longest time no milking was done, between the beginning and the ending of all milking, was 300 seconds (1500 minus 1200).

Your job is to write a program that will examine a list of beginning and ending times for N (1 <= N <= 5000) farmers milking N cows and compute (in seconds):

  • The longest time interval at least one cow was milked.
  • The longest time interval (after milking starts) during which no cows were being milked.

PROGRAM NAME: milk2

INPUT FORMAT

Line 1:The single integerLines 2..N+1:Two non-negative integers less than 1000000, the starting and ending time in seconds after 0500

SAMPLE INPUT (file milk2.in)

3300 1000700 12001500 2100

OUTPUT FORMAT

A single line with two integers that represent the longest continuous time of milking and the longest idle time.

SAMPLE OUTPUT (file milk2.out)

900 300

翻译:

【描述】

三个农民每天清晨5点起床,然后去牛棚给3头牛挤奶。第一个农民在300秒(从5点开始计时)给他的牛挤奶,一直到1000秒。第二个农民在700秒开始,在 1200秒结束。第三个农民在1500秒开始2100秒结束。期间最长的至少有一个农民在挤奶的连续时间为900秒(从300秒到1200秒),而最长的无人挤奶的连续时间(从挤奶开始一直到挤奶结束)为300秒(从1200秒到1500秒)。

你的任务是编一个程序,读入一个有N个农民(1 <= N <= 5000)挤N头牛的工作时间列表,计算以下两点(均以秒为单位):

  • 最长至少有一人在挤奶的时间段。
  • 最长的无人挤奶的时间段。(从有人挤奶开始算起)

【输入输出格式】

PROGRAM NAME: milk2

INPUT FORMAT:

(file milk2.in)

Line 1:

一个整数N。

Lines 2..N+1:

每行两个小于1000000的非负整数,表示一个农民的开始时刻与结束时刻。

OUTPUT FORMAT:

(file milk2.out)

一行,两个整数,即题目所要求的两个答案。

 

 

这一题典型的区间问题,离散化排序,用一个计数器,遇到左界就+1,遇到右界就-1

主要注意排序的时候如果值相等就要按照先左界后右界来排序(不然计数器就会先-1,就会错误判断到0了,就错误地以为区间到此结束了)

C++ Code

/*ID: jiangzh15TASK: milk2LANG: C++http://blog.csdn.net/jiangzh7*/#include<cstdio>#include<algorithm>using namespace std;#define MAXN 10010struct node{int t,r;}a[MAXN];//r=0表示左界,r=1表示右界int n;bool cmp(node a,node b){    if(a.t==b.t)return a.r<b.r;//相同则按照先左后右的原则排序    return a.t<b.t;}int main(){    freopen("milk2.in","r",stdin);    freopen("milk2.out","w",stdout);    scanf("%d",&n);    int c=0;    for(int i=1;i<=n;i++)    {        scanf("%d",&a[++c].t);a[c].r=0;        scanf("%d",&a[++c].t);a[c].r=1;    }    sort(a+1,a+1+c,cmp);    int num=0,last=0;    int maxw=0,maxr=0;    for(int i=1;i<=c;i++)    {        if(!a[i].r)num++;        if(a[i].r)num--;        if(num==0)        {            maxw=max(maxw,a[i].t-a[last+1].t);            maxr=max(maxr,a[i+1].t-a[i].t);            last=i;        }    }    printf("%d %d\n",maxw,maxr);    return 0;}

 

 

原创粉丝点击