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


문제 설명

In a movie festival n movies will be shown. You know the starting and ending time of each movie. What is the maximum number of movies you can watch entirely?

입력  

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

After this, there are n lines that describe the movies. Each line has two integers aa and bb: the starting and ending times of a movie.

출력

Print one integer: the maximum number of movies.

입력 예

3
3 5
4 9
5 8

출력 예

2

제약조건

  • 1 <= n <= 2x10^5
  • 1 <= a < b <= 10^9

문제 풀이 내용

영화가 끝나는 시간을 기준으로 정렬한다.

영화 끝나는 시간이 다음 영화 시작 시간 전에 끝나면, 볼 수 있는 영화편수를 증가시키고, 영화 끝나는 시간을 다음 영화 시간으로 갱신한다.  

프로그램 내용

더보기
...
    vector <pair<int, int>> m_time;

    for(int idx=0; idx < n_movie; ++idx)
        int start_time, end_time; 
        m_time.push_back({end_time, start_time});

    sort(m_time.begin(), m_time.end()); /// sort by end_time 

    int c_movie=0;
    int time_now=0;
    for (int i = 0; i< n_movie; ++i)
        /// start_time > time_now 
        /// time_now = end_time, increase counter
        if (m_time[i].second >= time_now)
            time_now = m_time[i].first;
            c_movie++;
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Maximum Subarray Sum (1643)  (0) 2019.09.26
CSES 2. Sum of Two Values (1640)  (0) 2019.09.26
CSES 2. Restaurant Customers (1619)  (0) 2019.09.25
CSES 2. Concert Tickets (1091)  (0) 2019.09.25
CSES 2. Ferris Wheel (1090)  (0) 2019.09.25

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


문제 설명

You are given the arrival and leaving times of n customers in a restaurant.

What was the maximum number of customers?

입력 

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

After this, there are n lines that describe the customers. Each line has two integers a and b: the arrival and leaving times of a customer.

You may assume that all arrival and leaving times are distinct.

출력

Print one integer: the maximum number of customers.

입력 예

3
5 8
2 4
3 9

출력 예

2

제약조건

  • 1 <= n <= 2x10^5
  • 1 <= a < b <= 10^9

문제 풀이 

입력받은 시간들을 priority queue 에 저장한다.

단, 먼저 도착한 사람이 앞쪽에 나오도록 모두 음수로 만든다.

저장된 queue 의 제일 위쪽에 있는 자료를 확인해서, 도착 시간이면 +1, 떠난 시간이면 -1을 누적한다.

 

이렇게 누적한 손님 수중에서 가장 큰 값을 출력한다.

프로그램 내용

더보기
...
    priority_queue<tuple<int, bool>> c_time;

    for(int idx=0; idx < n_Customer; ++idx)
        cin >> start_time >> end_time ;
        c_time.push({-start_time, true});
        c_time.push({-end_time, false});

    int ct_now=0;
    int ct_count=0;

    while (!c_time.empty())
        ct_now += get<1>(c_time.top()) ? 1 : -1; /// start__time +1, end_time -1
        c_time.pop();
        ct_count = max(ct_count, ct_now);

	cout << ct_count << endl;

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Sum of Two Values (1640)  (0) 2019.09.26
CSES 2. Movie Festival (1629)  (0) 2019.09.26
CSES 2. Concert Tickets (1091)  (0) 2019.09.25
CSES 2. Ferris Wheel (1090)  (0) 2019.09.25
CSES 2. Apartments (1084)  (0) 2019.09.24

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


문제 설명

There are n concert tickets available, each with a certain price. Then, m customers arrive, one after another.

Each customer announces the maximum price he or she is willing to pay for a ticket, and after this, they will get a ticket with the nearest possible price such that it does not exceed the maximum price.

입력

The first input line contains integers n and m: the number of tickets and the number of customers.

The next line contains n integers h_1,h_2,,h_n: the price of each ticket.

The last line contains mm integers t_1,t_2,,t_m: the maximum price for each customer.

출력

Print, for each customer, the price that they will pay for their ticket. After this, the ticket cannot be purchased again.

입력 예

5 3
5 3 7 8 5
4 8 3


If a customer cannot get any ticket, print −1.

출력 예

3
8
-1

제약조건

  • 1 <= n,m <= 2x10^5
  • 1 <= h_i, t_i <= 10^9

문제 풀이 

티켓 가격을 multiset에 저장하고, 희망 가격으로 lower_bound를 찾는다.

그 가격보다 낮은 가격이 있으면 출력하고, 없으면 -1을 출력한다.

프로그램 내용

더보기
...
    multiset <long, greater<long>> tPrice;

    for (int in=0; in < nTicket; ++in)
        cin >> temp;
        tPrice.insert(temp);

    for (int id = 0; id < nCustomer; ++id)
        cin >> temp;
        auto low = tPrice.lower_bound(temp);
        if ( low == tPrice.end())
            cout << -1 << endl;
        else
            cout << *low << endl;
            tPrice.erase(low);
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Movie Festival (1629)  (0) 2019.09.26
CSES 2. Restaurant Customers (1619)  (0) 2019.09.25
CSES 2. Ferris Wheel (1090)  (0) 2019.09.25
CSES 2. Apartments (1084)  (0) 2019.09.24
CSES 2. Distinct Numbers (1621)  (0) 2019.09.24

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

+ Recent posts