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


문제 설명

There is a large hotel, and n customers will arrive soon. Each customer wants to have a single room.

You know each customer's arrival and departure day. Two customers can stay in the same room if the departure day of the first customer is earlier than the arrival day of the second customer.

What is the minimum number of rooms that are needed to accommodate all customers? And how can the rooms be allocated?

입력 양식

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

Then there are n lines, each of which describes one customer. Each line has two integers a and b: the arrival and departure day.

출력

Print first an integer kk: the minimum number of rooms required.

After that, print a line that contains the room number of each customer in the same order as in the input. The rooms are numbered 1,2,,

입력 예

3
1 2
2 4
4 4

출력 예

2
1 2 1

제약조건

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

문제 풀이 내용

도착일, 출발일과 몇번째 손님인지 저장해서, 도착일 순으로 정렬한다.

출발일과 몇개의 방이 사용중인지 priority queue 에 저장하고, 가장 빠른 출발일과 새로운 도착일을 비교해서 사용중인 방의 수를 변경한다.

프로그램 내용

더보기
...
    vector <tuple<int, int, int>> in_schedule;

    for (int idx = 0; idx < nCus; idx++)
        in_schedule.push_back(make_tuple(arr, dep, idx));

    priority_queue <pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> > room_q;
    vector <int> nRoom(nCus);

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

    for (auto it = in_schedule.begin(); it != in_schedule.end(); it++)
        int arr, dep, cust_id, current;
        tie(arr, dep, cust_id) = *it;

        if (room_q.empty() || get<0>(room_q.top()) >= arr)
            current = ++room_count;                 /// used room number increase
        else
            current = get<1>(room_q.top());         /// used room number remove
            room_q.pop();

        room_q.push(make_pair(dep, current));      /// depature day, customer
        nRoom[cust_id] = current;                  /// current used room
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Reading Books (1632)  (0) 2019.10.02
CSES 2. Factory Machines (1620)  (0) 2019.10.01
CSES 2. Traffic Lights (1163)  (0) 2019.10.01
CSES 2. Tasks and Deadlines (1630)  (0) 2019.09.28
CSES 2. Towers (1073)  (0) 2019.09.28

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


문제 설명

There is a street of length x whose positions are numbered 0,1,,x. Initially, there are no traffic lights, but n sets of traffic lights are added to the street one after another.

Your task is to calculate the length of the longest passage without traffic lights after each addition.

입력 양식

The first input line contains two integers x and n: the length of the street and the number of sets of traffic lights.

Then, the next line contains n integers p_1,p_2,,p_n : the position of each set of traffic lights. Each position is distinct.

입력 예

8 3
3 6 2

출력 양식

Print the length of the longest passage without traffic lights after each addition.

출력 예

5 3 3

제약조건

  • 1 x 10^9
  • 1 n 2x10^^5
  • 0 < p_i < x

문제 풀이 내용

입력받은 가로등 위치를 set에 입력하고, 원래 있던 가로등 위치에서 가장 가까운 가로등 위치를 찾아서 간격을 계산한다. 

프로그램 내용

더보기
...
    while(nLight--)
    {
        long temp;
        cin >> temp;

        auto it = street.lower_bound(make_tuple(temp,0));
        int pre, cur;
        tie(pre, cur) = *it;

        street.erase(it);
        street.insert(make_tuple(temp, cur-(pre-temp)));
        street.insert(make_tuple(pre, pre-temp));

        t_street.erase(make_tuple(cur,pre));
        t_street.insert(make_tuple(cur-(pre-temp), temp));
        t_street.insert(make_tuple(pre-temp, pre));

        cout << get<0>(*t_street.rbegin());
        if ( nLight > 0 ) cout << " " ;
    }
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Factory Machines (1620)  (0) 2019.10.01
CSES 2. Room Allocation (1164)  (0) 2019.10.01
CSES 2. Tasks and Deadlines (1630)  (0) 2019.09.28
CSES 2. Towers (1073)  (0) 2019.09.28
CSES 2. Playlist (1141)  (0) 2019.09.28

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


문제 설명

You have to process n tasks. Each task has a duration and a deadline, and you will process the tasks in some order one after another. Your reward for a task is df where d is its deadline and f is your finishing time. (The starting time is 0, and you have to process all tasks even if a task would yield negative reward.)

What is your maximum reward if you act optimally?

입력 

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

After this, there are n lines that describe the tasks. Each line has two integers a and d: the duration and deadline of the task.

