Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- typedef long long lli;
- typedef struct edge{
- int u;
- int v;
- int w;
- bool operator < (const edge &rhs)const{
- return w > rhs.w;
- }
- }edge;
- priority_queue<edge> adj;
- vector<int> power;
- vector<int> parent;
- vector<int> ranks;
- int nv, ne;
- void PrintPower(){
- for(int i = 1; i <= nv; ++i){
- cout << power[i] << " ";
- }
- cout << "\n";
- return;
- }
- int FindDSet(int x){
- if(parent[x] == x){
- return x;
- } else {
- return parent[x] = FindDSet(parent[x]);
- }
- }
- void UnionDSet(int f, int s){
- int x = FindDSet(f);
- int y = FindDSet(s);
- if(ranks[x] > ranks[y]){
- parent[y] = x;
- } else {
- parent[x] = y;
- if(ranks[x] == ranks[y]){
- ++ranks[y];
- }
- }
- return;
- }
- lli Kruskal(){
- lli sum = 0;
- while(!adj.empty()){
- edge t = {adj.top().u, adj.top().v, adj.top().w};
- adj.pop();
- if(FindDSet(t.u) != FindDSet(t.v)){
- sum += t.w;
- UnionDSet(t.u, t.v);
- }
- }
- return sum;
- }
- int main(){
- int x, u, v;
- scanf("%d", &nv);
- power.assign(nv + 1, 0);
- parent.assign(nv + 1, 0);
- ranks.assign(nv + 1, 0);
- for(int i = 1; i <= nv; ++i){
- scanf("%d", &x);
- power[i] = x;
- parent[i] = i;
- }
- scanf("%d", &ne);
- for(int i = 0; i < ne; ++i){
- scanf("%d %d", &u, &v);
- adj.push({u, v, power[u] + power[v]});
- }
- cout << Kruskal();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement