Rumor
Hazrat Ali
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.
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.
Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.
5 2
2 5 3 4 8
1 4
4 5
10
10 0
1 2 3 4 5 6 7 8 9 10
55
10 5
1 6 2 7 3 8 4 9 5 10
1 2
3 4
5 6
7 8
9 10
15
Solution
#include <bits/stdc++.h>
using namespace std;
priority_queue<pair<long long, long long>> pq;
vector<vector<pair<long long, long long>>> cnn;
vector<long long> taken;
void process(int u) {
taken[u] = 1;
for (auto v: cnn[u]) {
if (!taken[v.first]) {
pq.push({-v.second, -v.first});
}
}
}
int main() {
int n, m;
cin >> n >> m;
cnn.resize(n + 1);
taken.assign(n + 1, 0);
for (int i = 1; i <= n; i++) {
long long c;
cin >> c;
cnn[0].push_back({i, c});
cnn[i].push_back({0, c});
}
while (m--) {
int s, t;
cin >> s >> t;
cnn[s].push_back({t, 0});
cnn[t].push_back({s, 0});
}
process(0);
long long mst = 0;
while (!pq.empty()) {
auto front = pq.top(); pq.pop();
long long u = -front.second;
long long w = -front.first;
if (!taken[u]) {
mst += w;
process(u);
}
}
cout << mst << endl;
return 0;
}