1 solutions

  • 0
    @ 2025-9-8 12:58:09

    可以用贪心来做,时间复杂度O(nlogn)O(n·logn)

    #include <iostream>
    #include <cstdio>
    #include <vector>
    #include <cstring>
    #include <algorithm>
    #include <unordered_map>
    #include <unordered_set>
    
    using namespace std;
    
    #define FAST_IO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    
    #define MAX(a,b) ((a) > (b)? (a): (b))
    #define MIN(a,b) ((a) < (b)? (a): (b))
    
    typedef pair<int, int> pii;
    typedef long long ll;
    
    vector<pii> peo; 
    
    int main(){
        FAST_IO;
    
        int T;
    
        cin >> T;
    
        while(T--){
            int n;
            cin >> n;
            peo.clear();
            for(auto i=0;i<n;i++){
                int wash, cut;
                cin >> wash >> cut;
                peo.emplace_back(wash, cut);
            }
            int sum = 0;
            int delt = 0;
            sort(peo.begin(), peo.end(), [](pii &a, pii &b){
                if(a.first <= a.second){
                    if(b.first <= b.second){
                        return a.first < b.first;
                    }else{
                        return true;
                    }
                }else{
                    if(b.first <= b.second){
                        return false;
                    }else{
                        return a.second > b.second;
                    }
                }
            });
            for(auto i=0;i<n;i++){
                auto item = peo[i];
                if(delt < item.first){
                    sum += item.first;
                    delt = item.second;
                }
                else{
                    sum += item.first;
                    delt -= item.first;
                    delt += item.second;
                }
            }
            cout << sum + delt << endl;
        }
    
        return 0;
    }
    
    • 1

    Information

    ID
    104
    Time
    1000ms
    Memory
    512MiB
    Difficulty
    1
    Tags
    # Submissions
    51
    Accepted
    18
    Uploaded By