Algorithm, Data structure/Solved Algorithmic Problem

USACO 1.2 - Milking Cows

JaykayChoi 2016. 6. 5. 19:21

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


출처: http://train.usaco.org/



1.2 section 첫 문제입니다. 3명의 농부가 5시에 일어나고 각각의 시간에 착유를 한다고 할 때 입력의 첫 번째 줄은 첫 번째 농부의 시작 시간과 끝 시간, 두 번째 줄은 두 번째 농부, 세 번째 줄은 세 번째 농부입니다. 한 농부라도 착유를 하고 있는 최대 연속 시간과, 어떤 농부도 착유를 하고 있지 않는 최대 연속 시간을 구하는 문제입니다.

1.2 는 Complete Search section 이네요. 거기에 맞게 완전 탐색으로 삽입과 동시에 정렬이 되며 중복 키를 허용하는 multimap 을 통해 풀었습니다.




my solving

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <fstream>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
 
int main() 
{
    ofstream fout("milk2.out");
    ifstream fin("milk2.in");
 
    int N;
    multimap<intint> farmers;
 
    fin >> N;
 
    for (int i = 0; i < N; i++)
    {
        int start, end;
        fin >> start >> end;
        farmers.insert(make_pair(start, end));
    }
 
    
 
    int longestContinuousTtime = 0;
    int longestIdleTime = 0;
 
    int start = 0;
    int end = 0;
 
    for (multimap<intint>::iterator it = farmers.begin(); it != farmers.end(); it++)
    {
        if (it->first >= start && it->first <= end)
        {
            if (it->second > end)
                end = it->second;
        }
        else
        {
            if (end != 0)
                longestIdleTime = max(longestIdleTime, it->first - end);
            start = it->first;
            end = it->second;
        }
 
        longestContinuousTtime = max(longestContinuousTtime, end - start);
    }
 
    fout << longestContinuousTtime << " " << longestIdleTime << endl;
 
    return 0;
}
cs