usaco training
关注我持续更新usaco training内容
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.
NOTE:Milking from time 1 through 10, then from time 11 through 20 counts as two different time intervals.
PROGRAM NAME: milk2
INPUT FORMAT
Line 1: The single integer, N Lines 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)
3 300 1000 700 1200 1500 2100OUTPUT 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
这题连大模拟都算不上,就是一个小小的模拟而已
翻译一下:给出n个奶牛挤奶开始时间以及结束时间,并求出最长连续挤奶时间和最长不挤奶时间
最长连续挤奶时间有两种情况:
(1)就是一个奶牛的挤奶时间
(2)第二头奶牛挤奶开始时间比第一头奶牛挤奶结束时间还要早,也就是说两头奶牛的挤奶时间相交,所以就把两段时间相加
我们把一头奶牛挤奶时间抽象成一个长方形
第一种:
很明显就能看出最长连续挤奶时间是第二头,闲置时间也就是空白那里
那么这种情况程序怎么写呢
我们用两个变量代表要求的两个时间:max_和min_
还有两个变量表示max_的时间的起始和结束时间:s和e
初始化:首先先将s定义为第一头奶牛的开始时间,将e定义为第一头奶牛的结束时间
然后对后面的奶牛依次考虑,如果这头奶牛的挤奶时间比现在的e和s的间隔长,就把e和s更新
然后求max_
因为共有两种情况,这里就先不给代码了
第二种:
这样的图形很明显可以看到最长连续挤奶时间是两个时间加在一起,间隔时间为0
两个方块相交,其实就可以抽象成这样:
新长方形的开始为原第一个的开始,新长方形的结束为第二个的结束
把这两个思想一结合就成为了ac代码
/*
ID:
TASK:milk2
LANG:C++
*/
# include <iostream>
# include <cstdio>
# include <algorithm>
using namespace std;
# define int long long
# define N 5005
int n,v[N],maxn=0;
struct node{
int st,en;
}cow[N];
bool cmp(node a,node b){
if (a.st==b.st){
return a.en<b.en;
}
return a.st<b.st;
}
signed main(){
freopen("milk2.in","r",stdin);
freopen("milk2.out","w",stdout);
scanf("%lld",&n);
for (int i=1;i<=n;i++){
scanf("%lld %lld",&cow[i].st,&cow[i].en);
}
if (n==1){//特判如果只有一头奶牛
printf("%lld 0\n",cow[1].en-cow[1].st);
return 0;
}
sort(cow+1,cow+1+n,cmp);
int s=cow[1].st,e=cow[1].en,max_=0,min_=0;
for (int i=2;i<=n;i++){
if(cow[i].st<=e){
e=max(e,cow[i].en);
}
else{
min_=max(min_,cow[i].st-e);
s=cow[i].st;
e=cow[i].en;
}
max_=max(max_,e-s);
}
printf("%lld %lld\n",max_,min_);
fclose(stdin);
fclose(stdout);
return 0;
}