hdu1233 并查集+Kruskal

题意:n个城市,给出城市间的距离,求最短路;

利用Kruskal算法:

先选取最短路,再从该集合外找次短路。

并查集思想:

将多点合并的方法为对其父节点p【】赋值指向根节点。

找到亮点父节点,根据父节点来判断是否合并。

Sample Input
3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
 


 

Sample Output
3 5

过程中   运用sort时  范围没控制好超时

p[i]赋值时  范围错误  WA。。。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int p[121],sum;
struct node{
    int c1;
    int c2;
    int len;
}q[10000];
bool cmp(node q1,node q2)
{
    return q1.len<q2.len;
}
int find(int x)
{
    if(x!=p[x])
      p[x]=find(p[x]);
     return p[x];
}
void unions(int x,int y)
{
    p[x]=y;
}
int main()
{
    //freopen("input.txt","r+",stdin);
    int i,n,m,fx,fy;
    while(scanf("%d",&n)&&n)
    {
        sum=0;
        m=n*(n-1)/2;
        for(i=1;i<=m;i++)
        {
            scanf("%d%d%d",&q[i].c1,&q[i].c2,&q[i].len);
        }
        for(i=1;i<=n;i++)
            p[i]=i;
        sort(q+1,q+m+1,cmp);
        for(i=1;i<=m;i++)
        {
            fx=find(q[i].c1);
            fy=find(q[i].c2);
            if(fx!=fy)
            {
                sum+=q[i].len;
                unions(fx,fy);
            }
        }
        cout<<sum<<endl;
    }
    return 0;
}


原文地址:https://www.cnblogs.com/amourjun/p/5134238.html