USACO1.21Milking 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 integer | Lines 2..N+1: | Two non-negative integers less than 1000000, 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 longest continuous time of milking and the longest idle time.
SAMPLE OUTPUT (file milk2.out)
900 300 好几天前没过的一题 突然想到哪错了 就改了改过了 贪心求连续覆盖区间最大值和连续不被覆盖的最大值 之前以左端点排序 然后枚举查找 依次更新最大值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 ID: your_id_here 3 LANG: C++ 4 TASK: milk2 5 */ 6 #include <iostream> 7 #include<cstdio> 8 #include<string.h> 9 #include<algorithm> 10 using namespace std; 11 #define N 1000000 12 struct node 13 { 14 int a,b; 15 }q[N+10]; 16 bool cmp(node x,node y) 17 { 18 return x.b<y.b; 19 } 20 bool cmpp(node x,node y) 21 { 22 return x.a<y.a; 23 } 24 int main() 25 { 26 freopen("milk2.in","r",stdin); 27 freopen("milk2.out","w",stdout); 28 int i,j,k,n,m,a,b,max =0,mm = 0; 29 scanf("%d",&n); 30 for(i = 0 ; i < n ; i++) 31 scanf("%d%d",&q[i].a,&q[i].b); 32 sort(q,q+n,cmpp); 33 for(i = 0 ; i < n ; i++) 34 { 35 int tmax = q[i].b-q[i].a; 36 int x = q[i].b; 37 for(j = i ; j < n-1 ; j++) 38 { 39 if(x>=q[j+1].a) 40 { 41 if(q[j+1].b>x) 42 { 43 tmax+=(q[j+1].b-x); 44 x = q[j+1].b; 45 } 46 } 47 } 48 if(max<tmax) 49 max = tmax; 50 } 51 sort(q,q+n,cmp); 52 int tmax = 0; 53 int m1 = q[n-1].a; 54 for(i = n-2 ; i >= 0 ;i--) 55 { 56 if(q[i].b<m1) 57 { 58 if(mm<m1-q[i].b) 59 mm = m1-q[i].b; 60 } 61 if(q[i].a<m1) 62 m1 = q[i].a; 63 } 64 printf("%d %d\n",max,mm); 65 fclose(stdin); 66 fclose(stdout); 67 return 0; 68 }