USCAO-Section1.2 Milking Cows

来源:互联网 发布:网络直播推广软文 编辑:程序博客网 时间:2024/06/05 09:36

原题:
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.

题解:
给定n组区间,求最长连续区间和起点到终点之间不在区间内的区间的最长长度,先排序再计算,比较简单,直接上代码:

/*ID:newyear111PROG: milk2LANG: C++*/#include <iostream>#include <fstream>#include <string>#include<algorithm>using namespace std;const int N=5010;struct node{    int start,end;}T[N];int n;//排序函数,起点不同按起点拍,不同按终点排 bool cmp(node a,node b){    if(a.start!=b.start)    {        return a.start<b.start;    }    return a.end<b.end;}int main(){    ifstream fin("milk2.in");    ofstream fout("milk2.out");    while(fin>>n)    {        for(int i=0;i<n;i++)            fin>>T[i].start>>T[i].end;        //只有一组数据的时候单独考虑  QAQ~~~         if(n==1)        {            fout<<T[0].end-T[0].start<<" "<<0<<endl;            continue;        }        //排序         sort(T,T+n,cmp);        //max1记录最长连续区间 max0记录最长非标记区间        //st记录连续区间起点  e记录连续区间终点         int max0,max1,st,e;        //初始化         st=T[0].start;        e=T[0].end;        max1=e-st;        max0=0;        for(int i=1;i<n;i++)        {            //如果下一段区间起点在上一段区间内,e=max(e,T[i].end)并更新max1             if(T[i].start<=e)            {                e=max(e,T[i].end);                max1=max(max1,e-st);            }            //如果下一段区间起点不知上一段区间内,st标记下一段区间起点,e为上一段区间终点            //从而更新max0   更新完e标记新连续区间终点             else            {                st=T[i].start;                max0=max(max0,st-e);                e=T[i].end;            }        }        fout<<max1<<" "<<max0<<endl;    }    fin.close();    fout.close();    return 0;}