출력

Print one integer: the maximum reward.

입력 예

3
6 10
8 15
5 12

출력 예

2

제약조건

  • 1 <= <= 2x10^5
  • 1 <= a,<= 10^6

문제 풀이 

입력받은 업무를 필요 시간을 기준으로 정렬한다.

일은 같이 진행할 수 없기 때문에 전체 업무를 끝내는 시간은 필요 시간 전체의 합으로 고정되어 있으므로, 보상이 큰 일을 먼저 하도록 한다. 필요시간이 짧은 순서로 보상을 계산하기 위해서, 처음부터 진행한 시간과 보상을 기록해서 출력한다.

프로그램 내용

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

    for (int idx = 0; idx < nTask; idx++)
        t_list.push_back({t_start, t_end});

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

    long reward = 0, t_now=0;

    for (int idx = 0; idx < nTask; idx++)
        reward += t_list[idx].second - (t_list[idx].first + t_now);
        t_now += t_list[idx].first;
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Room Allocation (1164)  (0) 2019.10.01
CSES 2. Traffic Lights (1163)  (0) 2019.10.01
CSES 2. Towers (1073)  (0) 2019.09.28
CSES 2. Playlist (1141)  (0) 2019.09.28
CSES 2. Stick Lengths (1074)  (0) 2019.09.26

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


문제 설명

You are given n cubes in a certain order, and your task is to build towers using them. Whenever two cubes are one on top of the other, the upper cube must be smaller than the lower cube.

You must process the cubes in the given order. You can always either place the cube on top of an existing tower, or begin a new tower. What is the minimum possible number of towers?

입력 

The first input line contains an integer n: the number of cubes.

The next line contains n integers k_1,k_2,,k_n: the sizes of the cubes.

출력

Print one integer: the minimum number of towers.

입력 예

5
3 8 2 1 5

출력 예

2

제약조건

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

문제 풀이 

몇개의 탑이 있고, 그 마지막값이 얼마인지 검색하는 문제이다.

입력받은 블럭의 크기보다 마지막 값이 큰 탑이 있는지 검색하고, 있으면 새로운 블럭 크기로 바꾸고, 없으면 새로운 탑을 만든다. 입력이 끝나면, 탑의 수를 출력한다.

프로그램 내용

더보기
...
    multiset <long> tower;

	cin >> temp;
	auto it = tower.lower_bound(temp+1);
	if ( it == tower.end()) 		/// need new tower
    	tower.insert(temp);
	else		/// replace top value
		tower.erase(it);
		tower.insert(temp);
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Traffic Lights (1163)  (0) 2019.10.01
CSES 2. Tasks and Deadlines (1630)  (0) 2019.09.28
CSES 2. Playlist (1141)  (0) 2019.09.28
CSES 2. Stick Lengths (1074)  (0) 2019.09.26
CSES 2. Maximum Subarray Sum (1643)  (0) 2019.09.26

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


문제 설명

You are given a playlist of a radio station since its establishment. The playlist has a total of n songs.

What is the longest sequence of successive songs where each song is unique?

입력

The first input line contains an integer n: the number of songs.

The next line has n integers k)1,k_2,,k_n: the id number of each song.

출력 

Print the length of the longest sequence of unique songs.

입력 예

8
1 2 1 3 2 7 4 2

출력 예

5

제약조건

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

문제 풀이 내용

입력받은 노래 목록을 set에 저장하며 중복목록을 확인한다. 중복목록이 나오면, 중복목록이 나오기 전에 있는 목록들을 지운다. 

노래 목록이 끝나면, set의 크기를 출력한다.

프로그램 내용

더보기
...
    long num_array[nSong] = {0};

    for (int idx = 0; idx < nSong; idx++)
        cin >> num_array[idx];

    set <int> slist;

    int id=0, idx=0;
    int sCount=0;

    while (idx < nSong)
        if ( slist.count(num_array[idx]))
            sCount = max(sCount, idx-id);
            while( num_array[id] != num_array[idx])
                slist.erase(num_array[id]);
                id++;
            id++;
        else
            slist.insert(num_array[idx]);
        idx++;

        sCount = max(sCount, idx-id);
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Tasks and Deadlines (1630)  (0) 2019.09.28
CSES 2. Towers (1073)  (0) 2019.09.28
CSES 2. Stick Lengths (1074)  (0) 2019.09.26
CSES 2. Maximum Subarray Sum (1643)  (0) 2019.09.26
CSES 2. Sum of Two Values (1640)  (0) 2019.09.26

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


