출처: https://cses.fi/problemset/task/1076


문제 설명

You are given an array of n integers. Your task is to calculate the median of each window of k elements, from left to right.

The median is the middle element when the elements are sorted. If the number of elements is even, there are two possible medians and we assume that the median is the smaller of them.

입력 

The first input line contains two integers n and k: the number of elements and the size of the window.

Then there are n integers x_1,x_2,,x_n : the contents of the array.

출력 

Print nk+1 values: the medians.

입력 예

8 3
2 4 3 5 8 1 2 1

출력 예

3 4 5 5 2 1

제약조건

  • 1 <= k <= n <= 2x10^5
  • 1 <= x_i <= 10^9

문제 풀이 내용

입력 배열을 읽어 들인다.

- 윈도우 크기가 1인 경우는 배열을 순서대로 출력한다.

- 윈도우의 크기가 배열 크기와 같은 경우에는 정렬하여 중간값을 출력한다.

 

처음에 작성한 알고리즘 - 같은 값이 여러개 있고, 그것들이 중간값인 경우에 잘못된 값을 출력한다.

배열의 앞에서부터 윈도우 크기만큼 multiset 에 넣고, 첫번째 중간값을 출력한다. 새로운 입력값(a), 현재 중간값(b), 삭제할 값(c)을 비교해서, 새로운 중간값을 출력한다.

  • 삭제할 값이 중간값과 같은 경우, 새로운 값의 크기에 따라 중간값 위치를 움직인다
    • a = b, c > b -> b* = b+1, c < b -> b* = b-1
  • 새로운 값과 삭제할 값이 다른 쪽에 위치하면 중간 값을 움직인다. 
    • a < b && c >= b -> b* = b+1,  a >= b && c < b  -> b* = b-1.

변경한 알고리즘 - median을 중심으로 커지는 것과 작아지는 2개의 priority_queue 2개를 사용한다.

입력을 median을 기준으로 작은쪽에 넣고, 양쪽 크기를 비교해서 같도록 값을 옮겨준다. 커지는 queue의 값이 median이 된다.

프로그램 내용

 

같은 값이 여러개 있고, 그것들이 중간값인 경우에 에러가 나오던 소스

더보기
...
    vector <long> num_arr(nNum);

    multiset <long> sub_arr;

    for(int idx=0; idx < nNum; ++idx)
        cin >> num_arr[idx];

    if (wSize == 1)
        for (int idx = 0; idx < nNum; ++idx) 
            cout << num_arr[idx] << " ";
        cout << endl;

        return 0;
    else if (wSize == nNum)
        sort(num_arr.begin(), num_arr.end()); 
        cout << num_arr[(nNum+1) / 2-1] << endl; 
        return 0;
    else
        for (int idx = 0; idx < wSize ; ++idx) 
            sub_arr.insert(num_arr[idx]);

        auto med = sub_arr.begin();

        /// first median
		for (int idx = 0; idx < (wSize-1)/2 ; ++idx)
            ++med;
        cout << *med << " ";

        /// moving window
        for (int idx = wSize, id=0; idx < nNum; ++idx, ++id) 
            sub_arr.insert(num_arr[idx]); 
            
            if (sub_arr.find(num_arr[id]) == med) 
                if ( num_arr[idx] < *med) 
                    --med; 
                else if ( num_arr[idx] >= *med) 
                    ++med; 
            else 
                if (num_arr[id] < *med && num_arr[idx] >= *med) 
                    ++med; 
                else if (num_arr[id] >= *med && num_arr[idx] < *med) 
                    --med; 
           
            sub_arr.erase(sub_arr.find(num_arr[id])); 
            cout << *med << " "; 
...

오름차순, 내림차순으로 priority queue 2개 만들어서 새로운 값들을 넣으면서 중간값을 출력하는 소스

