1783C - Yet Another Tournament - CodeForces Solution


binary search greedy sortings

Please click on ads to support us..

Python Code:


def ii(num=False):
    i = input().split()
    if num:
        return int(i[0])
    try:
        return list(map(int, i))
    except Exception:
        return i


def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)

for _ in range(ii(1)):
    n, m = ii()
    a = ii()
    b = list(a)
    b.sort()
    ans = 0
    for i in b:
        if i <= m:
            ans+=1
            m-=i
        else:
            break
    
    if ans != n and ans != 0 and b[ans-1] + m >= a[ans]:
        ans+=1
    print(n + 1 - ans)

C++ Code:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(void) {
    int t;
    cin >> t;
    while(t--) {
        int n, m;
        cin >> n >> m;
        vector<pair<int, int>> A(n);
        for(int i=0; i<n; i++) {
            cin >> A[i].first;
            A[i].second = i;
        }
        sort(A.begin(), A.end());
        int sum = 0, cnt = 0;
        for(int i=0; i<n; i++) {
            if(sum + A[i].first > m)
                break;
            sum += A[i].first;
            cnt++;
        }
        int idx = -1;
        for(int i=0; i<n; i++) {
            if(A[i].second == cnt) {
                idx = i;
                break;
            }
        }
        if(cnt == 0) {
            cout << n+1 << '\n';
        } else if(cnt == n) {
            cout << 1 << '\n';
        } else {
            if(sum - A[cnt - 1].first + A[idx].first > m) 
                cout << n - cnt + 1 << '\n';
            else 
                cout << n - cnt << '\n';
        }
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

230A - Dragons
200B - Drinks
13A - Numbers
129A - Cookies
1367B - Even Array
136A - Presents
1450A - Avoid Trygub
327A - Flipping Game
411A - Password Check
1520C - Not Adjacent Matrix
1538B - Friends and Candies
580A - Kefa and First Steps
1038B - Non-Coprime Partition
43A - Football
50A - Domino piling
479A - Expression
1480A - Yet Another String Game
1216C - White Sheet
1648A - Weird Sum
427A - Police Recruits
535A - Tavas and Nafas
581A - Vasya the Hipster
1537B - Bad Boy
1406B - Maximum Product
507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns