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


문제 설명

There are n children who want to go to a Ferris wheel, and your task is to find a gondola for each child.

Each gondola may have one or two children in it, and in addition, the total weight in a gondola may not exceed xx. You know the weight of every child.

What is the minimum number of gondolas needed for the children?

입력 

The first input line contains two integers n and x: the number of children and the maximum allowed weight.

The next line contains n integers p_1,p_2,,p_n: the weight of each child.

출력

Print one integer: the minimum number of gondolas.

입력 예

4 10
7 2 3 9

출력 예

3

제약조건

  • 1 <= n <= 2x1e5  
  • 1 <= x <= 1e9 
  • 1 <= p_i <= x

문제 풀이

무게를 입력받아서 정렬하고, 앞쪽(left)와 뒤쪽(right) 아이의 몸무게를 합쳐서 제한무게와 비교한다.

작으면, 곤돌라 하나에 탑승시키고(left+1, right-1), 무거우면 무거운 아이 혼자 타도록 한다.(right-1)  

프로그램 내용

더보기
...
    int nChild, weightL;
    cin >> nChild >> weightL ;

    long childWeight[nChild] = {0};

    for (int in=0; in < nChild; ++in)
        cin >> childWeight[in];

    sort(childWeight, childWeight+nChild);

    int idx=0, id = nChild-1;
    int gondola_count=0;

    while( idx <= id )
        if (childWeight[idx] + childWeight[id] > weightL) id--;
        else { idx++; id--;}
        gondola_count++;

	cout << gondola_count << endl;

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Restaurant Customers (1619)  (0) 2019.09.25
CSES 2. Concert Tickets (1091)  (0) 2019.09.25
CSES 2. Apartments (1084)  (0) 2019.09.24
CSES 2. Distinct Numbers (1621)  (0) 2019.09.24
CSES 2. Sorting and Searching  (0) 2019.09.24

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


문제 설명

There are n applicants and m free apartments. Your task is to distribute the apartments so that as many applicants as possible will get an apartment.

Each applicant has a desired apartment size, and they will accept any apartment whose size is close enough to the desired size.

입력 

The first input line has three integers n, m, and k: the number of applicants, the number of apartments, and the maximum allowed difference.

The next line contains n integers a_1,a_2,,a_n: the desired apartment size of each applicant. If the desired size of an applicant is x, he or she will accept any apartment whose size is between xk and x+k.

The last line contains mm integers b_1,b_2,,b_m: the size of each apartment.

출력

Print one integer: the number of applicants who will get an apartment.

입력 예

4 3 5
60 45 80 60
30 60 75

출력 예

2

제약조건

  • 1 <= n,m <= 2x10^5
  • 0 <= k <= 10^
  • 1 <= a_i, b_i <= 10^9

문제 풀이

아파트 크기와 원하는 크기를 입렵 받아서 작은 순서로 정렬한다.

원하는 크기와 감당할 수 있는 크기차이와 주어진 아파트의 크기를 비교해서, 가능한 방들을 출력한다.

프로그램 내용

더보기
#define MAX_N 2*100000
#define MAX_M 2*100000
#define MAX_K 1000000000
#define MAX_A 1000000000
#define MAX_B 1000000000

