16B - Burglar and Matches - CodeForces Solution


greedy implementation sortings *900

Please click on ads to support us..

Python Code:

(n, m) = map(int, input().split(' '))
all = []

for i in range(m):
    (a, b) = map(int, input().split(' '))
    all.append([a, b])

all.sort(key=lambda x:x[1])
all.reverse()

matches = 0

for sublist in all:
    if sublist[0] < n:
        matches += sublist[1] * sublist[0]
        n -= sublist[0]
    else:
        matches += n * sublist[1]
        break

print(matches)

C++ Code:

#include <bits/stdc++.h>
using namespace std;

#define en "\n"
#define ll long long

struct node{
    ll a;
    int b;
};

bool comp(node a, node b){
    return a.b < b.b;
}

int main()
{
    ll n;
    int m;
    cin>>n>>m;
    vector <node> v;
    while (m--){
        ll a;
        int b;
        cin>>a>>b;
        node c;
        c.a = a;
        c.b = b;
        v.push_back(c);
    }
    sort(v.begin(), v.end(), comp);
    ll sum=0;
    for (int i=v.size()-1;n>0 && i>=0;i--){
        if(v[i].a <= n){
            sum += (v[i].b * v[i].a);
            n-=v[i].a;
        }
        else if (n < v[i].a){
            sum += (v[i].b * n);
            break;
        }
    }
    cout<<sum;
    return 0;
}


Comments

Submit
0 Comments
More Questions

148A - Insomnia cure
1650A - Deletions of Two Adjacent Letters
1512A - Spy Detected
282A - Bit++
69A - Young Physicist
1651A - Playoff
734A - Anton and Danik
1300B - Assigning to Classes
1647A - Madoka and Math Dad
710A - King Moves
1131A - Sea Battle
118A - String Task
236A - Boy or Girl
271A - Beautiful Year
520B - Two Buttons
231A - Team
479C - Exams
1030A - In Search of an Easy Problem
158A - Next Round
71A - Way Too Long Words
160A - Twins
1A - Theatre Square
1614B - Divan and a New Project
791A - Bear and Big Brother
1452A - Robot Program
344A - Magnets
96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters