并查集- Supermarket POJ

并查集+贪心

https://vjudge.net/contest/362147#problem/C

#include <iostream>
#include <cstdio>
#include <cstring>
#include <limits>
#include <algorithm>
#define endl '
'
#define _for(i,a,b) for(int i=a;i<b;i++)
using namespace std;
const int N = 1e4+5;
typedef long long ll;
int n,P[N]; 
struct Node{
    int pi,di;
    bool operator < ( const Node &o )const{
        if( pi!=o.pi )
            return pi>o.pi;
        return di<o.di;
    }
}a[N];
int find(int p){
    if( P[p]== p ) return p;
    return P[p]= find( P[p] );
}
int main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    while(cin>>n){
        ll res = 0;
        int pos = 0;
        _for(i,1,n+1){
            cin>>a[i].pi>>a[i].di;
            pos = max(pos,a[i].di);
        }
        pos = min(pos,(int)1e4);
        sort(a+1,a+n+1);
        _for(i,0,pos+1) P[i]= i;
        _for(i,1,n+1){
            int apos = a[i].di;
            if( P[apos] ==apos ){
                res += a[i].pi;
                P[apos] = apos-1;
            }
            else{
                apos = find(apos);
                if( apos > 0 ){
                    res += a[i].pi;
                    P[apos] = apos-1;
                }
            }
        }
        cout<<res<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/SunChuangYu/p/12541747.html