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


문제 설명

There are n books, and Kotivalo and Justiina are going to read them all. For each book, you know the time it takes to read it.

They both read each book from beginning to end, and they cannot read a book at the same time. What is the minimum total time required?

입력  

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

The second line has n integers t_1,t_2,,t_n : the time required to read each book.

출력  

Print one integer: the minimum total time.

입력 예

3
2 8 3

출력 예

16

제약조건

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

문제 풀이 

가장 긴책을 읽는 동안 다른 책들을 모두 읽을 수 있으면, 가장 긴책을 읽는 시간 * 2, 아니면, 나머지 책을 읽는 시간 + 가장 긴책을 읽는 시간이 된다.

프로그램 내용

더보기
...
    for (int idx = 0; idx < nBook; idx++)
        long temp=0;
        lBook = max(lBook, temp);
        sumTime += temp;

    if ( lBook > (sumTime - lBook) )
        mTime = 2 * lBook;
    else
        mTime = sumTime;
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Sum of Four Values (1642)  (0) 2019.10.02
CSES 2. Sum of Three Values (1641)  (0) 2019.10.02
CSES 2. Factory Machines (1620)  (0) 2019.10.01
CSES 2. Room Allocation (1164)  (0) 2019.10.01
CSES 2. Traffic Lights (1163)  (0) 2019.10.01

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


문제 설명

A factory has n machines which can be used to make products. Your goal is to make a total of t products.

For each machine, you know the number of seconds it needs to make a single product. The machines can work simultaneously, and you can freely decide their schedule.

What is the shortest time needed to make tt products?

입력  

The first input line has two integers n and t: the number of machines and products.

The next line has n integers k_1,k_2,,k_n : the time needed to make a product using each machine.

출력 

Print one integer: the minimum time needed to make t products.

입력 예

3 7
3 2 5

출력 예

8

Explanation: Machine 1 makes two products, machine 2 makes four products and machine 3 makes one product

제약조건

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

문제 풀이

여러 기계를 동시에 돌려서 필요한 물건을 가장 빨리 만드는 시간을 찾는 문제이다.

가장 최악의 경우는 제일 오래 걸리는 기계가 모든 물건을 만드는 경우이고, 이것보다는 빨리 만들거라고 생각하고 이진 탐색을 한다. 특정 시간동안 만들어진 물건의 수를 확인해서 필요한 물건보다 많이 만들면 시간을 단축하고 부족하면 늘리는 방법으로 1/2 비율로 줄여나가서 필요한 물건과 같아질때 시간을 출력한다.

프로그램 내용

더보기
...
    long mtime[nMachine];

    for (int i = 0; i < nMachine; i++) cin >> mtime[i];

    sort(mtime, mtime+nMachine);

    long min_time = 0;
    long max_time = mtime[nMachine-1]*nProduct;
    long p_time = max_time;
    while(min_time <= max_time)
        long tPrd=0;
        long t_time = (min_time+max_time)/2;

        for (int idx= 0; idx < nMachine; ++idx)
            tPrd += t_time / mtime[idx];
            if ( tPrd >= nProduct)
                break;

        if ( tPrd >= nProduct)
            max_time = t_time -1;
            p_time = min(t_time, p_time);
        else if ( tPrd < nProduct)
            min_time = t_time + 1;
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Sum of Three Values (1641)  (0) 2019.10.02
CSES 2. Reading Books (1632)  (0) 2019.10.02
CSES 2. Room Allocation (1164)  (0) 2019.10.01
CSES 2. Traffic Lights (1163)  (0) 2019.10.01
CSES 2. Tasks and Deadlines (1630)  (0) 2019.09.28

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

+ Recent posts