더보기
...
    vector<long> num_arr(tN+1);

    priority_queue<pair<int, int>, vector<pair<int, int>>, less<pair<int, int>>> lpq;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> rpq;

    long mid = (tK+1)/2 ;
    int w_size = 0;
    for(int id=1; id <= tN;++id)
        cin >> num_arr[id];

		while (!lpq.empty() && lpq.top().second <= id - tK) lpq.pop();
		while (!rpq.empty() && rpq.top().second <= id - tK) rpq.pop();

		if (w_size < mid)
			rpq.push(make_pair(num_arr[id], id));
			auto tmp = rpq.top();
			rpq.pop();
			lpq.push(tmp);
			++w_size;
		else
			lpq.push(make_pair(num_arr[id], id));
			auto tmp = lpq.top();
			lpq.pop();
			rpq.push(tmp);

		while (!lpq.empty() && lpq.top().second <= id - tK) lpq.pop();
		while (!rpq.empty() && rpq.top().second <= id - tK) rpq.pop();

...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 3. Grid Paths (1638)  (0) 2019.12.28
CSES 2. Sliding Cost (1077)  (0) 2019.12.28
CSES 3. Removing Digits (1637)  (0) 2019.10.14
CSES 3. Coin Combinations II (1636)  (0) 2019.10.10
CSES 3. Coin Combinations I (1635)  (0) 2019.10.09

출처: https://www.acmicpc.net/problem/17404


문제 설명

1~N개의 집 칠하는데, 옆집과는 다른 색으로 칠하는데 필요한 최소 비용. 집의 배치는 원형으로 생각해서 첫집과 마지막집이 이웃이 되도록 한다.


입력

집의 수와 각각의 집을 칠하는데 필요한 비용

출력

필요한 최소 비용 

입력 예

3
26 40 83
49 60 57
13 89 99

출력 예

110

제약조건

  • 1<= N <= 1000
  • 1 <= a_i <= 1000

문제 풀이

RGB거리 문제에서 약간의 변형이 있다. 집들의 시작과 끝이 연결되어 초기조건을 한번 정하는 것으로 결정할 수 없도록 변형됐다. 기본 아이디어는 초기조건과 거기에 따른 제한 조건을 만족하는 최소의 값들을 찾어서, 비교하도록 했다.

첫집을 특정한 색으로 칠하는 경우에 그 색을 제외한 다른 색들은 아주 큰값으로 설정해서 다음번 집 계산에서 선택되지 않도록 해서 마지막 집까지 최소값을 구한다. 마지막집을 칠하는 최소값에서 첫집과 같은 색깔로 칠하는 경우는 배제하고 최소값을 구한다.  

프로그램 내용

더보기
const int INF = 987654321;
int tN;

/// 색깔별로 칠하는 최소비용을 계산한다
int minPaint(vector<tuple<int, int, int>>& p_cost, int color);

int main()
{
    cin >> tN;

    /// 각 집을 칠하는 비용 입력
    vector<tuple<int, int, int>> p_cost(tN);
    for(int id=0; id< tN; ++id)
    {
	...
	}

    int cost_r = minPaint(p_cost, 0); // first hosuse red
    int cost_g = minPaint(p_cost, 1); // first hosuse green
    int cost_b = minPaint(p_cost, 2); // first hosuse blue

  	int cost = min({cost_r, cost_g, cost_b}); 

    cout << cost << "\n";

 

관련 문제

 

RGB 거리 (1149)  

'Baekjoon Online Judge' 카테고리의 다른 글

BOJ 23970 알고리즘 수업 - 버블 정렬 3  (0) 2022.02.13
BOJ 2824 최대공약수  (0) 2021.12.03
BOJ 15686 - 치킨 배달  (0) 2020.03.25
BOJ 2903 - 중앙 이동 알고리즘  (0) 2020.01.28

출처: https://cses.fi/problemset/task/1637


문제 설명

You are given an integer n. On each step, you may subtract from it any one-digit number that appears in it.

How many steps are required to make the number equal to 0?

입력 

The only input line has an integer n.

출력

Print one integer: the minimum number of steps.

입력 예

27

출력 예

5

Explanation: An optimal solution is  27 , 20(-7), 18(-2), 10(-8), 9(-1) - 0 (-9)

제약조건

  • 1 <= n <= 10^6

문제 풀이

어떤 수의 자리수 중에서 가장 큰 숫자를 찾아서, 그 숫자들을 계속 빼주는 방법이다. 

최적의 경우의 수는 각 자리의 수를 빼서 나온 수의 경우의 수 +1 중에서 가장 작은 것이 된다. 

 

입력 N 의 크기를 생각해보면, 기록할 필요 없이 가장 큰 자리수를 찾아서 빼내고, 다시 재귀적으로 돌려도 충분할 것 같다.

프로그램 내용

더보기
...
    vector<int> DP(nNum+1, 1e9);

    DP[0] = 0;
    for (int idx=1; idx <= nNum; ++idx)
        int tmp = idx;
        while(tmp)
            int r_digit = tmp % 10;
            DP[idx] = min( DP[idx], DP[idx-r_digit] + 1);
            tmp /= 10;
...

 

Dynamic Programming link )

'CSES' 카테고리의 다른 글

CSES 2. Sliding Cost (1077)  (0) 2019.12.28
CSES 2. Sliding Median (1076)  (0) 2019.12.25
CSES 3. Coin Combinations II (1636)  (0) 2019.10.10
CSES 3. Coin Combinations I (1635)  (0) 2019.10.09
CSES 3. Minimizing Coins (1634)  (0) 2019.10.09

처음 풀이 ( link )


문제 풀이

자물쇠 숫자 3개를 tuple<int, int, int>로 처리하고, 숫자 사이의 차이를 abs 이용해서 계산한다. 다만, modulo 연산에서 -를 지원하지 않기 때문에 dial number - 2 ( modulo -2) 보다 큰 경우도 고려한다. 3중 루프를 O(N^3)이지만 최대 dial number 100 을 생각하면, 속도에 문제가 될 것 같지는 않다. 필요하다면, key number 에서 5x5x5 로 가능한 숫자 배열을 작성하고, 그 배열 숫자들로만 루프를 돌리면 좀 더 빨라질 것 같다. 중복 제거를 위해서 set 에 무조건 입력하고, 중복이 제거된 결과의 수만 조회 했는데, 입력하기 전에 조회를 하고 없으면 입력하도록 하는것도 방법이 될 수는 있을 것 같다. 효율성은 find를 하고 없으면 입력하는것이 조금은 더 좋을 것 같다.

프로그램 내용

더보기
#define MAX_DIAL 100

/// tuple<int, int, int> key vs tuple<int, int, int> dest check
bool check_distance(tuple <int, int, int> key, tuple <int, int, int> dest, int dial_num);
{
    int a, b, c;
    int x, y, z;
    tie(a,b,c) = key;
    tie(x,y,z) = dest;
    int dist1, dist2, dist3;

    dist1 = abs(a-x);    dist2 = abs(b-y);    dist3 = abs(c-z);

    if ((dist1 <= 2 || dist1 >= dial_num-2)
        && (dist2 <= 2 || dist2 >= dial_num-2)
        && (dist3 <= 2 || dist3 >= dial_num-2) )
        return true;
    else
        return false;
}