int main()
{
    int nApplicant, nApart, maxDiff;
    cin >> nApplicant >> nApart >> maxDiff;

    long desired[nApplicant];
    long aptSize[nApart];

    for (int idx=0; idx<nApplicant; ++idx)
        cin >> desired[idx];

    for (int idx=0; idx<nApart ; ++idx)
        cin >> aptSize[idx];

    sort(desired, desired+nApplicant);
    sort(aptSize, aptSize+nApart);

    int idx=0, id=0;
    int room_count=0;

    while(idx < nApplicant && id < nApart)
        if (desired[idx]+maxDiff < aptSize[id]) 
        	idx++;
        else if (desired[idx]-maxDiff > aptSize[id]) 
        	id++;
        else 
        	idx++; 
            id++; 
            room_count++;

	cout << room_count << endl;

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Concert Tickets (1091)  (0) 2019.09.25
CSES 2. Ferris Wheel (1090)  (0) 2019.09.25
CSES 2. Distinct Numbers (1621)  (0) 2019.09.24
CSES 2. Sorting and Searching  (0) 2019.09.24
CSES 1. Chessboard and Queens (1624)  (0) 2019.09.23

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


문제 설명

You are given a list of n integers, and your task is to calculate the number of distinct values in the list.

입력 양식

The first input line has an integer n: the number of values.

The second line has n integers x_1,x_2,,x_

출력

Print one integers: the number of distinct values.

입력 예

5
2 3 2 2 3

출력 예

2

제약조건

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

문제 풀이 내용

입력을 읽어 들여서 set에 입력하여 중복을 제거하고,  set size를 출력한다.

프로그램 내용

더보기
...
    set <long> distinct;

    for (int idx=0; idx<nInput; ++idx)
        distinct.insert(numbers);

	cout << distinct.size() << endl;

 

Sorting and Searching ( link )

'CSES' 카테고리의 다른 글

CSES 2. Ferris Wheel (1090)  (0) 2019.09.25
CSES 2. Apartments (1084)  (0) 2019.09.24
CSES 2. Sorting and Searching  (0) 2019.09.24
CSES 1. Chessboard and Queens (1624)  (0) 2019.09.23
CSES 1. Apple Division (1623)  (0) 2019.09.23
  1. Distinct Numbers (1)
  2. Apartments  (1)
  3. Ferris Wheel  (1)
  4. Concert Tickets  (1)
  5. Restaurant Customers  (1)
  6. Movie Festival  (1)
  7. Sum of Two Values (1)
  8. Maximum Subarray Sum (1)
  9. Stick Lengths (1)
  10. Missing Coin Sum
  11. Collecting Numbers
  12. Collecting Numbers II
  13. Playlist (1)
  14. Towers (1)
  15. Traffic Lights (1
  16. Josephus Problem I
  17. Josephus Problem II
  18. Nested Ranges Check
  19. Nested Ranges Count
  20. Room Allocation (1)
  21. Factory Machines (1)
  22. Tasks and Deadlines (1)
  23. Reading Books (1)
  24. Sum of Three Values (1)
  25. Sum of Four Values (1)
  26. Nearest Smaller Values (1)
  27. Subarray Sums I (1)
  28. Subarray Sums II (1)
  29. Subarray Divisibility (1
  30. Subarray Distinct Values
  31. Array Division (1)
  32. Sliding Median (1)
  33. Sliding Cost (1)
  34. Movie Festival II (1)
  35. Maximum Subarray Sum II (1

 

CSES Problem Set ( link

'CSES' 카테고리의 다른 글

CSES 2. Apartments (1084)  (0) 2019.09.24
CSES 2. Distinct Numbers (1621)  (0) 2019.09.24
CSES 1. Chessboard and Queens (1624)  (0) 2019.09.23
CSES 1. Apple Division (1623)  (0) 2019.09.23
CSES 1. Creating Strings I (1622)  (0) 2019.09.23

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


문제 설명

Your task is to place eight queens on a chessboard so that no two queens are attacking each other. As an additional challenge, each square is either free or reserved, and you can only place queens on the free squares. However, the reserved squares do not prevent queens from attacking each other.

How many possible ways are there to place the queens?

입력

The input has eight lines, and each of them has eight characters. Each square is either free (.) or reserved (*).

출력

Print one integer: the number of ways you can place the queens.

입력 예

........
........
..*.....
........
........
.....**.
...*....
........

출력 예

65


문제 풀이 

NxN보드에서 N개의 Queen을 서로 공격하지 않도록 배열하는 N-Queen 문제이다. 첫번째 열부터 퀸을 하나 배치하고, 공격 받을 수 있는 위치들을 표시하고 8번째 열에 도착하면 경우의 수를 기록한다.

프로그램 내용

더보기
/// n-th queen location check
int backtrack(vector<string> board, int nQueen )
{
	if(nQueen == 8)
        return 1;

	int ans=0;
	for (int i = 0; i < 8; ++i)
	{
		if(board[nQueen][i]=='.'){
			vector<string> n_board = board;
			for (int j = nQueen; j < 8; ++j) /// only check below rows
			{
				n_board[j][i]='*';
				if(i-j+nQueen>=0)
					n_board[j][i-(j-nQueen)]='*'; /// diagonal
				if(i+j-nQueen<8)
					n_board[j][i+(j-nQueen)]='*'; /// diagonal
			}
			ans += backtrack(n_board,nQueen+1);   /// updated board , next row
		}
	}
	return ans;
}

int main()
{
    vector <string> board;

    for (int i = 0; i < 8; i++)
    {
        string tmp;
        cin >> tmp;
        board.push_back(tmp);
    }

    int ways = backtrack(board, 0);

 

Introductory problems ( link )

'CSES' 카테고리의 다른 글

CSES 2. Distinct Numbers (1621)  (0) 2019.09.24
CSES 2. Sorting and Searching  (0) 2019.09.24
CSES 1. Apple Division (1623)  (0) 2019.09.23
CSES 1. Creating Strings I (1622)  (0) 2019.09.23
CSES 1. Palindrome Reorder (1755)  (0) 2019.09.23

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


문제 설명

There are n apples with known weights. Your task is to divide the apples into two groups so that the difference between the weights of the groups is minimal.

입력

The first input line has an integer n: the number of apples.

The next line has n integers p_1,p_2,,p_n: the weight of each apple.

출력

Print one integer: the minimum difference between the weights of the groups.

입력 예

5
3 2 7 4 1

출력 예

1

제약조건

  • 1 <= n <= 20
  • 1 <= p_i <= 10^9

문제 풀이

입력받은 사과들을 양쪽에 각각 넣어보고 무게 차의 최소 값을 찾는다.

프로그램 내용

더보기
long ans = 1e18;

void search_diff(int a, long b, vector<int> weight)
{
    if (a == weight.size()) {
        ans = min(ans, abs(b));
        return;
    }
    search_diff(a+1,b+weight[a], weight);	/// add apple to side A
    search_diff(a+1,b-weight[a], weight);	/// add apple to side B
}

int main()
{
    int N;		/// number of apple

    vector<int> weight(N,0);
    for(int idx=0; idx<N ; ++idx)
        cin >> weight[idx];

    search_diff(0,0, weight);

    cout << ans << endl;

 

Introductory problems ( link )

'CSES' 카테고리의 다른 글

CSES 2. Sorting and Searching  (0) 2019.09.24
CSES 1. Chessboard and Queens (1624)  (0) 2019.09.23
CSES 1. Creating Strings I (1622)  (0) 2019.09.23
CSES 1. Palindrome Reorder (1755)  (0) 2019.09.23
CSES 1. Coin Piles (1754)  (0) 2019.09.23

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


문제 설명

Given a string, your task is to generate all different strings that can be created using its characters.

입력 

The only input line has a string of length n. Each character is between a–z.

출력

First print an integer k: the number of strings. Then print k lines: the strings in alphabetical order.

입력 예

aabac

출력 예

20
aaabc
aaacb
aabac
aabca
aacab
aacba
abaac
abaca
abcaa
acaab
acaba
acbaa
baaac
baaca
bacaa
bcaaa
caaab
caaba
cabaa
cbaaa

제약조건

1 n 8


문제 풀이 내용

문자열을 읽어 들인다음, 정렬한다. next_permutation() 기능을 이용해서 새로운 문자열을 만들고 set<string>에 저장한다. set에 저장된 문자열 개수와 문자열들을 출력한다.

프로그램 내용

더보기
int main()
{
    cin >> in_str;

    set <string> out_str;

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

    do {
        out_str.insert(in_str);
    } while (next_permutation(in_str.begin(), in_str.end()));

    cout << out_str.size() << endl;
    for (auto it : out_str)  
	    cout << it << endl;

 

Introductory problems ( link )

'CSES' 카테고리의 다른 글

CSES 1. Chessboard and Queens (1624)  (0) 2019.09.23
CSES 1. Apple Division (1623)  (0) 2019.09.23
CSES 1. Palindrome Reorder (1755)  (0) 2019.09.23
CSES 1. Coin Piles (1754)  (0) 2019.09.23
CSES 1. Trailing Zeros (1618)  (0) 2019.09.23

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


문제 설명

You have two coin piles containing a and b coins. On each move, you can either remove one coin from the left pile and two coins from the right pile, or two coins from the left pile and one coin from the right pile.


Your task is to efficiently find out if you can empty both the piles.

입력

The first input line has an integer t: the number of tests.

After this, there are t lines, each of which has two integers a and b: the numbers of coins in the piles.

출력

For each test, print "YES" if you can empty the piles and "NO" otherwise.

입력 예

3
2 1
2 2
3 3

출력 예

YES
NO
YES

제약조건

  • 1 <= t <= 10^5
  • 0 <= a,b <= 10^9

문제 풀이

두개의 입력 a, b를 이용해서 가능한 조건들을 검사한다.

먼저, 한번에 제거 가능한 숫자는 3개 이므로, 두개의 합이 3의 배수가 아니면 불가능하다. 왼쪽에서 2개 제거하는 수를 x, 오른쪽에서 2개 제거하는 수를 y로 해서 계산한다.

더할 수는 없으므로 하나라도 음수이면 불가능하다. (x < 0 || y <0)

한쪽의 입력이 다른 쪽의 2배보다 크면 불가능하다. (a > 2b || 2a < b)

두 입력의 차가 abs(a-b) = abs(x-y) 이면, 모두 없애는게 가능하므로, 이 조건까지 확인해서 결과를 출력한다.  

프로그램 내용

더보기
#define MAX_T 100000
#define MAX_P 1000000000

int main()
{
    int a, b;
    int x, y;

	cin >> a >> b;
	x = (2*a-1*b)/3;
	y = (2*b-1*a)/3;

	if ((a+b) % 3 == 0)
		if ( a > 2*b || 2*a < b )
			cout << "NO" << endl;
		else if ( x < 0 || y < 0)
			cout << "NO" << endl;
		else if ( abs(a-b) == abs(x-y) )
        	cout << "YES" << endl;

        else
            cout << "NO" << endl;
    }
}

 

Introductory problems ( link )

'CSES' 카테고리의 다른 글

CSES 1. Creating Strings I (1622)  (0) 2019.09.23
CSES 1. Palindrome Reorder (1755)  (0) 2019.09.23
CSES 1. Trailing Zeros (1618)  (0) 2019.09.23
CSES 1. Bit Strings (1617)  (0) 2019.09.22
CSES 1. Two Knights (1072)  (0) 2019.09.22

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


문제 설명

Your task is to calculate the number of trailing zeros in the factorial n!n!.

For example, 20!=2432902008176640000 and it has 4 trailing zeros.

입력

The only input line has an integer n.

출력 양식

Print the number of trailing zeros in n!.

입력 예

20

출력 예

4

제약조건

1 <= n <= 10^9


문제 풀이

팩토리얼에서 뒤에 나오는 0의 갯수는 N보다 작은 수중에서 곱해지는 5나 5의 거듭제곱수들이 몇번인가와 같다. 그래서, 5로 계속 나누면서 나오는 수들을 누적해서 출력한다. 엄밀하게는 2와 2의 거듭제곱수들의 빈도수와 비교해야 한다.

프로그램 내용

더보기
#define MAX_N 1000000000

int main()
{
    int N;
    cin >> N; 

    /// count number of 5 less than N
    int count_5=0;
    int div=1;
    long base = N;

    while(div != 0)
        div = base / 5;
        count_5 += div;
        base = div;

	cout << count_5 << endl;

 

Introductory problems ( link )

'CSES' 카테고리의 다른 글

CSES 1. Palindrome Reorder (1755)  (0) 2019.09.23
CSES 1. Coin Piles (1754)  (0) 2019.09.23
CSES 1. Bit Strings (1617)  (0) 2019.09.22
CSES 1. Two Knights (1072)  (0) 2019.09.22
CSES 1. Two Sets (1092)  (0) 2019.09.21

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


문제 설명

Your task is to divide the numbers 1,2,,n into two sets of equal sum.

입력 양식

The only input line contains an integer n.

출력

Print "YES", if the division is possible, and "NO" otherwise.

After this, if the division is possible, print an example of how to create the sets. First, print the number of elements in the first set followed by the elements themselves in a separate line, and then, print the second set in a similar way.

입력 예

Example 1.

7

 

Example 2.

6

출력 예

Example 1.

YES
4
1 2 4 7
3
3 5 6

 

Example 2.

NO

제약조건

1 <= n  <= 1e6


문제 풀이

입력받은 n 이 4k 혹은 4k+3 인 경우에만 YES가 된다. ( (n+1)*n/2/2 == 0 ) n이 4k+3 형태인 경우와 4k 형태인 경우로 나누고, 4개 혹은 3개 그룹을 같도록 나누어서 출력한다.

프로그램 내용

더보기
#define MAX_N 1000000

int main()
{
    long long N;
    long long K;

    cin >> N;

    if ( (N+1)*N/2 % 2 != 0 )
        cout << "NO" << endl;

    if ( (N+1)*N/2 % 2 == 0 )
        cout << "YES" << endl;
        /// N = 4k + 3
        /// 2(k+1) ,
        /// 0, 3, 4, 7, ...
        if ( N % 4 == 3)
            K = (N+1) / 4;
            cout << 2*K -1 << endl;
            for (int i=0; i< K; i++)
                if ( i == 0)
                    cout << 4*i + 3 << " ";
                else
                    cout << 4*i << " " << 4*i + 3 << " ";
        /// 2(k+1)-1,
        /// 4k+2, 4k+1, 4(k-1)+2, 4(k-1)+1, ...
        /// 1, 2, 5, 6, ...
            cout << 2*K << endl;
            for (int i=1; i<= K; i++)
                cout << 4*(i-1)+1 << " " << 4*(i - 1) +2 << " ";

        if ( N % 4 == 0)
            K = N / 4;
            /// N = 4k
            /// 2(k+1) ,
            /// 1, 4, 5, 8, ...
            cout << 2*K << endl;
            for (int i=1; i<= K; i++)
                cout << 4*(i-1) + 1 << " " << 4*i << " ";

			/// N = 4k + 3
            /// 2(k+1) ,
            /// 2, 3, 6, 7, ...
            cout << 2*K << endl;
            for (int i=1; i<= K; i++)
                cout << 4*(i-1)+2 << " " << 4*(i - 1) +3 << " ";

 

Introductory problems ( link )

'CSES' 카테고리의 다른 글

CSES 1. Bit Strings (1617)  (0) 2019.09.22
CSES 1. Two Knights (1072)  (0) 2019.09.22
CSES 1. Number Spiral (1071)  (0) 2019.09.21
CSES 1. Permutations (1070)  (0) 2019.09.19
CSES 1. Increasing Array (1094)  (0) 2019.09.19

+ Recent posts