C. Rumor
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.
Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.
Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.
The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?
Take a look at the notes if you think you haven‘t understood the problem completely.
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105) — the number of characters in Overcity and the number of pairs of friends.
The second line contains n integer numbers ci (0 ≤ ci ≤ 109) — the amount of gold i-th character asks to start spreading the rumor.
Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≤ xi, yi ≤ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.
Output
Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.
Input
5 2 2 5 3 4 8 1 4 4 5
Output
10
思路:明显的并查集。
AC代码:
#include<bits/stdc++.h> using namespace std; #define N 100009 #define int long long int cost[N]; int f[N]; int getf(int v){ if(v==f[v]){ return f[v]; }else{ f[v]=getf(f[v]); return f[v]; } } void merge(int u,int v){ int t1=getf(u); int t2=getf(v); if(t1!=t2){ f[t2]=t1; } } signed main(){ int n,m; cin>>n>>m; int sb=0; int ans=0; for(int i=1;i<=n;i++){ scanf("%lld",&cost[i]); sb+=cost[i]; f[i]=i; } if(m==0){ cout<<sb<<endl; return 0; } for(int i=0;i<m;i++){ int x,y; scanf("%lld%lld",&x,&y); merge(x,y); } /*for(int i=1;i<=n;i++){ if(i==f[i]){ cout<<i<<" "; } } cout<<endl;*/ for(int i=1;i<=n;i++){ cost[getf(i)]=min(cost[getf(i)],cost[i]);// 关键:将该每一个集合中的最小花费赋值给祖先。 }// for(int i=1;i<=n;i++){ if(i==f[i]){ ans+=cost[i]; } } printf("%lld\n",ans); return 0; }
原文地址:https://www.cnblogs.com/pengge666/p/11511099.html