您的位置:首页 > 其它

hdu 1102 最小生成树 prim算法+Kruskal算法(并查集)

2011-05-03 17:42 337 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1102

题目大意:给定n个村庄,及各村庄间修路的费用,求要使各村庄连通的最小费用,要注意的是,有些村庄间已经有路,就不需要再修了,处理时,只要把已有路的村庄间距离修改为0就可以了

prim算法:

#include<stdio.h>
#define N 105
#define Initmax 1005
int a

,lowcost
,s
,n;
int prim()
{
int i,j,u,Max,sum=0;
for(i=1;i<=n;i++)
{
lowcost[i]=a[1][i];
s[i]=0;
}
s[1]=1;
for(i=1;i<n;i++)
{
Max=Initmax;
for(j=1;j<=n;j++)
{
if(!s[j] && lowcost[j]<Max)
{
Max=lowcost[j];
u=j;
}
}
if(Max==Initmax)
break;
s[u]=1;
sum+=lowcost[u];
for(j=1;j<=n;j++)
if(!s[j] && lowcost[j]>a[u][j])
lowcost[j]=a[u][j];
}
return sum;
}
int main()
{
int i,j,x,y,result,t;
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&x,&y);
a[x][y]=a[y][x]=0;
}
result=prim();
printf("%d/n",result);
}
return 0;
}


Kruskal算法:

#include<stdio.h>
#include<stdlib.h>
#define N 105
int n,k;
struct node{
int x,y,cost;
}edge[10005];  //刚开始开成N了,runtime error一次
int father
;
int cmp(const void *a,const void *b)
{
struct node *c=(struct node *)a;
struct node *d=(struct node *)b;
return c->cost-d->cost;
}
int find(int x)
{
int q,r=x;
while(father[r]!=r)
r=father[r];
while(x!=r)  //带路径压缩
{
q=father[x];
father[x]=r;
x=q;
}
return r;
}
void Union(int a,int b)
{
int fx,fy;
fx=find(a);
fy=find(b);
if(fx!=fy)
father[fx]=fy;
}
int Kruskal()
{
int i,a,b,sum=0;
qsort(edge,k,sizeof(edge[0]),cmp);
for(i=0;i<k;i++)
{
a=find(edge[i].x);
b=find(edge[i].y);
if(a!=b)
{
Union(a,b);
sum+=edge[i].cost;
}
}
return sum;
}
int main()
{
int i,j,result,t,s,a,b;
while(scanf("%d",&n)!=EOF)
{
k=0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
father[j]=j;
scanf("%d",&s);
if(i>j)
{
edge[k].x=i;
edge[k].y=j;
edge[k].cost=s;
k++;
}
}
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&b);
Union(a,b);
}
result=Kruskal();
printf("%d/n",result);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: