893C. Rumor#谣言传播(赋权无向图&搜索)

题目出处:http://codeforces.com/problemset/problem/893/C

题目大意:一个城中有一些关系圈,圈内会传播谣言,求使每个人都知道谣言的最小花费

#include <bits/stdc++.h>
using namespace std;
//赋权无向图 $DFS||BFS
int _sol(int m,int n[]){
    if(n[m]==m)return m;
    return n[m]=_sol(n[m],n);
}
int main(){
    int n,m,p[100010],a[100010],l,r;//p为标记。a为权 
    long long int ans=0;
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        p[i]=i;
    }
    while(m--){//将有关系的规划给同一个人,要求此人权值最小 
        cin>>l>>r;
        l=_sol(l,p);//无向图间接连通 
        r=_sol(r,p);
        if(a[r]<a[l])//有关系的两个人之间比较权值(贪心) 
            p[l]=r;
        else
            p[r]=l;
    }
    ans=0;
    for(int i=1;i<=n;i++)
        if(p[i]==i)
            ans+=a[i];
    cout<<ans;
}

本题考察图的遍历,关键在于朋友圈的建立

个人分享,欢迎指导,未经允许,请勿转载。谢谢!
原文地址:https://www.cnblogs.com/hello-OK/p/8052196.html