[USACO 1.2.1] Milking Cows

来源:互联网 发布:5230手机加密软件 编辑:程序博客网 时间:2024/05/18 00:41

[题目描述]

Milking Cows

挤牛奶

三个农民每天清晨5点起床,然后去牛棚给3头牛挤奶。第一个农民在300时刻(从5点开始计时,秒为单位)给他的牛挤奶,一直到1000时刻。第二个农民在700时刻开始,在 1200时刻结束。第三个农民在1500时刻开始2100时刻结束。期间最长的至少有一个农民在挤奶的连续时间为900秒(从300时刻到1200时刻),而最长的无人挤奶的连续时间(从挤奶开始一直到挤奶结束)为300秒(从1200时刻到1500时刻)。

你的任务是编一个程序,读入一个有N个农民(1 <= N <= 5000)挤N头牛的工作时间列表,计算以下两点(均以秒为单位):

  • 最长至少有一人在挤奶的时间段。
  • 最长的无人挤奶的时间段。

PROGRAM NAME: milk2

INPUT FORMAT

Line 1:

一个整数N。

Lines 2..N+1:

每行两个小于1000000的非负整数,表示一个农民的开始时刻与结束时刻。

SAMPLE INPUT (file milk2.in)

3
300 1000
700 1200
1500 2100
OUTPUT FORMAT

一行,两个整数,即题目所要求的两个答案。

SAMPLE OUTPUT (file milk2.out)

900 300

[解题思路]
题目模型很简单,可以看做是给定N条线段,有交的线段可以合并,问合并后最长的线段,与最长的线段间距离。自然先排序,以x为第一关键字,y为第二关键字离散每条线段,然后模拟合并每条线段,统计答案即可,时间复杂度O(NlogN+N)。

[Code]
{ID: zane2951PROG: milk2LANG: PASCAL}program milk2;var   x,y,lx,ly:array[0..5011] of longint;   ans1,ans2,n,i,tot,xx,yy:longint;//-----------qs------------procedure qs(s,t:longint);var   i,j,cex,cey,tmp:longint;begin   i:=s; j:=t; cex:=x[(i+j)>>1]; cey:=y[(i+j)>>1];   repeat      while (x[i]<cex) or (x[i]=cex) and (y[i]<cey) do inc(i);      while (x[j]>cex) or (x[j]=cex) and (y[j]>cey) do dec(j);      if i<=j then         begin            tmp:=x[i]; x[i]:=x[j]; x[j]:=tmp;            tmp:=y[i]; y[i]:=y[j]; y[j]:=tmp;            inc(i); dec(j);         end;   until i>j;   if i<t then qs(i,t); if s<j then qs(s,j);end;//----------main-----------begin   assign(input,'milk2.in'); reset(input);   assign(output,'milk2.out'); rewrite(output);   readln(n);   for i:=1 to n do readln(x[i],y[i]);   qs(1,n); tot:=0; ans1:=0;   x[n+1]:=1111111; y[n+1]:=1111111;   xx:=x[1]; yy:=y[1];   for i:=2 to n+1 do      if (x[i]>=xx) and (x[i]<=yy) then         if y[i]>yy then yy:=y[i] else else            begin               if yy-xx>ans1 then ans1:=yy-xx;               inc(tot);               lx[tot]:=xx;               ly[tot]:=yy;               xx:=x[i];               yy:=y[i];            end;   ans2:=0;   for i:=2 to tot do      if lx[i]-ly[i-1]>ans2 then ans2:=lx[i]-ly[i-1];   writeln(ans1,'':1,ans2);   close(input); close(output);end.


原创粉丝点击