출처: https://train.usaco.org/usacogate


문제 설명

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.

입력 양식

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 05:00

출력 양식

A single line with two integers that represent the longest continuous time of milking and the longest idle time.

입력 예

3 
300 1000 
700 1200 
1500 2100

출력 예

900 300


문제 풀이 내용

농부들이 작업하는 시간들을 (시작시간, 끝나는 시간) 쌍으로 만들고, 시작 시간을 기준으로 정렬한다. 앞에서부터 탐색해서 다음 시작하는 시간과 끝나는 시간을 비교해서 계속 겹쳐간다. 겹쳐지지 않는 시간들 중에서 가장 긴시간과 겹쳐진 시간들에서 제일 긴시간을 찾아서 출력한다.

프로그램 내용

더보기
    vector< pair<int, int> > farmers;

    for(int idx=0; idx < n_Farmer; ++idx)
    {
        int start_time =0, end_time =0;
        fin >> start_time >> end_time ;
        farmers.push_back(make_pair(start_time, end_time));
    }

    sort(farmers.begin(),farmers.end(),compare);

    int work_time =0, work_gap=0;

    int t_start=farmers[0].first, t_end=farmers[0].second;

    for(int idx=0; idx < n_Farmer; ++idx)
    {
        int t_work=0, t_gap=0;

        if( farmers[idx].first <= t_end )
        {
            if(farmers[idx].second > t_end)
            {
                t_end = farmers[idx].second;
            }
            t_work = t_end - t_start;
        }

        else if ( farmers[idx].first > t_end )
        {
            t_gap = farmers[idx].first - t_end;
            t_work = t_end - t_start;
            t_start = farmers[idx].first;
            t_end = farmers[idx].second;
        }

        if (work_time < t_work) work_time = t_work;
        if (work_gap < t_gap) work_gap = t_gap;
    }

 

Chapter 1. Getting started

 

'USACO Training' 카테고리의 다른 글

Problem 1.3.4 Name That Numbers  (0) 2019.09.07
Problem 1.3.3 Transformations  (0) 2019.09.07
Problem 1.2.7 Broken Necklace  (0) 2019.09.07
Problem 1.2.6 Friday the Thirteenth  (0) 2019.09.07
Problem 1.2.5 Greedy Gift Givers  (0) 2019.09.07

+ Recent posts