您的位置:首页 > 其它

USACO——Milking Cows 挤牛奶

2015-06-20 13:30 387 查看

最近开始系统刷USACO,看这进度只能一星期一单元,不积跬步无以至千里,希望能坚持

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 integer
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 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


思路:一开始开个结构体数组存每个人信息,然后通过合并(某人开始在另一个人结束之前,或者落在另一个人区间,只要有交集,则合并),最后因为这些数组已经没有交集,则可以一个个遍历,找出间隔最长时间和工作最长时间

/*
ID: youqihe1
PROG: milk2
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include<algorithm>

using namespace std;
int A[5000][2];
struct farmer
{
int start;
int end;
}pep[5005];
bool cmp(farmer a,farmer b)
{
if(a.start==b.start)
return a.end<b.end;
return a.start<b.start;
}
int main() {
FILE *fin  = fopen ("milk2.in", "r");
FILE *fout = fopen ("milk2.out", "w");
int N;
fscanf(fin,"%d",&N);
int i,j,k=0;
int e,m=-1;
for(i=0;i<N;i++)
{
fscanf(fin,"%d %d",&pep[i].start,&pep[i].end);
e=pep[i].end;
if(e>=m)
m=e;
}

sort(pep,pep+N,cmp);
A[0][0]=pep[0].start;
A[0][1]=pep[0].end;
for(i=1;i<N;i++)
{
int a=pep[i].start,b=pep[i].end;
if(a==A[k][0])
{
if(b<=A[k][1])
continue;
else
{
A[k][1]=b;
continue;
}
}
else
{
if(b<=A[k][1])
continue;
else
{
if(a<=A[k][1])
{
A[k][1]=b;
continue;
}
else
{
A[++k][0]=a;
A[k][1]=b;
continue;
}
}
}
}
k++;
int sh=0,lo=A[0][1]-A[0][0];
if(k==1)
{
fprintf(fout,"%d %d\n",lo,sh);
return 0;
}
for(i=1;i<k;i++)
{
int s,l;
s=A[i][0]-A[i-1][1];
l=A[i][1]-A[i][0];
sh=max(sh,s);
lo=max(lo,l);
}
fprintf(fout,"%d %d\n",lo,sh);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: