藍橋杯 歷年試題 國王的煩惱

題目分析

這道題我是通過求最大生成樹的方法求出的,然後求這個最大生成樹的邊中有多少個權值不一樣的邊即可。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章