hdu 1301(最小生成树kruskal)

题目的意思是看的别人的解题报告,但代码是自己写的

#include 
#include 
using namespace std;
int u[100],v[100],w[100],f[27],r[100];

int getf(int x)
{
    return f[x] == x ? x : (f[x] = getf(f[x]));
}

int cmp(const int i,const int j){return w[i] < w[j];}

int main()
{
    int t,n,nums,i,index,sum;
    char startAlpha,trueAlpha,endAlpha,tendAlpha;
    while(cin >> n && n)
    {
        sum = 0;
        index = 0;
        for(t = 1; t < n; ++t)
        {
            cin >> startAlpha;
            trueAlpha = startAlpha - 'A';
            cin >> nums;
            for(i = 0; i < nums; ++i)
            {
                cin >> endAlpha;
                tendAlpha = endAlpha - 'A';
                u[index] = trueAlpha;
                v[index] = tendAlpha;
                cin >> w[index];
                ++index;
            }
        }
        //初始化并查集
        for(i = 0; i < 26; ++i) f[i] = i;
        //初始化边序号
        for(i = 0; i < index; ++i) r[i] = i;
        //按权值从小到大排序
        sort(r,r+index,cmp);
        //index就是边的个数
        for(i = 0; i < index; ++i)
        {
            int e = r[i];
            int x = getf(u[e]);
            int y = getf(v[e]);
            if(x != y)
            {
                sum += w[e];
                f[x] = y;
            }
        }
        cout << sum << endl;
    }
    return 0;
}


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