Three farmers rise at 5 am each morning and head for the barnto milk three cows. The first farmer begins milking his cow at time300 (measured in seconds after 5 am) and ends at time 1000. Thesecond farmer begins at time 700 and ends at time 1200. The thirdfarmer begins at time 1500 and ends at time 2100. The longestcontinuous time during which at least one farmer was milking a cowwas 900 seconds (from 300 to 1200). The longest time no milking wasdone, between the beginning and the ending of all milking, was 300seconds (1500 minus 1200).
Your job is to write a program that will examine a list ofbeginning and ending times for N (1 <= N <= 5000) farmersmilking N cows and compute (in seconds):
- The longest time interval at least one cow was milked.
- The longest time interval (after milking starts) during whichno cows were being milked.
PROGRAM NAME: milk2
INPUT FORMAT
Line 1: | The single integer |
Lines 2..N+1: | Two non-negative integers less than1000000, the starting and ending time in seconds after 0500 |
SAMPLE INPUT (file milk2.in)
3 300 1000 700 1200 1500 2100
OUTPUT FORMAT
A single line with two integers that represent the longestcontinuous time of milking and the longest idle time.SAMPLE OUTPUT (file milk2.out)
900 300 解题思路: 本题大意是说某牧场养牛,靠牧民挤奶,然而每个牧民的挤奶时间并不一致,有可能在某个时间段一直都有人在挤奶哦,也有可能在某一个时间段没有人在挤奶,所以, 在本题中,我采用了一贯的思路,用结构体来存储每个牧民的开始与结束时间,并按照开始时间的先后排序,然后对牧民的时间数组遍历,判断每一次的开始时间与前一次结束 时间的先后,如果本次开始早于前次结束,则再判断本次结束若晚于上次结束,则替换,记录持续时间,否则,记录无人挤奶连续时间。 代码如下:/* ID:ayludon3 LANG: C++ TASK: milk2 */ #include <iostream> #include <fstream> #include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> #include<algorithm> using namespace std; struct Time { int startT; int endT; }; int cmp(Time a,Time b) { if(a.startT<b.startT) return 1; else if(a.startT==b.startT&&a.endT<b.endT) return 1; else return 0; } int main() { // ifstream fin ("milk2.in"); // ofstream fout ("milk2.out"); Time per[5001]; int i,n,ss,ee; int Max,Min,count1,count2; // fin>>n; cin>>n; for(i=0;i<n;i++) // fin>>per[i].startT>>per[i].endT; cin>>per[i].startT>>per[i].endT; sort(per,per+n,cmp); ss=per[0].startT; ee=per[0].endT; Min=0; Max=ee-ss; for(i=1;i<n;i++) { if(per[i].startT>=ss&&per[i].startT<=ee) { if(per[i].endT>ee) ee=per[i].endT; } else if(per[i].startT>ee) { count1=ee-ss; count2=per[i].startT-ee; if(count1>Max) Max=count1; if(count2>Min) Min=count2; ss=per[i].startT; ee=per[i].endT; } } // fout<<Max<<' '<<Min<<endl; cout<<Max<<' '<<Min<<endl; return 0; }