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

    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <string>
    #include <cstring>
    #include <cstdlib>
    #include <map>
    #include <vector>
    #include <set>
    #include <queue>
    #include <stack>
    #include <cmath>
    using namespace std;
    #define mem(s,t) memset(s,t,sizeof(s))
    #define pq priority_queue
    #define pb push_back
    #define fi first
    #define se second
    #define ac return 0;
    #define TLE std::ios::sync_with_stdio(false);   cin.tie(NULL);   cout.tie(NULL);   cout.precision(10);
    const int mxn = 1e3;
    int root[mxn];
    int n,m,k,l,r,t,ans,cnt;
    struct node
    {
        int x,y,k;
        bool operator <(const node &a) const
        {
            return k<a.k;
        }
    }no[50+5];
    void init() {for(int i=0;i<=mxn;i++) root[i]=i;}
    int Judge(int now)
    {
        if( now==root[now] )
            return now;
        root[now] = Judge(root[now]);
        return root[now];
    }
    int check(int x,int y)
    {
        if(Judge(x)==Judge(y))
            return 0;
        root[Judge(x)]=Judge(y);
        return 1;
    }
    int main()
    {
        TLE;
        while(cin>>n&&n)
        {
            cin>>m;
            init(); ans = 0,cnt = 0 ;
            for(int i=1;i<=m;i++)
                cin>>no[i].x>>no[i].y>>no[i].k;
            sort(no+1,no+1+m);
            for(int i=1;i<=m;i++)
            {
                if( check( no[i].x,no[i].y ) )
                {
                    cnt++;
                    ans += no[i].k;
                }
                if(cnt==n-1) break;
            }
            cout<<ans<<endl;
        }
        return 0;
    }
    所遇皆星河
  • 相关阅读:
    枚举子集 Codeforces306 Div2 B
    UVA140 剪枝
    回溯法浅谈
    UVA10976
    UVA11059
    BZOJ3355
    hdu 2509 博弈 *
    博弈专题
    hdu 1404 找sg ***
    hdu 4759 大数+找规律 ***
  • 原文地址:https://www.cnblogs.com/Shallow-dream/p/11780269.html
Copyright © 2011-2022 走看看