Tuesday, February 07, 2012

MST - Kurskal Algorithm

/***
    MST - Kurskal Algorithm
    Author : Md.Saiful Islam
***/
#include<stdio.h>
#include<stdlib.h>


struct S
{
int u,v,cost;
};
S a[10002];


int Set[1002],Rank[1002];
int Node,Edge;


void make_set(int x)
{
Set[x] = x;
Rank[x] = 0;
}
int find_set(int x)
{
if(x != Set[x])
{
Set[x] = find_set(Set[x]);
}
return Set[x];
}


void Union(int x,int y)
{
if(Rank[x] > Rank[y])
{
Set[y] = x;
}
else
{
Set[x] = y;
if(Rank[x] == Rank[y])
{
Rank[y]++;
}
}
return;
}


int comp_fun(const void *m,const void *n)
{
S *x,*y;
x=(S*)m;
y=(S*)n;
return ( y->cost - x->cost );
}
int main()
{
int i,taken,u_set,v_set,test,kase=1,max;


scanf("%d",&test);
while(test--)
{
scanf("%d %d",&Node,&Edge);


for(i=0;i<Edge;i++)
{
   scanf("%d %d %d",&a[i].u,&a[i].v,&a[i].cost);
}
qsort(a,Edge,sizeof(S),comp_fun);


for(i=0;i<Node;i++)
{
make_set(i);
}


taken=1;max = 99999999;
for(i=0; taken<Node ;i++)
{
u_set=find_set(a[i].u);
v_set=find_set(a[i].v);
if( u_set!=v_set )
{
++taken;
if(a[i].cost <= max)
max = a[i].cost;
Union(u_set,v_set);
}
}
printf("Case #%d: %d\n",kase++,max);
}
return 0;
}
/*
Input:
2
2 3
0 1 10
0 1 20
0 0 30
4 5
0 1 1
3 1 2
1 2 3
2 3 4
0 2 5
Output:
Case #1: 20
Case #2: 3
*/

No comments:

Post a Comment