POJ 1258 (典型Kruskal算法)

样例错了

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<list>
#include<queue>
#define mm(a,b) memset(a,b,sizeof(a))
#define ACCELERATE (ios::sync_with_stdio(false),cin.tie(0))
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define MAXNL 0x3fffffff
#define MAXN 0x3f3f3f3f
using namespace std;

//#define debug

struct node{
    int u,v,w;
};

bool cmp(const node& a,const node& b){
    return a.w<b.w;
}

int fa[1005];

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

int main()
{
    #ifdef debug
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    #endif // debug

    node mmp[15005];
    node p[15005];
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        for(int i=0;i<m;i++){
            scanf("%d%d%d",&mmp[i].u,&mmp[i].v,&mmp[i].w);
        }
        sort(mmp,mmp+m,cmp);
        int maxn=-1;
        int ans=0;
        for(int i=1;i<=n;i++) fa[i]=i;
        int cnt=0;
        for(int i=0;i<m;i++){
            if(get_father(mmp[i].u)!=get_father(mmp[i].v)){
                ans+=mmp[i].w;
                fa[fa[mmp[i].u]]=fa[mmp[i].v];
                p[cnt].u=mmp[i].u,p[cnt].v=mmp[i].v;
                cnt++;
                if(cnt==n-1){
                    maxn=mmp[i].w;
                    break;
                }
            }
        }
        printf("%d\n",maxn);
        printf("%d\n",cnt);
        for(int i=0;i<cnt;i++){
            printf("%d %d\n",p[i].u,p[i].v);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/80716390