DMOJ · ecoo20p2

ECOO '20 P2 - Online Shopping

This C++ solution uses greedy for DMOJ ecoo20p2 ECOO '20 P2 - Online Shopping. Read the reasoning, inspect the code, or try your own test case below.

ecoo20p2GreedyC++49 lines
Solution155of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Greedy

Online Shopping store inventory, requested quantities, and minimum purchase cost match the per-item greedy computation.

Greedy

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

online_shopping.cpp

C++

    #include <bits/stdc++.h>
     
    using namespace std;
     
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        int t;
        cin >> t;
        while(t--){
            int n;
            cin >> n;
            unordered_map<string, vector<pair<int, int>>> pos;
            for(int i = 0; i < n; i++){
                int m;
                cin >> m;
                for(int j = 0; j < m; j++){
                    string s; int c, v;
                    cin >> s >> c >> v;
                    pos[s].emplace_back(c, v);
                }
            }
            int k;
            cin >> k;
            unordered_map<string, int> need;
            for(int i = 0; i < k; i++){
                string s; int v;
                cin >> s >> v;
                need[s] = v;
            }
            int cost = 0;
            for(auto &[s, v] : pos){
                sort(v.begin(), v.end());
            }
            for(auto[name, amount] : need){
                auto &vec = pos[name];
                for(auto[co, am] : vec){
                    if(amount >= am){
                        cost += co * am;
                        amount -= am;
                    } else {
                        cost += co * amount;
                        break;
                    }
                }
            }
            cout << cost << '\n';
        }
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.