hdu1233 并查集+Kruskal

来源:互联网 发布:adobe xd cc for mac 编辑:程序博客网 时间:2024/05/18 12:01

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

利用Kruskal算法:

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

并查集思想:

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

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

Sample Input
31 2 11 3 22 3 441 2 11 3 41 4 12 3 32 4 23 4 50
 


 

Sample Output
35

 

过程中   运用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;}


原创粉丝点击