Kruskal Code in C
/* kruskal code in C with using merge sort*/
#include<stdio.h>
#define MAX 100
void merge(int *arr,int *order,int low,int mid,int high)
{
int i,j,k,temp[MAX],ord[MAX];
i=low;
j=mid+1;
k=low;
while(i<=mid && j<=high)
{
if(arr[i]<arr[j])
{
temp[k]=arr[i];
ord[k]=order[i];
i++;
k++;
}
else
{
temp[k]=arr[j];
ord[k]=order[j];
j++;
k++;
}
}
if(i>mid)
{
while(j<=high)
{
temp[k]=arr[j];
ord[k]=order[j];
k++;
j++;
}
}
else
{
while(i<=mid)
{
temp[k]=arr[i];
ord[k]=order[i];
k++;
i++;
}
}
for(i=low;i<=high;i++)
{
arr[i]=temp[i];
order[i]=ord[i];
}
}
void divided(int *arr,int *ord,int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
divided(arr,ord,low,mid);
divided(arr,ord,mid+1,high);
merge(arr,ord,low,mid,high);
}
}
void merge_sort(int *arr,int *ord,int low,int high)
{
for(int i=0;i<=high;i++)
ord[i]=i;
divided(arr,ord,low,high);
}
void kruskal(int (*edge)[2],int *weight,int node,int line,int *ans)
{
int i,j,k,e,u,v,up,vp,parent[MAX],index[MAX],table[MAX][MAX];
merge_sort(weight,index,0,line-1);
for(i=1;i<=node;i++)
parent[i]=i;
for(i=1;i<=node;i++)
table[i][0]=0;
k=0;
for(i=0;i<line;i++)
{
e=index[i];
u=edge[e][0];
v=edge[e][1];
up=parent[u];
vp=parent[v];
if(up==vp)
continue;
ans[k]=e;
k++;
if(up==u && vp==v)
{
table[u][0]++;
table[u][table[u][0]]=v;
parent[v]=u;
}
else
{
if(table[vp][0]<=table[up][0])
{
table[up][0]++;
table[up][table[up][0]]=vp;
parent[vp]=up;
for(j=1;j<=table[vp][0];j++)
{
table[up][0]++;
table[up][table[up][0]]=table[vp][j];
parent[table[vp][j]]=up;
}
}
else
{
table[vp][0]++;
table[vp][table[vp][0]]=up;
parent[up]=vp;
for(j=1;j<=table[up][0];j++)
{
table[vp][0]++;
table[vp][table[vp][0]]=table[up][j];
parent[table[up][j]]=vp;
}
}
}
}
}
int main()
{
freopen("in.txt","r",stdin);
int edge[20][2],weight[20],i,x,y,z,node,line,selected_edge[20];
scanf("%d %d",&node,&line);
for(i=0;i<line;i++)
{
scanf("%d %d %d",&x,&y,&z);
edge[i][0]=x;
edge[i][1]=y;
weight[i]=z;
}
kruskal(edge,weight,node,line,selected_edge);
for(i=0;i<=node-2;i++)
{
x=selected_edge[i];
printf("%d %d\n",edge[x][0],edge[x][1]);
}
return 0;
}
Input:
7 12
1 2 8
1 5 5
2 5 10
2 4 2
2 3 18
3 4 12
3 7 4
4 5 3
4 7 14
5 6 16
4 6 30
6 7 26
Output:
2 4
4 5
3 7
1 5
3 4
5 6
Comments
Post a Comment