WAP in C To Implement Minimal Spanning Tree by (A) Kruskal's Algorithm
WAP in C To Implement Minimal Spanning Tree by (A) Kruskal's Algorithm
by
(a) Kruskal’s Algorithm
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include<process.h>
#include<alloc.h>
#define MAX 10
struct edge
int u;
int v;
int weight;
}*front=NULL;
int father[MAX];
int n,wt_tree=0,count=0;
void create_graph();
void maketree();
//void display();
void main()
int i,j;
clrscr();
create_graph();
maketree();
cout<<endl;
for(i=1;i<=count;i++)
cout<<tree[i].u<<"->";
cout<<tree[i].v;
cout<<"\t";
getch();
void create_graph()
int i,max_edge,origin,destin,wt;
cin>>n;
max_edge=n*(n-1)/2;
for(i=1;i<=max_edge;i++)
cin>>origin>>destin;
if((origin==0)&&(destin==0))
break;
cin>>wt;
if(origin>n||destin>n||origin<=0||destin<=0)
cout<<"Invalid edge";
i--;
else
insert_pque(origin,destin,wt);
if(i<n-1)
exit(1);
}
void maketree()
int node1,node2,root_n1,root_n2;
while(count<n-1)
temp=del_pque();
node1=temp->u;
node2=temp->v;
cout<<"n1="<<node1;
cout<<"n2="<<node2;
while(node1>0)
root_n1=node1;
node1=father[node1];
while(node2>0)
root_n2=node2;
node2=father[node2];
cout<<"Rootn1 "<<root_n1;
cout<<"Rootn2 "<<root_n2;
if(root_n1!=root_n2)
insert_tree(temp->u,temp->v,temp->weight);
wt_tree=wt_tree+temp->weight;
father[root_n2]=root_n1;
count++;
tree[count].u=i;
tree[count].v=j;
tree[count].weight=wt;
temp->u=i;
temp->v=j;
temp->weight=wt;
if(front==NULL||temp->weight<front->weight)
temp->link=front;
front=temp;
else
q=front;
q=q->link;
temp->link=q->link;
q->link=temp;
if(q->link==NULL)
temp->link=NULL;
temp=front;
cout<<endl;
cout<<endl;
front=front->link;
return temp;