标题
最小生成树
时间限制
2 S
内存限制
10000 Kb
问题描述:
用克鲁斯卡尔(Kruskal)算法求无向网的最小生成树。
输入:
输入数据第一行为两个正整数n(1<n<=30)和m(1<m<100),分别表示顶点数和边数。后面紧跟m行数据,每行数据是一条边的信息,包括三个数字,分别表示该边的两个顶点和边上的权值。
输出:
按顺序输出Kruskal算法求得的最小生成树的边集,每行一条边,包括三个数字,分别是该边的两个顶点和边上的权值,其中第一个顶点的编号应小于第二个顶点的编号。
示例输入
8 11
1 2 3
1 4 5
1 6 18
2 4 7
2 5 6
3 5 10
3 8 20
4 6 15
4 7 11
5 7 8
5 8 12
示例输出
1 2 3
1 4 5
2 5 6
5 7 8
3 5 10
5 8 12
4 6 15
我天真地认为不会给降序。。。结果一直没有满分
#include<stdio.h>
#include<stdlib.h>
//克鲁斯卡尔算法
typedef struct ANode{
int u,v;
int weight;
}ANode;
void sort(ANode *A,int arcnum){
int i,j;
ANode temp;
for(i=1;i<arcnum;i++){
for(j=1;j<arcnum-(i-1);j++){
if(A[j].weight>A[j+1].weight){
temp=A[j];
A[j]=A[j+1];
A[j+1]=temp;
}
}
}
}
int FindRoot(int root[],int vex){
if(root[vex]==-1){
return vex;
}else{
return FindRoot(root,root[vex]);
}
}
int main(){
int vexnum,arcnum,i,temp1,temp2,count=0;
scanf("%d %d",&vexnum,&arcnum);
int root[31];
for(i=1;i<=vexnum;i++){
root[i]=-1;
}
ANode *A,*path;
A=(ANode*)malloc(sizeof(ANode)*101);
path=(ANode*)malloc(sizeof(ANode)*101);
for(i=1;i<=arcnum;i++){
scanf("%d %d %d",&A[i].u,&A[i].v,&A[i].weight);
}
sort(A,arcnum);
for(i=1;i<=arcnum;i++){
temp1=FindRoot(root,A[i].u);
temp2=FindRoot(root,A[i].v);
if(temp1!=temp2){
count++;
path[count]=A[i];
root[temp1]=temp2;
}
if(count==vexnum-1){
break;
}
}
for(i=1;i<=count;i++){
if(path[i].u>path[i].v){
printf("%d %d %d\n",path[i].v,path[i].u,path[i].weight);
}else{
printf("%d %d %d\n",path[i].u,path[i].v,path[i].weight);
}
}
return 0;
}
1786

被折叠的 条评论
为什么被折叠?



