首页 > 代码库 > poj1861最小生成树

poj1861最小生成树

#include <cstdio>#include <cstring>#include <algorithm>#include <climits>#include <string>#include <iostream>#include <map>#include <cstdlib>#include <list>#include <set>#include <queue>#include <stack>using namespace std;int father[22222];int getfather(int x){    if(x!=father[x])        return father[x]=getfather(father[x]);    return father[x];}struct Node{    int a;int b;int c;}node[111111];int cmp(const Node&a,const Node &b){    return a.c<b.c;}int Max(int a,int b){    return a>b?a:b;}int gg[111111];int Map[1111][1111];int main(){    int n,m;    while(~scanf("%d%d",&n,&m)){        int ans=0;        int sum=0;        memset(Map,0,sizeof(Map));        for(int i=1;i<=n;i++) father[i]=i;        for(int i=0;i<m;i++){            int a,b,c;            scanf("%d%d%d",&a,&b,&c);            if(!Map[a][b]){                Map[a][b]=Map[b][a]=c;                node[ans].a=a;node[ans].b=b;node[ans++].c=c;            }            if(Map[a][b]&&Map[a][b]>c){                Map[a][b]=Map[b][a]=c;                node[ans].a=a;node[ans].b=b;node[ans++].c=c;            }        }        sort(node,node+ans,cmp);       // cout<<endl;      //  for(int i=0;i<n;i++)        //    printf("%d %d %d\n",node[i].a,node[i].b,node[i].c);        int cc=0;        int ret=0;        for(int i=0;i<ans;i++){            int fa=getfather(node[i].a);int fb=getfather(node[i].b);            if(fa!=fb){                father[fa]=fb;ret=Max(ret,node[i].c);                gg[cc++]=i;            }        }        cout<<ret<<endl;        cout<<cc<<endl;        for(int i=0;i<cc;i++){            printf("%d %d\n",node[gg[i]].a,node[gg[i]].b);        }    }    return 0;}