USACO--Milking Cows

来源:互联网 发布:mysql安装教程 图解 编辑:程序博客网 时间:2024/05/29 06:55

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 1,000,000, respectively 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

思路:

这道题挺简单的,刚开始的思路用的结构体排序,判断,要是下次开始时间小于上次结束时间,就更新连续的时间,如果下次开始时间大于上次结束时间,就求出间隔时间

可是这种思路一直没有解决 一组数据涵盖所有时间的情况,只有用这种笨方法,幸好数据不是太极端,否则肯定会超时。这种是开一个bool型大小为999999的数组,

把挤奶时间标记为true,间隔时间为false,这样来求出最大的连续,间隔时间


代码如下:

#include<cstdio>#include<iostream>#include<cstring>#include<algorithm>#define MAXN 999999using namespace std;bool cmp(int a,int b)  {return a>b;}int main(){freopen("milk2.in","r",stdin);freopen("milk2.out","w",stdout);int N;scanf("%d",&N);int s,e,beg,fin,vis[MAXN];memset(vis,0,sizeof(vis));for(int i=0;i<N;i++){scanf("%d%d",&s,&e);if(!i || s<beg) beg=s;       //beg为最早的开始时间if(!i || e>fin) fin=e;          //end为最后结束时间for(int j=s;j<e;j++)vis[j]=true;}int con,bre,len=0,arr[MAXN]; //con为连续的时间,bre为间隔时间bool tg=false;   memset(arr,0,sizeof(arr));for(int i=beg;i<fin;i++){if(vis[i]) {arr[len]++;tg=true;}if(!vis[i] && tg) {len++;tg=false;}}sort(arr,arr+len,cmp);con=arr[0];  //排序求出最大值,len=0;tg=false;memset(arr,0,sizeof(arr));for(int i=beg;i<fin;i++){if(!vis[i]) {arr[len]++;tg=true;}if(vis[i] && tg) {len++;tg=false;}}sort(arr,arr+len,cmp);bre=arr[0];printf("%d %d\n",con,bre);return 0;}

0 0
原创粉丝点击