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


문제 설명

Given an array of n integers, your task is to find the maximum sum of values in a contiguous subarray with length between a and b.

입력 

The first input line has three integers n, a and b: the size of the array and the minimum and maximum subarray length.

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

출력 

Print one integer: the maximum subarray sum.

입력 예

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

출력 예

8

제약조건

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

문제 풀이 내용

입력을 받으면서, prefix sum을 계산한다. 특정한 구간 array[a] ~ array[b]의 합은 presum[b+1] - presum[a]를 통해서 구할 수 있다. subarray 길이에 따라서 값을 계산하도록 한다. 처음 알고리즘에서는 길이의 차가 5000이 넘어가면 제한시간에 걸렸다.

알고리즘 수정

prefix sum을 이용해서 읽어 들이면서, prefix sum의 위치가 a 보다 크면 multiset 에 prefix sum 값을 입력하고, 위치가 b 보다 커지면, 그 값들은 multiset에서 제외 시킨다. 부분합을 관리하는 방법은 queue, deque, priority queue 를 사용할 수도 있다.

프로그램 내용

더보기
...
    vector <long long> num_array(nNum);
    long long sum_array[nNum+1] = {0};

    long long num_max= -1e18;
    long long best = -1e18, sum = -1e18;

    sum_array[0] = 0;

    for (int idx = 0; idx < nNum; ++idx)
        cin >> num_array[idx];
        sum_array[idx+1] = num_array[idx] + sum_array[idx];
        num_max = max(num_max, num_array[idx]);

... /// N^2 
	for (int width=minW; width<= maxW; ++width)
        if (width == 1)
            best = num_max;
        else
            int left=0, right= width;
            long long tsum=sum;
            for (int idx = 0; idx <= nNum - width ; ++idx)
                tsum = sum_array[right] - sum_array[left];
                sum = max(sum, tsum);
                left++;
                right++;

            best = max(best, sum);
...

 

 수정한 프로그램

더보기
...
    maxW++; /// boundary

    vector <long long> num_array(nNum+1, 0);

    multiset <long long> sum_set;

    long long best = -1e18;

    for (int idx = 1; idx <= nNum; ++idx)
        cin >> num_array[idx];
        num_array[idx] += num_array[idx-1]; /// pre-sum update

        if ( idx - minW >= 0) /// window check
            sum_set.insert(num_array[idx-minW]);

        if ( idx - maxW >= 0) /// window check - too big
            sum_set.erase(sum_set.find(num_array[idx-maxW]));

        if ( sum_set.size()) /// check maximum
            best = max(best, num_array[idx]-*sum_set.begin());
...

 

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 3. Dice Combinations (1633)  (0) 2019.10.09
CSES 8. Minimal Rotation (1110)  (0) 2019.10.09
CSES 2. Movie Festival II (1632)  (0) 2019.10.07
CSES 2. Subarray Sums I (1660)  (0) 2019.10.03
CSES 2. Nearest Smaller Values (1645)  (0) 2019.10.03

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


문제 설명

In a movie festival, n movies will be shown.  movie club consists of k members, who will be all attending the festival.

You know the starting and ending time of each movie. What is the maximum total number of movies the club members can watch entirely if they act optimally?

입력 

The first input line has two integers n and k: the number of movies and club members.

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

출력

Print one integer: the maximum total number of movies.

입력 예

5 2
1 5
8 10
3 6
2 5
6 9

출력 예

4

제약조건

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

문제 풀이 내용

입력받은 영화 시작시간과 끝나는 시간을 이용해서, (영화시간, 시작/끝, 영화순서) 를 영화시간을 기준으로 정렬한다. 영화시작시간이면 클럽 맴버를 보내고, 끝나는 시간이면 본 영화수를 증가시키고, 영화 보고 있는 클럽 맴버수를 감소 시킨다.  

