蓝桥杯 历年试题 国王的烦恼

题目分析

这道题我是通过求最大生成树的方法求出的,然后求这个最大生成树的边中有多少个权值不一样的边即可。

#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 1e4+10;
const int maxm = 1e5+100;
const int INF = 0x3f3f3f3f;

struct Edge{
    int from, to, val;
    Edge(){}
    Edge(int a, int b, int c):from(a), to(b), val(c){}
    bool operator < (const Edge e)const{
        return  val > e.val;
    }
};

Edge e[maxm];
int fa[maxn];

int Find(int x){
    return  fa[x] == x?fa[x]:fa[x] = Find(fa[x]);
}

int main(){
    int n, m;
    while(scanf("%d%d", &n, &m) != EOF){
        for(int i = 0; i < maxn; i++) fa[i] = i;
        int from, to, val;
        for(int i = 0; i < m; i++){
            scanf("%d%d%d", &from, &to, &val);
            e[i] = Edge(from, to, val);
        }
        sort(e, e+m);
        int ans = 0, temp = INF;
        for(int i = 0; i < m; i++){
            int xx = Find(e[i].from);
            int yy = Find(e[i].to);
            if(xx != yy){
                fa[xx] = yy;
                if(e[i].val < temp){
                    temp = e[i].val;
                    ans++;
                }
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

你可能感兴趣的:(ACM_蓝桥杯)