int main() {
    /// Read requirement
    int dial_num = 0;
    fin >> dial_num;

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

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

    set <tuple<int,int,int>> c_codes;

    tuple <int, int, int> f_key = make_tuple(f1, f2, f3);
    tuple <int, int, int> m_key = make_tuple(m1, m2, m3);

    for(int id1=0;id1 < dial_num ; ++id1)
        for (int id2 = 0; id2 < dial_num; ++id2)
            for(int id3= 0; id3 < dial_num; ++id3)
                tuple <int, int, int> c_key = make_tuple(id1, id2, id3);
                /// check distance 1d1 with f1/m1, id2 with f2/m2, id3 with f3/m3
                if(check_distance(f_key, c_key, dial_num))
                    c_codes.insert(c_key);
                if(check_distance(m_key, c_key, dial_num))
                    c_codes.insert(c_key);

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

 

 

Chapter 1. Getting started (link)

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


문제 설명

Farmer John has three milking buckets of capacity A, B, and C liters. Each of the numbers A, B, and C is an integer from 1 through 20, inclusive. Initially, buckets A and B are empty while bucket C is full of milk. Sometimes, FJ pours milk from one bucket to another until the second bucket is filled or the first bucket is empty. Once begun, a pour must be completed, of course. Being thrifty, no milk may be tossed out. 

Write a program to help FJ determine what amounts of milk he can leave in bucket C when he begins with three buckets as above, pours milk among the buckets for a while, and then notes that bucket A is empty.

입력 

A single line with the three integers A, B, and C.

출력

A single line with a sorted list of all the possible amounts of milk that can be in bucket C when 
bucket A is empty.

입력 예

8 9 10

출력 예

1 2 8 9 10


문제 풀이

water jug problem 이라고 불리는 물통 사이에서 물을 옮기는 문제이다. 여기서는 물통 3개를 이용하므로, 3 water jug problem이라고 할 수 있다. 시작할때 가지고 있는 물의 양(0, 0, C)에서 물통 사이에서 한번에 옮길 수 있는 6가지 경우들을 재귀적으로 검색한다. 한번 검색한 곳은 다시 검색하지 않도록 확인해서, 검색을 종료하도록 한다. 문제 조건에 따라서 물통 A가 비어 있을때 물통 C의 양을 기록해서 출력한다.

프로그램 내용

더보기
#define BUCKET_LIMIT 21

vector <int> record(BUCKET_LIMIT, 0); /// possible amount record
vector <vector <int>> visited(BUCKET_LIMIT, vector<int>(BUCKET_LIMIT,0)); /// mark visit
vector <int> capa(3); /// store bucket status

void pour(int &from, int &to, int cpfrom, int cpto);
void search(int a, int b, int c); /// check all possible case

int main() {
    int A, B, C;
    fin >> A >> B >> C;

/// initial
    /// Bucket A : 0, Bucekt B: 0, Bucket C: full
    capa[0] = A;    capa[1] = B;    capa[2] = C;

    search(0, 0, C);

 

Chapter 1. Getting started ( link )

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


문제 설명

The cows have not only created their own government but they have chosen to create their own money system. In their own rebellious way, they are curious about values of coinage. Traditionally, coins come in values like 1, 5, 10, 20 or 25, 50, and 100 units, sometimes with a 2 unit coin thrown in for good measure.
The cows want to know how many different ways it is possible to dispense a certain amount of money using various coin systems. For instance, using a system of {1, 2, 5, 10, ...} it is possible to create 18 units several different ways, including: 18x1, 9x2, 8x2+2x1, 3x5+2+1, and many others.
Write a program to compute how many ways to construct a given amount of money using supplied coinage. It is guaranteed that the total will fit into both a signed long long (C/C++) and Int64 (Free Pascal).

입력 양식

The number of coins in the system is V (1 <= V <= 25).
The amount money to construct is N (1 <= N <= 10,000).

Line 1: Two integers, V and N
Lines 2..: V integers that represent the available coins (no particular number of integers per line)

출력

A single line containing the total number of ways to construct N money units using V coins.

입력 예

3 10 
1 2 5

출력 예

10


문제 풀이

특정한 정수 집합으로 원하는 값을 만들어내는 경우의 수를 세는 문제로 coin change 문제이다. 

특정한 코인 값 c[i] =a 라고 하면, 원하는 값 target 를 만들 수 있는 방법은 이 코인이 없이 만들수 있는 경우의 수와 이 코인 값을 제외한 값을 만들수 있는 경우의 수의 합이 된다. 

  ... target - b  ... target ...
coin[i] = a ... ... ... v(target, a) ...
coin[i+1] = b ... v(target - b, b) ... v(target, b) ...

 v(target, b) = v(target, a) + v(target-b, b) 

다만, 이 경우에는 코인의 수는 제한이 없기 때문에, 코인 값의 배수들에 해당하는 값들을 모두 확인해야 한다.

참고: subset sum problem ( link )

프로그램 내용

더보기
int main()
{
    int N, target;
    fin >> N >> target;

    vector<int> coins(N,0);

    for (int id = 0; id < N; ++id) 
        fin >> coins[id]; 

    vector <long long> table(target+1,0);

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

    table[0] = 1;

    for(int id = 0; id < N; ++id) 
        for(int idn = coins[id]; idn <= target; ++idn) 
            table[idn] += table[idn-coins[id]]; 

	if( table[target] != 0) 
        fout << table[target] << '\n'; 
    else 
        fout << -1 << '\n'; 

 

Chapter 2. Bigger Challenges ( link )

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

Problem 1.4.6 Combination Lock - 2  (0) 2019.10.13
Problem 1.5.3 Mother's Milk  (0) 2019.10.12
Problem 2.2.4 Subset Sums  (0) 2019.10.10
Problem 2.1.5 Sorting A Three-Valued Sequence  (0) 2019.09.18
Problem 2.1.4 Ordered Fractions  (0) 2019.09.18

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


문제 설명

For many sets of consecutive integers from 1 through N (1 <= N <= 39), one can partition the set into two sets whose sums are identical. 

For example, if N=3, one can partition the set {1, 2, 3} in one way so that the sums of both subsets
are identical:

  • {3} and {1,2}

This counts as a single partitioning (i.e., reversing the order counts as the same partitioning and
thus does not increase the count of partitions).
If N=7, there are four ways to partition the set {1, 2, 3, ... 7} so that each partition has the same
sum:

  • {1,6,7} and {2,3,4,5}
  • {2,5,7} and {1,3,4,6}
  • {3,4,7} and {1,2,5,6}
  • {1,2,4,7} and {3,5,6}

Given N, your program should print the number of ways a set containing the integers from 1 through N can be partitioned into two sets whose sums are identical. Print 0 if there are no such ways. 


Your program must calculate the answer, not look it up from a table.

입력 

The input file contains a single line with a single integer representing N, as above.

출력 

The output file contains a single line with a single integer that tells how many same-sum partitions can be made from the set {1, 2, ..., N}. The output file should contain 0 if there are no ways to make a same-sum partition.

입력 예

7

출력 예

4


문제 풀이 내용

{1, 2, ..., N} 인 집합을 합이 같은 2개의 집합으로 나누는 경우의 수를 구하는 문제이다. 전체의 합은 N*(N+1)/2 이고 이것을 2개의 같은 값으로 나누는 것이기 때문에 N*(N+1)/4 = k. 즉, N % 4 = 0 or -1(3) 인 경우만 가능하다. 

이 경우의 수는 조건에 맞는 모든 부분집합을 찾아서 그 수를 구할 수 있다. N = 4K 인 경우는 A = { (1, 4), (5,8), ..., (4K+1, 4K+4)}, B = { (2, 3), (6,7), ... , (4K+2, 4K+3)} 의 두 집합으로 나눈뒤 한쪽의 특정한 값을 가진 수의 조합을 다른 쪽에서 같은 값을 가진 조합으로 변경해서, 다른 집합들을 찾을 수 있다. N = 4K+3 인 경우는 A = { (1,2), (5,5), ... (4K+1, 4K+2)}, B = { (0,3), (4, 7), ... , (4K, 4K+3)}으로 초기 집합을 나눌 수 있다.

 

부분 집합들을 직접 찾지 않고, 아래 같은 규칙을 이용해서 경우의 수를 세는 것도 가능하다.  다만 어떤 부분 집합이 가능한지는 알 수 없다.

 

  ... ... ... N*(N+1)/4 = K ...
{1, 2, ..., i} ... ... ... A(i, K) ...
{1, 2, ..., i+1} ... A(i+1, K-(i+1)) ... A(i+1, K) ...

A(i+1, K) 의 값은 새로운 수 (i+1)이 원하는 합을 만드는데 사용한 경우< A(i+1, K-(i+1))>와 사용하지 않는 경우<A(i, K)>의 합이 된다.  A(i+1, K) = A(i, K) + A(i+1, K-(i+1))

이 값들을 구하는데,  A(0,0) = 1. (empty set), A(k, 0) = 1(empty set) 을 가지고 시작해서 완성한다.

프로그램 내용

더보기
int main()
{
    unsigned long N;
    fin >> N;
    if( N % 4 == 1 || N % 4 == 2)
        fout << "0" << endl;

    int sum = N*(N+1) / 4;

    long long DP[800][40] = {0};
    DP[0][0] = 1;

    for (int idx1=1; idx1 <= N ; ++idx1)
        for (int idx2 = 0; idx2 <= sum ; ++idx2)     
            DP[idx2][idx1] = DP[idx2][idx1-1];
        for (int idx2 = 0; idx2 <= sum -idx1; ++idx2) 
            DP[idx2+idx][idx1] += DP[idx2][idx1-1];

	fout << DP[sum][N-1] << "\n";

 

Chapter 2. Bigger Challenges

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

Problem 1.5.3 Mother's Milk  (0) 2019.10.12
Problem 2.3.4 Money Systems  (0) 2019.10.11
Problem 2.1.5 Sorting A Three-Valued Sequence  (0) 2019.09.18
Problem 2.1.4 Ordered Fractions  (0) 2019.09.18
Problem 2.2.5 Runaround Numbers  (0) 2019.09.18

출처: https://cses.fi/problemset/task/1636


문제 설명

Consider a money system consisting of n coins. Each coin has a positive integer value. Your task is to calculate the number of distinct ordered ways you can produce a money sum xx using the available coins.

For example, if the coins are {2,3,5} and the desired sum is 9, there are 3 ways:

  • 2+2+
  • 3+3+
  • 2+2+2+3

입력 

The first input line has two integers n and x: the number of coins and the desired sum of money.

The second line has n distinct integers c_1,c_2,,c_n: the value of each coin.

출력

Print one integer: the number of ways modulo 10^9+

입력 예

3 9
2 3 5

출력 예

3

제약조건

  • 1 <= <= 100
  • 1 <= x <= 10^
  • 1 <= c_i <= 10^6

문제 풀이

특정한 값(a)을 만드는 경우의 수를 dp(a) 라고 하고, 특정한 코인의 값을 coin(b)라고 하면, 코인 coin(b)를 추가해서 a값을 완성하는 경우와 사용하지 않고 완성하는 경우의 합으로 계산할 수 있다. 

dp(a, b) = dp(a, 0) + dp(a - coin(b)) 

 

0 값을 만드는 방법은 아무것도 고르지 않는 empty set의 한가지 경우 밖에 없으므로, dp(0) = 1이 된다. 

또, dp(coin(a)) = 1, 특정 코인 1개로 표현할 수 있는 방법 1에서 다른 경우들을 완성해서 목표로 하는 값을 찾는 문제이다. 

프로그램 내용

더보기
...
    vector<int> coins(nCoin,0);
    vector<long> dp(tValue+1, 0);

    for (int idx=0; idx < nCoin; ++idx)
        cin >> coins[idx];

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

    dp[0] = 1;

    for (int idx = 0; idx < nCoin; ++idx)
        for (int id = coins[idx]; id <= tValue; ++id)
            dp[id] = (dp[id] + dp[id - coins[idx]]) % 1000000007;
...

 

Dynamic Programming link )

'CSES' 카테고리의 다른 글

CSES 2. Sliding Median (1076)  (0) 2019.12.25
CSES 3. Removing Digits (1637)  (0) 2019.10.14
CSES 3. Coin Combinations I (1635)  (0) 2019.10.09
CSES 3. Minimizing Coins (1634)  (0) 2019.10.09
CSES 3. Dynamic Programming  (0) 2019.10.09

출처: https://cses.fi/problemset/task/1635


문제 설명

Consider a money system consisting of n coins. Each coin has a positive integer value. Your task is to calculate the number of distinct ways you can produce a money sum x using the available coins.

For example, if the coins are {2,3,5} and the desired sum is 9, there are 8 ways: 

  • 2+2+
  • 2+5+
  • 5+2+
  • 3+3+
  • 2+2+2+
  • 2+2+3+
  • 2+3+2+
  • 3+2+2+2

입력 

The first input line has two integers n and x: the number of coins and the desired sum of money.

The second line has n distinct integers c_1,c_2,,c_n : the value of each coin.

출력  

Print one integer: the number of ways modulo 10^9+7

입력 예

3 9
2 3 5

출력 예

8

제약조건

  • 1 <= n <= 100 
  • 1 <= x <= 10^
  • 1 <= c_i <= 10^6

문제 풀이 

특정한 값을 만드는 경우의 수는 코인의 값을 포함하는 경우와 포함하지 않는 경우를 더하면 된다.

먼저, 초기 값으로 목표값이 0인 경우는 아무런 코인도 고르지 않는 empty set 한가지가 된다. (dp[0] = 1)  새로운 코인 값과 기존의 값이 목표값 보다 작은 모든 경우들을 합하면 목표값을 만드는 경우의 수가 된다.

 

목표값이 xValue가 될때까지 dp[]를 완성하면, dp[xValue] 이 원하는 경우의 수가 된다.

프로그램 내용

더보기
...
    vector<int> coins(nCoin);
    vector<long long> dp(xValue + 1, 0);

    for (int idx = 0; idx < nCoin; ++idx)
        cin >> coins[idx];

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

    dp[0] = 1;        /// target value == 0, empty set , 1 way

    for (int idx = 0; idx <= xValue; ++idx)
        for (int id =0; id < nCoin; ++id)
            if (idx + coins[id] <= xValue)
                dp[idx + coins[id]] += dp[idx];
                dp[idx + coins[id]] %= 1000000007;
...

 

Dynamic Programming link )

'CSES' 카테고리의 다른 글

CSES 3. Removing Digits (1637)  (0) 2019.10.14
CSES 3. Coin Combinations II (1636)  (0) 2019.10.10
CSES 3. Minimizing Coins (1634)  (0) 2019.10.09
CSES 3. Dynamic Programming  (0) 2019.10.09
CSES 2. Array Division (1085)  (0) 2019.10.09

출처: https://cses.fi/problemset/task/1634


문제 설명

Consider a money system consisting of n coins. Each coin has a positive integer value. Your task is to produce a sum of money x using the available coins in such a way that the number of coins is minimal.

For example, if the coins are {1,5,7and the desired sum is 11, an optimal solution is 5+5+1 which requires 3 coins.

입력 

The first input line has two integers n and x: the number of coins and the desired sum of money.

The second line has n distinct integers c_1,c_2,,c_n: the value of each coin.

출력  

Print one integer: the minimum number of coins. If it is not possible to produce the desired sum, print -1.

입력 예

3 11
1 5 7

출력 예

3

제약조건

  • 1 <= n <= 100
  • 1 <= x <= 10^6
  • 1 <= c_i <= 10^6

문제 풀이 

코인의 종류와 목표값을 입력 받고, 코인들의 값을 입력 받는다. 목표값이 0인 경우 최소 코인은 0개가 되고, 목표값이 특정한 코인의 값과 같은 경우에 필요한 코인 최소 개수는 1개가 된다.  목표값을 1 부터 x 까지 이동해가면서 코인들을 포함 시키는 경우들에 대해서 검사해서 값을 변경한다. dp[x] 가 원하는 값이 된다. 

(dp[target], coin[j]) check dp[target-coin[j]] >0 

  • dp[target] == initial value(-1) -> dp[target] = dp[target-coin[j]] + 1 
  • dp[target] != initial value -> compare min(dp[target], dp[target-coin[j]] +1)

프로그램 내용

더보기
...
    vector <int> coins(N);
    vector <long> dp(MAX_T+1, -1);

    for(int idx = 0; idx < N ; ++idx)
        cin >> coins[idx];
        dp[coins[idx]] = 1; // target == coin_value, minimum coin 1

    sort(coins.begin(), coins.end()); /// coin value low to high

    dp[0] = 0;  /// target = 0, no coin

    /// Compute minimum coins required for all values from 1 to target
    for (int i=1; i<=target; i++)
        /// Go through all coins smaller than i
        for (int j=0; j < N; j++)
            if (i <= coins[j] ) continue;           // skip current coin

            if ( dp[i - coins[j]] >= 0)             // check current coin use or not
                if (dp[i] == -1)                    // not updated target value
                    dp[i] = 1 + dp[i-coins[j]];
                else                                // add current coin to meet the target value
                    dp[i] = min(dp[i], 1 + dp[i-coins[j]]);
...

 

Dynamic Programming link )

'CSES' 카테고리의 다른 글

CSES 3. Coin Combinations II (1636)  (0) 2019.10.10
CSES 3. Coin Combinations I (1635)  (0) 2019.10.09
CSES 3. Dynamic Programming  (0) 2019.10.09
CSES 2. Array Division (1085)  (0) 2019.10.09
CSES 2. Subarray Divisibility (1662)  (0) 2019.10.09

+ Recent posts