프로그램 내용

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

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

    sort(m_time.begin(), m_time.end(), greater<tuple<int, int>>());

    vector<tuple<int, bool, int>> m_schedule(2*n_movie);

    for (int idx = 0; idx < n_movie; ++idx)
        tie(end_time, start_time) = m_time[idx];
        m_schedule[2*idx] = {start_time, 0, idx};
        m_schedule[2*idx + 1] = {end_time, 1, idx};

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

    set <int> c_movie;
    int ct_member=0;
    int ct_movie=0;

    for (int idx=0; idx < 2*n_movie; ++idx)
        int m_time, m_idx;
        bool flag;
        tie(m_time,flag,m_idx) = m_schedule[idx];

        if(!flag) /// flag == 0, movie start time -> club member see
            c_movie.insert(m_idx);
            ct_member++;
        else if( c_movie.count(m_idx)) /// movie end,
            c_movie.erase(m_idx);
            ct_member--;
            ct_movie++;

        if ( idx < 2*n_movie -1 && get<0>(m_schedule[idx+1]) == m_time)
            continue;

        if (ct_member > n_member) /// can not exceed max member
            c_movie.erase(c_movie.begin());
            ct_member--;
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 8. Minimal Rotation (1110)  (0) 2019.10.09
CSES 2. Maximum Subarray Sum II (1644)  (0) 2019.10.08
CSES 2. Subarray Sums I (1660)  (0) 2019.10.03
CSES 2. Nearest Smaller Values (1645)  (0) 2019.10.03
CSES 2. Sum of Four Values (1642)  (0) 2019.10.02

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


문제 설명

Given an array of n positive integers, your task is to count the number of subarrays having sum x.

입력  

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

The next line has n integers a_1,a_2,,a_n: the contents of the array.

출력  

Print one integer: the required number of subarrays.

입력 예

5 7
2 4 1 2 7

출력 예

3

제약조건

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

문제 풀이 내용

배열의 값들을 더해가다가, 원하는 값보다 크거나 같아지면 제일 앞쪽 값을 삭제한다. 이때 값이 같은 경우 카운터를 기록해서 출력한다.  

프로그램 내용

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

    int ar_count = 0;
    int ids=0;
    int ar_sum = 0;
    for(int idx=0; idx < nNum; ++idx)
        int temp;
        num_arr[idx] =  temp;
        ar_sum += num_arr[idx];
        while(ar_sum >= tSum)
            if (ar_sum == tSum) ar_count++;
            ar_sum -= num_arr[ids++];
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Maximum Subarray Sum II (1644)  (0) 2019.10.08
CSES 2. Movie Festival II (1632)  (0) 2019.10.07
CSES 2. Nearest Smaller Values (1645)  (0) 2019.10.03
CSES 2. Sum of Four Values (1642)  (0) 2019.10.02
CSES 2. Sum of Three Values (1641)  (0) 2019.10.02

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


문제 설명

Given an array of n integers, your task is to find for each array position the nearest position to its left having a smaller value.

입력 

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 n integers: for each array position the nearest position with a smaller value. If there is no such position, print 0.

입력 예

8
2 5 1 4 8 3 2 5

출력 예

0 1 0 3 4 3 3 7

제약조건

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

문제 풀이 내용

stack에 작은 값의 위치를 기록한다. 기록된 작은 값의 위치의 값과 새로운 입력을 비교해서 작으면 위치를 출력한다. 새로운 입력의 값이 가장 지금까지 입력중에 가장 작으면 0, 아니면 기록하는 위치를 갱신한다. 출력하는 값은 배열 값이 아니라, 배열 위치이므로 출력할때는 +1을 해준다.

프로그램 내용

더보기
...
    vector <long> in_num;

    for(int idx=0; idx < nNum; ++idx)
        int temp;
        in_num.push_back(temp);

    stack<int, vector<int>> num_stack;

    for(int idx = 0 ; idx < nNum; ++idx) 
        while(!num_stack.empty() && in_num[num_stack.top()] >= in_num[idx]) 
            num_stack.pop();

        if(num_stack.empty()) 
            cout << "0 " ; 
        else 
            cout << num_stack.top()+1 << " ";

        num_stack.push(idx);
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Movie Festival II (1632)  (0) 2019.10.07
CSES 2. Subarray Sums I (1660)  (0) 2019.10.03
CSES 2. Sum of Four Values (1642)  (0) 2019.10.02
CSES 2. Sum of Three Values (1641)  (0) 2019.10.02
CSES 2. Reading Books (1632)  (0) 2019.10.02

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


문제 설명

You are given an array of n integers, and your task is to find four 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 four integers: the positions of the values. If there are several solutions, you may print any of them. If there are no solutions, print IMPOSSIBLE.

입력 예

8 15
3 2 5 8 1 3 2 3

출력 예

2 4 6 7

제약조건

  • 1 <= n <= 1000
  • 1 <= x, a_i <= 10^9

문제 풀이 내용

서로 다른 배열의 원소 2개의 합으로 새로운 배열을 만든다. 그러면 배열에서 2개의 합으로 원하는 수를 만드는 문제로 바꿀 수 있다. (참고) 다만, 원래 배열에서 4개의 원소가 달라야 하는 조건을 확인해야 한다.

프로그램 내용

더보기
...
    vector <tuple <long, int, int> > num_arr;

    for(int idx=0; idx < nNum; ++idx)
        int temp;
        in_num.push_back(temp);

    for(int idx=0; idx < nNum-1; ++idx)
        for(int id = idx+1; id < nNum ; ++ id)
            num_arr.push_back(make_tuple(in_num[idx]+in_num[id], idx+1, id+1));

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

    int id = 0, idx = num_arr.size()-1;
    while( id < idx )
        long a, b, c, d, e, f;
        tie(a, b, c) = num_arr[id];
        tie(d, e, f) = num_arr[idx];
        long k = a+d;

        if (k == tSum)
            if ( b == e || c == f)
                break;
            else
                cout << b << " " << c << " " << e << " " << f << endl;
        else if ( k < tSum) id++;
        else idx--;
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Subarray Sums I (1660)  (0) 2019.10.03
CSES 2. Nearest Smaller Values (1645)  (0) 2019.10.03
CSES 2. Sum of Three Values (1641)  (0) 2019.10.02
CSES 2. Reading Books (1632)  (0) 2019.10.02
CSES 2. Factory Machines (1620)  (0) 2019.10.01

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


문제 설명

You are given an array of n integers, and your task is to find three 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 three 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

출력 예

1 3 4

제약조건

  • 1 <= n <= 5000
  • 1 <= x, a_i <= 10^9

문제 풀이 

첫번째 수를 고정하고, 필요한 수에서 그 수만큼을 빼내면, n-1 배열에서 2개의 합으로 (x - a_i)를 만드는 문제가 된다. 참고

프로그램 내용

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

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

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

    for (int a=0; a < nNum-2; ++a)
        int b = a+1 , c = nNum-1;
        int ttSum = tSum - num_arr[a].first;
        while( b < c )
            int k = num_arr[b].first + num_arr[c].first;

            if (k == ttSum)
                cout << num_arr[a].second << " " << num_arr[b].second << " " << num_arr[c].second << endl;
            else if ( k < ttSum) b++;
            else c--;
...

 

Sorting and Searching link )

'CSES' 카테고리의 다른 글

CSES 2. Nearest Smaller Values (1645)  (0) 2019.10.03
CSES 2. Sum of Four Values (1642)  (0) 2019.10.02
CSES 2. Reading Books (1632)  (0) 2019.10.02
CSES 2. Factory Machines (1620)  (0) 2019.10.01
CSES 2. Room Allocation (1164)  (0) 2019.10.01

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

+ Recent posts