문제 설명

There are n sticks with some lengths. Your task is to modify the sticks so that each stick has the same length.

You can either lengthen and shorten each stick. Both operations cost x where x is the difference between the new and original length.

What is the minimum total cost?

입력  

The first input line contains an integer n: the number of sticks.

Then there are n integers: p_1,p_2,,p_n: the lengths of the sticks.

출력  

Print one integer: the minimum total cost.

입력 예

5
2 3 1 5 2

출력 예

5

제약조건

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

문제 풀이 내용

입력받은 막대 길이를 정렬하고, median 값을 기준으로 비용을 계산한다.

프로그램 내용

더보기
...
    for (int idx = 0; idx < nStick; idx++)
        cin >> num_array[idx];

    sort(num_array, num_array+nStick);

    long target = num_array[nStick/2];
    long long sum = 0;

    for(int idx=0; idx < nStick; ++idx)
        sum += abs(target - num_array[idx]);
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Towers (1073)  (0) 2019.09.28
CSES 2. Playlist (1141)  (0) 2019.09.28
CSES 2. Maximum Subarray Sum (1643)  (0) 2019.09.26
CSES 2. Sum of Two Values (1640)  (0) 2019.09.26
CSES 2. Movie Festival (1629)  (0) 2019.09.26

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


문제 설명

Given an array of n integers, your task is to find the maximum sum of values in a contiguous, nonempty subarray.

입력 

The first input line has an integer n: the size of the array.

The second line has n integers x_1, x_2,,x_n: the array values.

출력 

Print one integer: the maximum subarray sum.

입력 예 

8
-1 3 -2 5 3 -5 2 2

출력 예

9

제약조건

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

문제 풀이

배열에 값을 읽어들이면서, 부분합(1~ k) 을 기록한다.

새로운 배열값과 부분합을 비교해서 최대값을 기록한다.

프로그램 내용

더보기
...
    long num_array[nNum] = {0};
    long best = -1000000007, sum = -1000000007;

    for (int idx = 0; idx < nNum; idx++)
        cin >> num_array[idx];
        sum = max(num_array[idx],sum+num_array[idx]);
        best = max(best,sum);

...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Playlist (1141)  (0) 2019.09.28
CSES 2. Stick Lengths (1074)  (0) 2019.09.26
CSES 2. Sum of Two Values (1640)  (0) 2019.09.26
CSES 2. Movie Festival (1629)  (0) 2019.09.26
CSES 2. Restaurant Customers (1619)  (0) 2019.09.25

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


문제 설명

You are given an array of n integers, and your task is to find two values (at distinct positions) whose sum is x.

입력 

The first input line has two integers n and x: the array size and the target sum.

The second line has n integers a_1,a_2,,a_n : the array values.

출력 

Print two integers: the positions of the values. If there are several solutions, you may print any of them. If there are no solutions, print IMPOSSIBLE.

입력 예

4 8
2 7 5 1

출력 예

2 4

제약조건

  • 1 <= n <= 2x10^5
  • 1 <= x, a_i <= 10^9

문제 풀이 

입력받은 문자열의 값과 위치를 저장하고, 값을 기준으로 정렬한다.

양쪽에서 출발해서 맞는 값을 찾는다.

작은 값(left)과 큰 값(right)을 더해서 원하는 값과 비교해서 작으면 (left++), 값이 더 크면 (right--) 진행한다.  

답이 있는면 위치를 출력하고,  해당하는 값이 없는 경우 IMPOSSIBLE 출력한다.

프로그램 내용

더보기
...
    vector <pair <long, long> > num_arr;

    for(int idx=0; idx < nNum; ++idx)
        int temp;
        num_arr.push_back({temp, idx});

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

    int idx=0, id = nNum-1;			// double pointer
    while( idx < id )
        int k = num_arr[idx].first + num_arr[id].first;

        if (k == tSum)
            cout << num_arr[idx].second + 1 << " " << num_arr[id].second + 1 << endl;
        else if ( k < tSum ) idx++;
        else id--;

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Stick Lengths (1074)  (0) 2019.09.26
CSES 2. Maximum Subarray Sum (1643)  (0) 2019.09.26
CSES 2. Movie Festival (1629)  (0) 2019.09.26
CSES 2. Restaurant Customers (1619)  (0) 2019.09.25
CSES 2. Concert Tickets (1091)  (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

+ Recent posts