USACO Milking Cows 解题日志

来源:互联网 发布:淘宝充气娃娃实际拍图 编辑:程序博客网 时间:2024/06/04 20:16

因为过年,加上被窝太温暖,加上……总之好久没有做题了。

先把题目贴上来。

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 integerLines 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)

3300 1000700 12001500 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

这道题思路很简单,就是合并,比较。暴力的做法即可。

合并前的cmp的方法需要注意。还有讨论是否该合并的先后顺序需要注意。

嗯,就这样。

开始没考虑到出现断点后,后面的连续挤奶时间最大值比前面的大,导致第七个数据没有通过。后来增加了一个判断就OK了。

下面是我的代码:

#include<iostream>#include<fstream>#include<algorithm>using namespace std;int N, answer1, answer2;ifstream fin("milk2.in");ofstream fout("milk2.out");struct link{int l, r;}Time[5000];int cmp(link a, link b){return (a.l == b.l) ? (a.r <= b.r) : (a.l < b.l);}void AnswerTime(){int r, l;answer1 = Time[0].r - Time[0].l;answer2 = 0;r = Time[0].r; l = Time[0].l;for (int i = 1; i < N; ++i){if (r >= Time[i].r) continue;if (r >= Time[i].l){r = Time[i].r;if (r - l > answer1)answer1 = r - l;}else {if (answer2 < Time[i].l - r) answer2 = Time[i].l - r;r = Time[i].r; l = Time[i].l;if (answer1 < r - l) answer1 = r - l;}}fout << answer1 << " " << answer2 << endl;}int main(){fin >> N;for (int i = 0; i < N; ++i)fin >> Time[i].l >> Time[i].r;sort(Time, Time + N, cmp);AnswerTime();fin.close();fout.close();return 0;}


0 0