Rumor
time limit per test
memory limit per test
input
output
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 c**i 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 c**i (0 ≤ c**i ≤ 109) — the amount of gold i-th character asks to start spreading the rumor.
Then m lines follow, each containing a pair of numbers (x**i, y**i) which represent that characters x**i and y**i are friends (1 ≤ x**i, y**i ≤ n, x**i ≠ y**i). 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.
Examples
input
5 2
2 5 3 4 8
1 4
4 5
output
10
input
10 0
1 2 3 4 5 6 7 8 9 10
output
55
input
10 5
1 6 2 7 3 8 4 9 5 10
1 2
3 4
5 6
7 8
9 10
output
15
题意
有个散布谣言的人,要把一个谣言传给所有人,有的人是朋友,只要告诉其中一人,他的朋友就会知道,求最小花费。例如样例一,先告诉1(然后1会告诉4,4再告诉5),这样就只用再告诉2和3就行了,所以最小花费是2+5+3=10。
解题思路
并查集好题。首先用并查集把所有具有朋友关系的人连接起来,即路径压缩。然后再找出每个集合中最小的权值,最后再求和。
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<iostream>
using namespace std;
const int maxn = 1e5+5;
int n,m;
long long val[maxn];
int p[maxn];
int find(int x)
{
return p[x]==x?x:(p[x]=find(p[x]));
}
void kruskal(int a,int b)
{
int x=find(a);
int y=find(b);
if(x!=y)
p[x]=y;
}
int main()
{
cin>>n>>m;
for(int i=1; i<=n; i++)
p[i]=i;
for(int i=1; i<=n; i++)
scanf("%I64d",&val[i]);
int a,b;
for(int i=0; i<m; i++)
{
scanf("%d%d",&a,&b);
kruskal(a,b);
}
for(int i=1; i<=n; i++)
val[find(i)]=min(val[find(i)],val[i]);
long long sum=0;
for(int i=1; i<=n; i++)
if(i==find(i))
sum+=val[i];
printf("%I64d\n",sum);
return 0;
}