poj1251最小生成树

#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]) father[x]=getfather(father[x]);

        return father[x];

}



struct Node

{

    int a;int b;int val;

}node[111111];

int cmp(const Node &a,const Node &b)

{

    return a.val<b.val;

}

int main()

{

    int n,m;

    while(cin>>n,n){

        int ans=0;

        int sum=0;

        for(int i=0;i<n;i++) father[i]=i;

        for(int i=0;i<n-1;i++){

            char c;cin>>c;int a=c-'A';

            cin>>m;

            for(int j=0;j<m;j++){

                int val;

                char d;cin>>d>>val;int b;;

                b=d-'A';

                node[ans].a=a;node[ans].b=b;node[ans].val=val;ans++; //cout<<a<<" "<<b<<endl;

            }

        }

        sort(node,node+ans,cmp);

      //  cout<<endl;

       // for(int i=0;i<ans;i++)

         //   printf("%d %d %d\n",node[i].a,node[i].b,node[i].val);system("pause");

        for(int i=0;i<ans;i++){

            int fa=getfather(node[i].a);int fb=getfather(node[i].b);

            if(fa!=fb){

                sum+=node[i].val;father[fa]=fb;

            }

        }

        cout<<sum<<endl;

    }

    return 0;

}

 

你可能感兴趣的:(最小生成树)