ZJNU 1528 - War--高级

类似于1213取水

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

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

 1 /*
 2 Written By StelaYuri
 3 */
 4 #include<iostream>
 5 #include<algorithm>
 6 using namespace std;
 7 struct road{
 8     int from,to,cost;
 9     bool operator < (const road &a) const{
10         return cost<a.cost;
11     }
12 }ar[210001];
13 int gp[10001];
14 int find(int a){
15     return a==gp[a]?a:gp[a]=find(gp[a]);
16 }
17 void merge(int a,int b){
18     gp[find(b)]=find(a);
19 }
20 int main(){
21     ios::sync_with_stdio(0);cin.tie(0);
22     int T,i,n,m,k;
23     long long res;
24     cin>>T;
25     while(T--){
26         cin>>n>>m;
27         for(i=0;i<n;i++){
28             ar[i*2].from=i+1;
29             ar[i*2].to=0;
30             cin>>ar[i*2].cost;
31             ar[i*2+1].from=0;
32             ar[i*2+1].to=i+1;
33             ar[i*2+1].cost=ar[i*2].cost;
34         }
35         for(i=n;i<n+m;i++){
36             cin>>ar[i*2].from>>ar[i*2].to>>ar[i*2].cost;
37             ar[i*2+1].from=ar[i*2].to;
38             ar[i*2+1].to=ar[i*2].from;
39             ar[i*2+1].cost=ar[i*2].cost;
40         }
41         sort(ar,ar+(m+n)*2);
42         for(i=0;i<=n;i++)
43             gp[i]=i;
44         for(k=res=i=0;i<(m+n)*2;i++){
45             if(k==n)
46                 break;
47             if(find(ar[i].from)!=find(ar[i].to)){
48                 merge(ar[i].from,ar[i].to);
49                 res+=ar[i].cost;
50                 k++;
51             }
52         }
53         cout<<res<<'\n';
54     }
55     
56     return 0;
57 }

猜你喜欢

转载自www.cnblogs.com/stelayuri/p/12235284.html
今日推荐