zoukankan      html  css  js  c++  java
  • 最小生成树

    const int inf = 1<<29;
    int n, m;
    int edge[105][105];
    bool vis[105];
    int d[105];
    
    struct node
    {
        int v, c;
        node(int _v = 0, int _c = 0):v(_v), c(_c){}
        friend bool operator< (node n1, node n2){
            return n1.c > n2.c;
        }
    };
    int ans;
    
    void prim(){
        priority_queue<node>que;
        while(!que.empty()) que.pop();
        memset(vis, false, sizeof(vis));
        for(int i = 1; i <= n; i++){
            d[i] = edge[1][i];
            if (d[i] < inf) que.push(node(i, d[i]));
        }    
        vis[1] = true;
        ans = 0;
        int cnt = 0;
        while(!que.empty()){
            node tem = que.top();
            que.pop();
            int v = tem.v;
            int c = tem.c;
            
            if (vis[v]) continue;
            vis[v] = true;
          //  printf("v = %d c = %d
    ", v, c);
            ans += c;
            cnt++;
            if (cnt == n-1) break;
            for(int i = 1; i <= n; i++){
                if (!vis[i] && edge[v][i] < d[i]){
                    d[i] = edge[v][i];
                    que.push(node(i, d[i]));
                }
            }
        }
        if (cnt < n-1) ans = -1;
    }
    
    int main() {
        int t;
        int a, b, c;
        
        cin >>t;
        while(t--){
            scanf("%d%d", &n, &m);
            for(int i = 1; i <= n; i++){
                for(int j = 1; j <= n; j++){
                    edge[i][j] = inf;
                }
            }
            for(int i = 1; i <= m; i++){
                scanf("%d%d%d", &a, &b, &c);       
                edge[a][b] = edge[b][a] = c;
            }
            prim();
            printf("%d
    ", ans);
        }
        return 0;
    }
    
    东北日出西边雨 道是无情却有情
  • 相关阅读:
    开更
    PKUSC2016
    Educational Codeforces Round 12 E Beautiful Subarrays
    省选过了,又开始更新了。。。
    我来试试视频功能
    [BZOJ4407]于神之怒加强版
    bzoj3998: [TJOI2015]弦论
    bzoj4569: [Scoi2016]萌萌哒
    2016-5-30模拟测试
    2016-5-26模拟测试
  • 原文地址:https://www.cnblogs.com/ccut-ry/p/7815251.html
Copyright © 2011-2022 走看看