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


문제 설명

 

Farmer John's cows keep escaping from his farm and causing mischief. To try and prevent them from leaving, he purchases a fancy combination lock to keep his cows from opening the pasture gate.

Knowing that his cows are quite clever, Farmer John wants to make sure they cannot easily open the lock by simply trying many different combinations. The lock has three dials, each numbered 1..N (1 <= N <= 100), where 1 and N are adjacent since the dials are circular. There are two combinations that open the lock, one set by Farmer John, and also a "master" combination set by the lock maker.

The lock has a small tolerance for error, however, so it will open even if the numbers on the dials are each within at most 2 positions of a valid combination.

For example, if Farmer John's combination is (1,2,3) and the master combination is (4,5,6), the lock will open if its dials are set to (1,3,5) (since this is close enough to Farmer John's combination) or to (2,4,8) (since this is close enough to the master combination). Note that (1,5,6) would not open the lock, since it is not close enough to any one single combination.

Given Farmer John's combination and the master combination, please determine the number of distinct settings for the dials that will open the lock. Order matters, so the setting (1,2,3) is distinct from (3,2,1).

입력 

Line 1: The integer N.
Line 2: Three space-separated integers, specifying Farmer John's combination.
Line 3: Three space-separated integers, specifying the master combination (possibly the same as Farmer John's combination).

출력

Line 1: The number of distinct dial settings that will open the lock.

입력 예

50 
1 2 3 
5 6 7

출력 예

249


문제 풀이 내용

 

입력받은 수에서 각 자리수들이 가능한 영역을 결정하고, 가능한 모든 3자리 수를 만들어서 set에 입력한다. 중복되는 조합은 set 특성에 의해서 없어지므로, set에 입력된 조합의 개수를 출력한다.

 

프로그램 내용

더보기
#define MAX_DIAL 100

int RANGE[5];

/// dial_num -1 -> 47, 48, 49, 50, (1), adding code value=1,
/// dial_num  -> 48, 49, 50, (1), (2),adding code value=1, 2
/// code : 1 -> (49), (50), 1, 2, 3, adding code value=dial_num, dial_num-1
/// code : 2 -> (50), 1,  2, 3, 4, adding code value = dial_num
void set_Range(int input, int dial_num);
 
int main() {

	/// Read dial number  
    fin >> dial_num;

    int f1, f2, f3;
    fin>> f1 >> f2 >> f3;

    int m1, m2, m3;
    fin>> m1 >> m2 >> m3;

    set <string> codes;

    /// build passed codes range for all codes
    vector <string> f1_code;
    vector <string> f2_code;
    vector <string> f3_code;
    vector <string> m1_code;
    vector <string> m2_code;
    vector <string> m3_code;

    /// if dial_num < 5
    /// all codes are not available.
    /// if dail_num = 1, 1^3
    /// if dail_num = 2, 2^3
    /// if dail_num = 3, 3^3
    /// if dail_num = 4, 4^3
    /// if dail_num = 5, 5^3

    /// init f_codes
    set_Range(f1, dial_num); 
    set_Range(f2, dial_num); 
    set_Range(f3, dial_num);
   
    /// insert all codes from farmers code
    for (int idx=0; idx < 5; ++idx)
    {
		...
	}

    /// init m_codes
    set_Range(m1, dial_num); 
    set_Range(m2, dial_num);
    set_Range(m3, dial_num);

    /// insert codes from master code
    for (int idx=0; idx < 5; ++idx)
    {
		...
	}

    if (dial_num < 6)
        fout << dial_num * dial_num * dial_num << endl;
    else
        fout << codes.size() << endl;

    return 0;
}

 

Chapter 1. Getting started 

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

Problem 1.4.8 Ski Course Design  (0) 2019.09.12
Problem 1.4.7 Wormholes  (0) 2019.09.12
Problem 1.4.5 Prime Cryptarithm  (0) 2019.09.12
Problem 1.4.3 Barn Repair  (0) 2019.09.12
Problem 1.4.2 Mixing Milk  (0) 2019.09.12

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


문제 설명

A cryptarithm is usually presented as a pencil-and-paper task in which the solver is required to substitute a digit for each of the asterisks (or, often, letters) in the manual evaluation of an arithmetic term or expression so that the consistent application of the digits results in a proper expression. A classic example is this cryptarithm, shown with its unique solution:

    SEND           9567       S->9 E->5 N->6 D->7

+ MORE       + 1085        M->1 O->0 R->8

   -------           -------

 MONEY          10652      Y->2

The following cryptarithm is a multiplication problem that can be solved by substituting digits from a specified set of N digits into the positions marked with *. Since the asterisks are generic, any digit from the input set can be used for any of the asterisks; any digit may be duplicated as many times as desired.

Consider using the set {2,3,5,7} for the cryptarithm below:

 * * *

 x * *

 -------

 * * * <-- partial product 1 -- MUST BE 3 DIGITS LONG

* * * <-- partial product 2 -- MUST BE 3 DIGITS LONG

-------

* * * *

Digits can appear only in places marked by `*'. Of course, leading zeroes are not allowed.

입력

Line 1:N, the number of digits that will be used

Line 2:N space separated non-zero digits with which to solve the cryptarithm

출력 

A single line with the total number of solutions. Here is the one and only solution for the sample input:

입력 예

5

2 3 4 6 8

출력 예

1


문제 풀이 내용

입력받은 수들을 set에 정리하고, 임의로 3자리수, 2자리수를 만들어서 계산을 했다. 그래서, 나오는 수들이 모두 집합에 있는지 확인해서, 있으면 (aaa, bb)를 기록해서 출력한다.

프로그램 내용

더보기
set <int> num_sets;

/// check all digit in sets
bool check_set(int input) ;

int main() {
    vector <int> used_nums;
    vector <int> aaa; /// a1a2a3
    vector <int> bb; /// b1b2b3

    /// reading used numbers
    for(int idx=0; idx < num_used; ++idx)
    {
    }

    sort(used_nums.begin(),used_nums.end()); 

    /// build aaa & bb
    for(int idx=0; idx < num_used ; ++idx)
    {
        for(int idx2=0; idx2 < num_used ; ++idx2)
        {
            for(int idx3=0; idx3 < num_used ; ++idx3)
            {
                aaa.push_back(100*used_nums[idx]+10*used_nums[idx2]+used_nums[idx3]);
            }
            bb.push_back(10*used_nums[idx]+used_nums[idx2]);
        }
    }

    vector <pair <int, int>> filtered;
    for(int idx=0; idx < aaa.size(); ++idx)
    {
        for(int idx2=0;idx2 < bb.size(); ++idx2)
        {
            int ccc = aaa[idx] * (bb[idx2]%10);
            int ddd = aaa[idx] * (bb[idx2]-(bb[idx2]%10))/10;
            int eee = aaa[idx] * bb[idx2];

            if ( ccc < 1000 && ddd < 1000 && eee < 10000)
            {
                if (check_set(ccc) && check_set(ddd) && check_set(eee))
                {
                    filtered.push_back(make_pair(aaa[idx], bb[idx2]));
                }
            }
        }
    }

    fout << filtered.size() << endl;

 

Chapter 1. Getting started

 

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

Problem 1.4.7 Wormholes  (0) 2019.09.12
Problem 1.4.6 Combination Lock  (0) 2019.09.12
Problem 1.4.3 Barn Repair  (0) 2019.09.12
Problem 1.4.2 Mixing Milk  (0) 2019.09.12
Problem 1.3.6 Dual Palindromes  (0) 2019.09.08

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


문제 설명

It was a dark and stormy night that ripped the roof and gates off the stalls that hold Farmer John's cows. Happily, many of the cows were on vacation, so the barn was not completely full.

The cows spend the night in stalls that are arranged adjacent to each other in a long line. Some stalls have cows in them; some do not. All stalls are the same width.

Farmer John must quickly erect new boards in front of the stalls, since the doors were lost. His new lumber supplier will supply him boards of any length he wishes, but the supplier can only deliver a small number of total boards. Farmer John wishes to minimize the total length of the boards he must purchase.

Given M (1 <= M <= 50), the maximum number of boards that can be purchased; S (1 <= S <= 200), the total number of stalls; C (1 <= C <= S) the number of cows in the stalls, and the C occupied stall numbers (1 <= stall_number <= S), calculate the minimum number of stalls that must be blocked in order to block all the stalls that have cows in them.

Print your answer as the total number of stalls blocked.

입력 양식

Line 1: M, S, and C (space separated)
Lines 2-C+1: Each line contains one integer, the number of an occupied stall.

출력

A single line with one integer that represents the total number of stalls blocked.

입력 예

4 50 18 
3 
4 
6 
8 
14 
15 
16 
17 
21 
25 
26 
27 
30 
31 
40 
41 
42 
43

출력 예

25


문제 풀이

소들을 순서대로 정렬한다. 제일 처음과 제일 마지막 소를 다 가릴 수 있는 긴 보드에서 시작한다. 각 소들 사이에 간격들을 계산해서 정렬한다. 가장 넓은 간격부터 긴 보드에서 제거해나가서 필요한 보드를 완성한다 

프로그램 내용

더보기
#define MAX_BOARD 50
#define MAX_STALL 200

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

    /// Read requirement
    int num_boards = 0, num_stalls =0, num_cows = 0;
    fin >> num_boards >> num_stalls >> num_cows ;

    vector <int> filled_stalls;
    vector <pair <int, int>> gap_table;

    /// reading filled stalls
    for(int idx=0; idx < num_cows; ++idx)
    {
		...
	}

    /// sorting stalls
    sort(filled_stalls.begin(),filled_stalls.end()); 

    for(int idx=1; idx < num_cows; ++idx)
    {
        gap_table.push_back(make_pair(filled_stalls[idx-1], filled_stalls[idx]-filled_stalls[idx-1]-1));
    }

    /// checked end to end
    int base_line = 0;
    base_line = filled_stalls[num_cows-1] - filled_stalls[0] +1;

    /// sort gap from longest
    sort(gap_table.begin(),gap_table.end()); 

    /// remove num_boards - 1 gaps from base_line
    for(int idx=0; idx < num_boards - 1; ++idx)
    {
        if(base_line - gap_table[idx].second > 0)
            base_line -= gap_table[idx].second;
    }

    /// result
    fout << base_line << endl;

 

Chapter 1. Getting started 

 

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

Problem 1.4.6 Combination Lock  (0) 2019.09.12
Problem 1.4.5 Prime Cryptarithm  (0) 2019.09.12
Problem 1.4.2 Mixing Milk  (0) 2019.09.12
Problem 1.3.6 Dual Palindromes  (0) 2019.09.08
Problem 1.3.5 Palindromic Squares  (0) 2019.09.08

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


문제 설명

A number that reads the same from right to left as when read from left to right is called a palindrome. The number 12321 is a palindrome; the number 77778 is not. Of course, palindromes have neither leading nor trailing zeroes, so 0220 is not a palindrome.

The number 21 (base 10) is not palindrome in base 10, but the number 21 (base 10) is, in fact, a palindrome in base 2 (10101).

Write a program that reads two numbers (expressed in base 10):

N (1 <= N <= 15)
S (0 < S < 10000)
and then finds and prints (in base 10) the first N numbers strictly greater than S that are palindromic when written in two or more number bases (2 <= base <= 10).
Solutions to this problem do not require manipulating integers larger than the standard 32 bits.

입력 양식

A single line with space separated integers N and S.

출력

N lines, each with a base 10 number that is palindromic when expressed in at least two of the bases 2..10. The numbers should be listed in order from smallest to largest.

입력 예

3 25

출력 예

26
27
28


문제 풀이 

숫자 N과 S를 읽어서, S보다 큰 수중에서 이진법~십진법으로 바꿨을때 palindrome 이 두번 이상되는 N개의 수를 작은 순서대로 출력하는 문제이다. S에서 시작되는 루프를 돌리면서, 이진법~10진법으로 변환해서 palindrome 이 되는 경우가 2번 되면, 그 숫자를 결과 목록에 추가하고, 결과 목록이 N개가 되면 출력한다. 

프로그램 내용

더보기
#define MAX_N 16
#define MAX_S 100001
#define MAX_DIGIT 21

/// 10 이상의 수를 영문자로 표시한다. ex) 12 -> C
char reVal(int num);

/// 특정 진법으로 변환한다.
char *convert_Base(char str[], int inputNum, int base );

bool check_palindrome(string input);

int main() {
    // Read Base
    int base_N = 0, base_S = 0;
    fin >> base_N >> base_S;

    vector <int> result;

    // base 2 ~ base 10 check palindrom from S
    // count == N break

    int t_count = 0;
    for (int idx = base_S+1; idx < MAX_S ; ++idx)
    {
		...
		if(t_count >= base_N)
            break;
    }

    for(auto it : result) 
        fout << it << "\n"; 

 

 

Chapter 1. Getting started

 

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

Problem 1.4.3 Barn Repair  (0) 2019.09.12
Problem 1.4.2 Mixing Milk  (0) 2019.09.12
Problem 1.3.5 Palindromic Squares  (0) 2019.09.08
Problem 1.3.4 Name That Numbers  (0) 2019.09.07
Problem 1.3.3 Transformations  (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

+ Recent posts