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


문제 설명

The Merry Milk Makers company buys milk from farmers, packages it into attractive 1- and 2-Unit bottles, and then sells that milk to grocery stores so we can each start our day with delicious cereal and milk.

Since milk packaging is such a difficult business in which to make money, it is important to keep the costs as low as possible. Help Merry Milk Makers purchase the farmers' milk in the cheapest possible manner. The MMM company has an extraordinarily talented marketing department and knows precisely how much milk they need each day to package for their customers.

The company has contracts with several farmers from whom they may purchase milk, and each farmer has a (potentially) different price at which they sell milk to the packing plant. Of course, a herd of cows can only produce so much milk each day, so the farmers already know how much milk they will have available.

Each day, Merry Milk Makers can purchase an integer number of units of milk from each farmer, a number that is always less than or equal to the farmer's limit (and might be the entire production from that farmer, none of the production, or any integer in between).

Given:

The Merry Milk Makers' daily requirement of milk
The cost per unit for milk from each farmer
The amount of milk available from each farmer
calculate the minimum amount of money that Merry Milk Makers must spend to meet their daily need for milk.
Note: The total milk produced per day by the farmers will always be sufficient to meet the demands of the Merry Milk Makers even if the prices are high.

입력 

Line 1: Two integers, N and M.
The first value, N, (0 <= N <= 2,000,000) is the amount of milk that Merry Milk Makers wants per day.
The second, M, (0 <= M <= 5,000) is the number of farmers that they may buy from.
Lines 2 through M+1: The next M lines each contain two integers: Pi and Ai.
Pi (0 <= Pi <= 1,000) is price in cents that farmer i charges.
Ai (0 <= Ai <= 2,000,000) is the amount of milk that farmer i can sell to Merry Milk Makers per day.

출력

A single line with a single integer that is the minimum cost that Merry Milk Makers must pay for one day's milk.

입력 예

100 5 
5 20 
9 40 
3 10 
8 80 
6 30

출력 예

630


문제 풀이

farmer unit price 를 기준으로 정렬해서, 가격이 낮은 순으로 최대한 사들이여서 필요한 양을 맞추도록 한다.

프로그램 내용

더보기
#define MAX_MILK 2000001
#define MAX_FARMER 5001

int main() {
    ifstream fin ("milk.in");
    ofstream fout ("milk.out");

    // Read requirement
    int amounts = 0, farmers = 0;
    fin >> amounts >>farmers ;

    vector <pair<int, int>> price_table;

    // reading price table
    for(int idx=0; idx < farmers; ++idx)
    {
		...    
	}

    // sorting unit_price
    sort(price_table.begin(),price_table.end()); 

    int purchased_amount =0, total_cost =0;
    for(int idx=0; idx < farmers; ++idx)
    {
        int current_amount=0;
        int need_amount = amounts - purchased_amount;
       
        if(need_amount > 0)
        {
            if( need_amount >= price_table[idx].second )
                current_amount = price_table[idx].second;
            else if (need_amount < price_table[idx].second)
                current_amount = need_amount;
        }

        purchased_amount += current_amount;
        total_cost += current_amount*price_table[idx].first;
    }

    fout << total_cost << endl;

 

Chapter 1. Getting started

 

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

Problem 1.4.5 Prime Cryptarithm  (0) 2019.09.12
Problem 1.4.3 Barn Repair  (0) 2019.09.12
Problem 1.3.6 Dual Palindromes  (0) 2019.09.08
Problem 1.3.5 Palindromic Squares  (0) 2019.09.08
Problem 1.3.4 Name That Numbers  (0) 2019.09.07

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


문제 설명

Palindromes are numbers that read the same forwards as backwards. The number 12321 is a typical palindrome.

Given a number base B (2 <= B <= 20 base 10), print all the integers N (1 <= N <= 300 base 10) such that the square of N is palindromic when expressed in base B; also print the value of that palindromic square. Use the letters 'A', 'B', and so on to represent the digits 10, 11, and so on.

Print both the number and its square in base B.

입력 양식

A single line with B, the base (specified in base 10).

출력 

Lines with two integers represented in base B. The first integer is the number whose square is palindromic; the second integer is the square itself. NOTE WELL THAT BOTH INTEGERS ARE IN BASE B!

입력 예

10

출력 예

1 1
2 4
3 9
11 121
22 484
26 676
101 10201
111 12321
121 14641
202 40804
212 44944
264 69696


문제 풀이 내용

십진수 (1<= N <= 300) 중에서 N^2 이 이진수부터 20진수(2<=B <=20)  중에 주어진 진법으로 변환했을때 Palindrome 이 되는 모든 수를 찾아서 출력하는 것이다. N 에 대해서 루프를 돌면서, N^2 를 주어진 진법으로 바꿔서, palindrome 인지 확인하고 해당하는 idx=N을 결과값 목록에 넣어둔다. 출력하면서, N, N^2 주어진 진법으로 변환해서 출력한다.

프로그램 내용

더보기
#define MAX_BASE 21
#define MAX_NUM 301
#define MAX_DIGIT 21

/// 10진수 이상의 진법에서 사용하는 문자로 변경, ex) 11 -> B
char reVal(int num);

// Convert input number is given base 
// by repeatedly dividing it by base and taking remainder
char *convert_Base(char str[], int inputNum, int base );

bool check_palindrome(string input);
{
    bool check = false;

    if (input == string(input.rbegin(), input.rend()))
    {
        check = true;
    }
    return check;
};

int main() {
    // Read Base
    int base_Num = 0;
    fin >> base_Num;

    // Convert all N^2 with Base B -> vector <string>
    for(int idx=0; idx < MAX_NUM ; ++idx)
    {
    }

    // Convert all N with Base B -> vector <string>
    for(int idx=0; idx < result.size(); ++idx)
    {
    }

 

Chapter 1. Getting started

 

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

Problem 1.4.2 Mixing Milk  (0) 2019.09.12
Problem 1.3.6 Dual Palindromes  (0) 2019.09.08
Problem 1.3.4 Name That Numbers  (0) 2019.09.07
Problem 1.3.3 Transformations  (0) 2019.09.07
Problem 1.3.2 Milking Cow  (0) 2019.09.07

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


문제 설명

Among the large Wisconsin cattle ranchers, it is customary to brand cows with serial numbers to please the Accounting Department. The cow hands don't appreciate the advantage of this filing system, though, and wish to call the members of their herd by a pleasing name rather than saying, "C'mon, #4734, get along."

Help the poor cowhands out by writing a program that will translate the brand serial number of a cow into possible names uniquely associated with that serial number. Since the cow hands all have cellular saddle phones these days, use the standard Touch-Tone(R) telephone keypad mapping to get from numbers to letters (except for "Q" and "Z"):

          2: A,B,C     5: J,K,L    8: T,U,V
          3: D,E,F     6: M,N,O    9: W,X,Y
          4: G,H,I     7: P,R,S
Acceptable names for cattle are provided to you in a file named "dict.txt", which contains a list of fewer than 5,000 acceptable cattle names (all letters capitalized). Take a cow's brand number and report which of all the possible words to which that number maps are in the given dictionary which is supplied as dict.txt in the grading environment (and is sorted into ascending order).

For instance, the brand number 4734 produces all the following names:

GPDG GPDH GPDI GPEG GPEH GPEI GPFG GPFH GPFI GRDG GRDH GRDI
GREG GREH GREI GRFG GRFH GRFI GSDG GSDH GSDI GSEG GSEH GSEI
GSFG GSFH GSFI HPDG HPDH HPDI HPEG HPEH HPEI HPFG HPFH HPFI
HRDG HRDH HRDI HREG HREH HREI HRFG HRFH HRFI HSDG HSDH HSDI
HSEG HSEH HSEI HSFG HSFH HSFI IPDG IPDH IPDI IPEG IPEH IPEI
IPFG IPFH IPFI IRDG IRDH IRDI IREG IREH IREI IRFG IRFH IRFI
ISDG ISDH ISDI ISEG ISEH ISEI ISFG ISFH ISFI
As it happens, the only one of these 81 names that is in the list of valid names is "GREG".

Write a program that is given the brand number of a cow and prints all the valid names that can be generated from that brand number or ``NONE'' if there are no valid names. Serial numbers can be as many as a dozen digits long.

입력

A single line with a number from 1 through 12 digits in length.

출력 

A list of valid names that can be generated from the input, one per line, in ascending alphabetical order.

입력 예

4734

출력 예

GREG


문제 풀이 내용

전화번호 숫자에서 만들 수 있는 단어들중에 사전에 있는 이름들을 출력하는 문제이다. 이것을 위해서, 사전을 읽어 들이고, 단어들의 길이를 같이 기록한다. 입력 숫자열의 길이와 단어 길이를 비교해서 같은 경우에 단어들을 숫자로 변경하고, 그 숫자와 입력된 숫자를 비교한다. 사전의 크기가 별로 크지 않기 때문에, 전체 탐색을 실행하고, 두번의 숫자 비교와 한번의 숫자 변환이 시행된다. 

프로그램 내용

더보기
#define MAX_NAME 100000000000
#define MAX_DICT 50000

class Dict
{
public:
    string word;
    int word_size;
};

class Dict My_Dict[MAX_DICT];

    long long name_Num = 0;
    fin >> name_Num;
    fin.close();

    // check digits of input
    int in_len = to_string(name_Num).length();

    // reading dictionary
    // - building map <int, string> : word_length, word
    ifstream dict ("dict.txt");
    int idx=0;
    while(!dict.eof())
    {
        string word;
        int word_size =0;

        dict >> My_Dict[idx].word;
        My_Dict[idx].word_size = My_Dict[idx].word.length();         
    }

// find word_length from dictionary map 
// -> check string to number -> compare number -> build result
    vector <string> ret;
    for(int idx2=0; idx2 < idx; ++idx2)
    {
	...
	}

    if( ret.size() == 0) fout << "NONE" << endl;

    for(int i=0; i < ret.size();++i)
    {
        fout << ret[i] << endl;
    }

 

Chapter 1. Getting started

 

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

Problem 1.3.6 Dual Palindromes  (0) 2019.09.08
Problem 1.3.5 Palindromic Squares  (0) 2019.09.08
Problem 1.3.3 Transformations  (0) 2019.09.07
Problem 1.3.2 Milking Cow  (0) 2019.09.07
Problem 1.2.7 Broken Necklace  (0) 2019.09.07

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


문제 설명

A square pattern of size N x N (1 <= N <= 10) black and white square tiles is transformed into another square pattern. Write a program that will recognize the minimum transformation that has been applied to the original pattern given the following list of possible transformations:

#1: 90 Degree Rotation: The pattern was rotated clockwise 90 degrees.
#2: 180 Degree Rotation: The pattern was rotated clockwise 180 degrees.
#3: 270 Degree Rotation: The pattern was rotated clockwise 270 degrees.
#4: Reflection: The pattern was reflected horizontally (turned into a mirror image of itself by reflecting around a vertical line in the middle of the image).
#5: Combination: The pattern was reflected horizontally and then subjected to one of the rotations (#1-#3).
#6: No Change: The original pattern was not changed.
#7: Invalid Transformation: The new pattern was not obtained by any of the above methods.
In the case that more than one transform could have been used, choose the one with the minimum number above.

입력 

Line 1: A single integer, N
Line 2..N+1: N lines of N characters (each either `@' or `-'); this is the square before transformation
Line N+2..2*N+1: N lines of N characters (each either `@' or `-'); this is the square after transformation

출력

A single line containing the number from 1 through 7 (described above) that categorizes the transformation required to change from the `before' representation to the `after' representation.

입력 예

3 
@-@ 
--- 
@@- 
@-@ 
@-- 
--@

출력 예

1


문제 풀이 내용

N x N 보드를 구성하고, 그 보드를 회전시키는 문제이다. 보드를 돌렸을때 셀이 움직이는 구조를 규칙으로 만들어서, 변화된 보드와 비교해서 해당하는 변화를 찾아내서 출력한다.

프로그램 내용

더보기
bool rotate90(int org[MAX_TILE][MAX_TILE], int chg[MAX_TILE][MAX_TILE], int t_size)
 
bool rotate180(int org[MAX_TILE][MAX_TILE], int chg[MAX_TILE][MAX_TILE], int t_size)

bool rotate270(int org[MAX_TILE][MAX_TILE], int chg[MAX_TILE][MAX_TILE], int t_size)

bool reflected(int org[MAX_TILE][MAX_TILE], int chg[MAX_TILE][MAX_TILE], int t_size)

bool boardsAreEqual(int org[MAX_TILE][MAX_TILE], int chg[MAX_TILE][MAX_TILE], int t_size)

    int org[MAX_TILE][MAX_TILE];
    int refl[MAX_TILE][MAX_TILE];
    int chg[MAX_TILE][MAX_TILE];

    // reading original tiles
    for(int i = 0; i < tile_Size; ++i)
    {
	...
    }

    // reading target tiles
    for(int i = 0; i < tile_Size; ++i)
    {
	...
	}

    // reflected tiles
    for(int i = 0; i < tile_Size; ++i)
    {
	...
	}

/*
#1: 90 Degree Rotation: The pattern was rotated clockwise 90 degrees.
#2: 180 Degree Rotation: The pattern was rotated clockwise 180 degrees.
#3: 270 Degree Rotation: The pattern was rotated clockwise 270 degrees.
#4: Reflection: The pattern was reflected horizontally (turned into a mirror image of itself by reflecting around a vertical line in the middle of the image).
#5: Combination: The pattern was reflected horizontally and then subjected to one of the rotations (#1-#3).
#6: No Change: The original pattern was not changed.
#7: Invalid Transformation: The new pattern was not obtained by any of the above methods.
*/
    int result = 0;
    if(rotate90(org, chg, tile_Size)) result = 1;
    else if(rotate180(org, chg, tile_Size)) result = 2;
    else if(rotate270(org, chg, tile_Size)) result = 3;
    else if(reflected(org, chg, tile_Size)) result = 4;
    else if(rotate90(refl, chg, tile_Size) || rotate180(refl, chg, tile_Size) || rotate270(refl, chg, tile_Size)) result = 5;
    else if(boardsAreEqual(org, chg, tile_Size)) result = 6;
    else result = 7;
    fout << result << "\n";

 

Chapter 1. Getting started

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

Problem 1.3.5 Palindromic Squares  (0) 2019.09.08
Problem 1.3.4 Name That Numbers  (0) 2019.09.07
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

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

+ Recent posts