ZJNU 1528

类似于1213取水

可以把空投当作第0个城市

最后将0~n的所有城市跑最小生成树

#include<iostream>
#include<algorithm>
using namespace std;
struct road{
    int from,to,cost;
    bool operator < (const road &a) const{
        return cost<a.cost;
    }
}ar[210001];
int gp[10001];
int find(int a){
    return a==gp[a]?a:gp[a]=find(gp[a]);
}
void merge(int a,int b){
    gp[find(b)]=find(a);
}
int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    int T,i,n,m,k;
    long long res;
    cin>>T;
    while(T--){
        cin>>n>>m;
        for(i=0;i<n;i++){
            ar[i*2].from=i+1;
            ar[i*2].to=0;
            cin>>ar[i*2].cost;
            ar[i*2+1].from=0;
            ar[i*2+1].to=i+1;
            ar[i*2+1].cost=ar[i*2].cost;
        }
        for(i=n;i<n+m;i++){
            cin>>ar[i*2].from>>ar[i*2].to>>ar[i*2].cost;
            ar[i*2+1].from=ar[i*2].to;
            ar[i*2+1].to=ar[i*2].from;
            ar[i*2+1].cost=ar[i*2].cost;
        }
        sort(ar,ar+(m+n)*2);
        for(i=0;i<=n;i++)
            gp[i]=i;
        for(k=res=i=0;i<(m+n)*2;i++){
            if(k==n)
                break;
            if(find(ar[i].from)!=find(ar[i].to)){
                merge(ar[i].from,ar[i].to);
                res+=ar[i].cost;
                k++;
            }
        }
        cout<<res<<'
';
    }
    
    return 0;
}
原文地址:https://www.cnblogs.com/stelayuri/p/12235284.html