출처: 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

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


문제 설명

Broken Necklace
You have a necklace of N red, white, or blue beads (3<=N<=350) some of which are red, others blue, and others white, arranged at random. Here are two examples for n=29:

                1 2                               1 2
            r b b r                           b r r b
          r         b                       b         b
         r           r                     b           r
        r             r                   w             r
       b               r                 w               w
      b                 b               r                 r
      b                 b               b                 b
      b                 b               r                 b
       r               r                 b               r
        b             r                   r             r
         b           r                     r           r
           r       r                         r       b
             r b r                             r r w
            Figure A                         Figure B
                        r red bead
                        b blue bead
                        w white bead
The beads considered first and second in the text that follows have been marked in the picture.

The configuration in Figure A may be represented as a string of b's and r's, where b represents a blue bead and r represents a red one, as follows: brbrrrbbbrrrrrbrrbbrbbbbrrrrb .

Suppose you are to break the necklace at some point, lay it out straight, and then collect beads of the same color from one end until you reach a bead of a different color, and do the same for the other end (which might not be of the same color as the beads collected before this).

Determine the point where the necklace should be broken so that the most number of beads can be collected.

Example
For example, for the necklace in Figure A, 8 beads can be collected, with the breaking point either between bead 9 and bead 10 or else between bead 24 and bead 25.

In some necklaces, white beads had been included as shown in Figure B above. When collecting beads, a white bead that is encountered may be treated as either red or blue and then painted with the desired color. The string that represents this configuration can include any of the three symbols r, b and w.

Write a program to determine the largest number of beads that can be collected from a supplied necklace.

입력 양식

Line 1: N, the number of beads
Line 2: a string of N characters, each of which is r, b, or w

출력 양식

A single line containing the maximum of number of beads that can be collected from the supplied necklace.

입력 예

29 
wwwbbrwrbrbrrbrbrwrwwrbwrwrrb

출력 예

11


문제 풀이 내용

목걸이는 원형으로 연결되어 있으므로, 시작과 끝부분을 서로 연결해서 2번의 배열 안에서만 세면 가능하다. 흰색은 어떤 색이든 연결이 되고, 빨간색과 파란색이 서로 달라지는데, 두번 바뀌기 전까지 배열을 세는 방법이다.

프로그램 내용

더보기
#define MAX_BEAD 350

    int Length = 0;
    string Beads;

        Length = Beads.length();

    int count = 0;
    int MAX = 0;
    char color;
    int flag=0;

    string ExtBeads = Beads + Beads;

    for(int idx=0; idx < Length; ++idx)
    {
        char current = ExtBeads[idx];

        if(current == 'w')
            flag = 0;
        else
            flag = 1;

        count =0;

        int idx2 = idx;
        while( flag <=2 )
        {
            while (idx2 < (Length + idx) && ( ExtBeads[idx2] == current || ExtBeads[idx2] == 'w'))
            {
                count++;
                idx2++;
            }
            flag++;
            current = ExtBeads[idx2];
        }

        if ( count > MAX ) MAX = count;
    }

 

Chapter 1. Getting started

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

Problem 1.3.3 Transformations  (0) 2019.09.07
Problem 1.3.2 Milking Cow  (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
Problem 1.2.2 Ride  (0) 2019.09.07

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


문제 설명

Is Friday the 13th really an unusual event?

That is, does the 13th of the month land on a Friday less often than on any other day of the week? To answer this question, write a program that will compute the frequency that the 13th of each month lands on Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday over a given period of N years. The time period to test will be from January 1, 1900 to December 31, 1900+N-1 for a given number of years, N. N is positive and will not exceed 400.

Note that the start year is NINETEEN HUNDRED, not NINETEEN NINETY.

There are few facts you need to know before you can solve this problem:

January 1, 1900 was on a Monday.
Thirty days has September, April, June, and November, all the rest have 31 except for February which has 28 except in leap years when it has 29.
Every year evenly divisible by 4 is a leap year (1992 = 4*498 so 1992 will be a leap year, but the year 1990 is not a leap year)
The rule above does not hold for century years. Century years divisible by 400 are leap years, all other are not. Thus, the century years 1700, 1800, 1900 and 2100 are not leap years, but 2000 is a leap year.
Do not use any built-in date functions in your computer language.

Don't just precompute the answers, either, please.

입력 양식

One line with the integer N.

출력 양식

Seven space separated integers on one line. These integers represent the number of times the 13th falls on Saturday, Sunday, Monday, Tuesday, ..., Friday.

입력 예

20

출력 예

36 33 34 33 35 35 34


문제 풀이 내용

매달 13일이 요일마다 몇번씩 있었는지 세는 문제이다. 1900. 1. 1 이 월요일에서 시작하기 때문에 첫번째 13일이 토요일이 되는 것을 기준으로 각 달이 며칠인지 더해서 계산했다.

프로그램 내용

더보기
#define BEGIN_YEAR 1900
#define FIRST_DAY 2 // Jan. 1. 1990 - Monday
/// Sat=0, Sun=1, Mon=2, Tue=3, Wed=4, Thu=5, Fri=6
#define DAYS_IN_WEEK 7
#define MONTH_IN_YEAR 12
#define MAX_IN_YEAR 400

/*
Leap Year : year % 4 == 0 && year % 100 != 100 && year %400 == 0
*/
bool LeapYear (int inYear)
{
    bool LeapFlag = false;

    if (inYear % 4 == 0) { LeapFlag = true; }
    if (inYear % 100 == 0) { LeapFlag = false; }
    if (inYear % 400 == 0) { LeapFlag = true; }

    return LeapFlag;
};

int Days = 13 + FIRST_DAY - 1; /// 15 Mon - Sat

    for (int index = 0; index < InYear ; ++index)
    {
        int year = BEGIN_YEAR + index;
        if(!LeapYear (year))
        {
            for (int idx =0; idx< MONTH_IN_YEAR ; ++idx)
            {
                ++Thirteen[Days%7];
                Days += DayInMonth[idx];
            }
        }
        else
        {
            for (int idx =0; idx< MONTH_IN_YEAR ; ++idx)
            {
                ++Thirteen[Days%7];
                Days += LeapDayInMonth[idx];
            }
        }
    }

    for (int index=0; index<DAYS_IN_WEEK ; ++index)
    {
        fout << Thirteen[index];
        if(index < 6)
            fout << " ";
    }

 

Chapter 1. Getting started

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

Problem 1.3.2 Milking Cow  (0) 2019.09.07
Problem 1.2.7 Broken Necklace  (0) 2019.09.07
Problem 1.2.5 Greedy Gift Givers  (0) 2019.09.07
Problem 1.2.2 Ride  (0) 2019.09.07
USACO Training - Chapter 1. Getting started  (0) 2019.09.06

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


문제 설명

Task 'gift1': Greedy Gift Givers

A group of NP (2 ≤ NP ≤ 10) uniquely named friends has decided to exchange gifts of money. Each of these friends might or might not give some money to some or all of the other friends (although some might be cheap and give to no one). Likewise, each friend might or might not receive money from any or all of the other friends. Your goal is to deduce how much more money each person receives than they give.

The rules for gift-giving are potentially different than you might expect. Each person goes to the bank (or any other source of money) to get a certain amount of money to give and divides this money evenly among all those to whom he or she is giving a gift. No fractional money is available, so dividing 7 among 2 friends would be 3 each for the friends with 1 left over – that 1 left over goes into the giver's "account". All the participants' gift accounts start at 0 and are decreased by money given and increased by money received.

In any group of friends, some people are more giving than others (or at least may have more acquaintances) and some people have more money than others.

Given:
a group of friends, no one of whom has a name longer than 14 characters,
the money each person in the group spends on gifts, and
a (sub)list of friends to whom each person gives gifts,
determine how much money each person ends up with.

입력 양식

Line # Contents
1 A single integer, NP
2..NP+1 Line i+1 contains the name of group member i
NP+2..end NP groups of lines organized like this:
The first line of each group tells the person's name who will be giving gifts.
The second line in the group contains two numbers:
The amount of money (in the range 0..2000) to be divided into gifts by the giver
NGi (0 ≤ NGi ≤ NP), the number of people to whom the giver will give gifts
If NGi is nonzero, each of the next NGi lines lists the name of a recipient of a gift; recipients are not repeated in a single giver's list.

출력 양식

The output is NP lines, each with the name of a person followed by a single blank followed by the net gain or loss (final_money_value - initial_money_value) for that person. The names should be printed in the same order they appear starting on line 2 of the input.

입력 예

5 
dave 
laura 
owen 
vick 
amr 
dave 
200 3 
laura 
owen 
vick 
owen 
500 1 
dave 
amr 
150 2 
vick 
owen 
laura 
0 2 
amr 
vick 
vick 
0 0

출력 예

dave 302
laura 66
owen -359
vick 141
amr -150


문제 풀이 내용

각 인원마다 선물을 주고 받은 금액을 더하고 빼줘야 한다. 다만, 나머지 부분을 주는 사람이 가지게 하면 된다.

간단하게 이름/금액을 가지는 클래스를 만들고, 이름으로 검색해서 금액을 조정해주도록 했다.

프로그램 내용

더보기
class GiftMap
{
public:
    string Names;
    int gifts;
};

class GiftMap Party[MAXPEOPLE];

/* look for name in people table */
class GiftMap* lookup(string inName)
{
    for(int i=0; i<MAXPEOPLE; ++i)
	if(inName == Party[i].Names)
	    return &Party[i];
}
...
    for(int index=0;index < size ; ++index)
    {
        string gName;
        fin >> gName;
        int amount, targets;
        fin >> amount >> targets ;

		// Reduce Giver's amount
        class GiftMap *giver;
        giver = lookup(gName);

        if(targets)
        {
            giver->gifts -= amount;
            giver->gifts += amount%targets;
        }

 

 

Chapter 1. Getting started

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

Problem 1.3.2 Milking Cow  (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.2 Ride  (0) 2019.09.07
USACO Training - Chapter 1. Getting started  (0) 2019.09.06

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


문제 설명

It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.

Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be 21 * 19 * 1 * 3 * 15 = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)

Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.

Examples:

Input Output
COMETQ  GO 
HVNGAT

ABSTAR  STAY
USACO 

입력 양식

Line 1: An upper case character string of length 1..6 that is the name of the comet.
Line 2: An upper case character string of length 1..6 that is the name of the group.

출력 양식

A single line containing either the word "GO" or the word "STAY".

입력 예

COMETQ 
HVNGAT

출력 예

GO


문제 풀이 내용

기본적인 시스템 적응 문제이다. 파일 입출력으로 자료를 읽어 들이고, 결과를 기록하면 된다. 특별한 알고리즘이 필요하지는 않고, 문제에서 지시한 내용대로 알파벳을 숫자로 변환해서, 처리하면 된다.

프로그램 내용

더보기
...
    string a, b;
    fin >> a >> b;    
...
	for(int index=0; index< a.size(); ++index)
        sum_1 *= (int)(a[index]-'A') + 1;

    for(int index=0; index< b.size(); ++index)
        sum_2 *= (int)(b[index]-'A') + 1;
... 
	/// compare sum_1 % 47 vs sum_2 % 47

 

Chapter 1. Getting started

 

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

Problem 1.3.2 Milking Cow  (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
USACO Training - Chapter 1. Getting started  (0) 2019.09.06

USACO Training Site problems ( link )

 

Chapter 1. Getting started

 

Section 1.1 Introduction

section 1.1 Text - Introduction

 

Section 1.2 Submitting Soln, Task Types, Ad Hoc 
section 1.2.1 Text - submitting solution 
section 1.2.2 prob - Your Ride is Here  (1
section 1.2.3 Text - contest problem type 

section 1.2.4 Text - ad hoc problem 

section 1.2.5 prob - Greedy Gift Givers (1) (2)

section 1.2.6 prob - Friday the Thirteenth (1) 
section 1.2.7 prob - Broken Necklace (1) (?)

 

Section 1.3 Complete Search 
section 1.3.1 Text - Complete Search
section 1.3.2 prob - Milking Cow (1)
section 1.3.3 prob - Transformations (1)
section 1.3.4 prob - Name That Numbers (1)
section 1.3.5 prob - Palindromic Squares (1)
section 1.3.6 prob - Dual Palindromes (1)


Section 1.4 Greedy, Crafting Solutions 
section 1.4.1 Text - Greedy Algorithm
section 1.4.2 prob - Mixing Milk (1)
section 1.4.3 prob - Barn Repair (1)
section 1.4.4 Text - Winning Solutions
section 1.4.5 prob - Prime Cryptarithm (1)
section 1.4.6 prob - Combination Lock (1) (2)
section 1.4.7 prob - Wormholes (1) (?)
section 1.4.8 prob - Ski Course Design (1) (?)

 

Section 1.5 More Search Techniques 

section 1.5.1 Text - More Search Techniques 

section 1.5.2 prob - Arithmetic Progressions (1)
section 1.5.3 prob - Mother's Milk (1)

 

Section 1.6 Binary Numbers

section 1.6.1 Text - Introduction to Binary Numbers 
section 1.6.2 prob - Number Triangles (1)
section 1.6.3 prob - Prime Palindromes (1)
section 1.6.4 prob - Super Prime Rib (1)

 

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

Problem 1.3.2 Milking Cow  (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
Problem 1.2.2 Ride  (0) 2019.09.07

Teaching Yourself, lesson 20를 살펴보고 있다. 

 

가야 할 곳은 아직 멀다. 기본적인 문법 부분은 다 지나갔고 STL에서 나오는 주요 template들의 기능을 살펴보는 구간이다. vector, list, map, set, ... 

 

"Guide to Competitive Programming: Learning and Improving Algorithms Through Contests" 도 주문해서 읽기 시작했다.

 

실제로 어떤 목적을 가진 코드를 작성하기 위해서, USACO Traing 도 같이 진행하고 있다.

 

아직까지 구체적으로 생각나는 아이디어를 바로 적용할 수 있는 자료구조나 알고리즘이 떠오르지는 않는다.

 

다만, '이런 식으로 알고리즘이나 자료구조를 적용할 수는 있겠구나' 이정도 느낌을 받고 있다.

 

책을 전체적으로 다 살펴본 뒤에, 머리속에 있는 내용들을 기초로 해서 다시 찾아보고 정리하면서 어떤 경우에 어떻게 적용할 수 있을지도 적어가야 겠다.

 

 

 

 

 

 

'Basic Preparation' 카테고리의 다른 글

USAMO vs USACO III  (0) 2020.04.16
USAMO vs USACO II  (0) 2020.04.09
USACO vs USAMO I  (0) 2020.04.05
Teach Yourself C++  (0) 2019.09.17
2019년 8월 진행  (0) 2019.08.24

기본적으로 어떤 내용들을 살펴봐야 하는지 자료조사를 진행했다.

 

Competition Programming 은 제한된 환경에서 효과적인 알고리즘을 구현하는 시합이라고 할 수 있다. 메모리, 시간의 제한이 있고, 대부분의 알고리즘이나 자료구조는 직접 구현하거나 언어에서 지원하는 기본적인 내용만을 사용해야 한다. 아마도 이런 이유에서 C++이 제일 선호되는 언어인지도 모른다. Java 혹은 Pascal 도 가능하고, IOI 2019 경우(https://ioi2019.az/en-content-26.html)에는 Ruby, Python 도 제공됐다. 요구되는 코딩 수준이 복잡하고 어려운 기능이 아니기 때문에, 언어에 대한 아주 깊은 수준의 이해나 공부는 필요하지 않다고 생각했다. 그래서, USACO 19-20 season이 시작되는 12월 전까지 기본적인 학습과 다른 연습들을 해보려고 한다.  

이것을 위해서 자료를 찾고, 몇개 기사들을 읽고, 실제 문제를 살펴봤다. 그리고, 진행방향을 정리했다.  

먼저, 사용할 언어는 C++로 했다. 나중에 C++17이 적용된다고 해도, 새롭게 사용할 수 있는 기능들이 꼭 필요한 문제는 없을 것이라고 생각해서, 아래의 책 3권을 골랐다.

  • 입문용: C++ in One Hour a Day, Sams Teach Yourself, 8th
  • 참고용: C++ Primer, 5th
  • 참고용: The C++ Programming Language, 4th

참고용 책 2권은 너무 많은 내용을 다루기 때문에 처음 입문용으로는 좀 분량이 많다. 1000 페이지가 넘어가는 책은 읽는 책이 아니라 찾아보는 사전같은 책이라고 생각한다. 혹시, C++을 더 능숙하게 다루는 프로그래머의 진로를 생각한다면 자세히 읽어봐야 겠지만, 그것은 여기에서 생각하는 범위 밖에 있는 것이다. C++ 컴파일러는 IOI 2019 에 나와있는 virtual box image에서 진행하려고 했는데, 컴퓨터 사양이 부족해서 cygwin g++ 로 구축했다. 손에 익숙하기는 vi 가 익숙하지만, 나중에 다른 사람들에게 설명하려고 생각하면 IDE를 골라야 한다고 생각해서 CodeBlock으로 연습중이다. 

 그 다음은 알고리즘, 자료구조에 관련된 공부 방법이다. "Introduction to Algorithms" 같은 온라인 강의를 찾을 수 있다. IOI 에서 요구하는 수준의 알고리즘만을 대상으로 생각하면, 수업 전체를 들을 필요까지는 없을 것 같다. 다 들을 수 있으면 좋겠지만, 일단 IOI Syllabus에 나온 것들을 중심으로 필요한 내용들을 들어보려고 생각한다.

마지막으로는 Competition Programming 준비이다. 관련된 책들이 여러가지 있겠지만, 아래같은 책들을 찾을 수 있었다.

 

  • Programming Challenges: The Programming Contest Training Manual by Steven S Skiena, Miguel A. Revilla
  • Competitive Programming, 3rd Edition by Steven Halim
  • Competitive Programmer’s Handbook by Antti Laaksonen
  • Guide to Competitive Programming: Learning and Improving Algorithms Through Contests by Antti Laaksonen

책들은 알고리즘과 그것을 적용하기 위한 연습문제들로 구성되어 있고, "Guide to Competitive Programming: Learning and Improving Algorithms Through Contests"이 가장 최근에 나왔고 온라인 참고자료들도 있어서 이 책으로 선정했다. 같은 저자가 작성한 "Competitive Programmer's Handbook" 은 온라인에 공개된 책으로 바로 내용을 확인 할 수 있다. 

 

지금 현재는 Teaching Yourself, lesson 12를 살펴보고 있다. 하루에 한시간정도 책을 읽고 코드를 살펴보고 있는데 생각처럼 빨리 넘길 수는 없다.

'Basic Preparation' 카테고리의 다른 글

USAMO vs USACO III  (0) 2020.04.16
USAMO vs USACO II  (0) 2020.04.09
USACO vs USAMO I  (0) 2020.04.05
Teach Yourself C++  (0) 2019.09.17
C++ 공부 - 2019. 8월  (0) 2019.09.02

+ Recent posts