Wednesday, February 08, 2012

Second Best MST (UVA 10462 - Is there any second way)

/***
    Second Best MST (UVA 10462 - Is there any second way)
    Author : Md.Saiful Islam
***/
#include<stdio.h>
#include<stdlib.h>
#define INF 99999999


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


int Set[203],Rank[203],store[203];
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 ( x->cost - y->cost );
}
int main()
{
int i,u_set,v_set,sum,set,test,ans,k,min,cnt,y,kase=1;


scanf("%d",&test);
while(test--)
{
scanf("%d %d",&Node,&Edge);
set  = 0;
for(i=0;i<=Node;i++)
{
make_set(i);
}
ans = -1;
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);


sum = k = 0;
for(i=0; i<Edge ;i++)
{
u_set=find_set(a[i].u);
v_set=find_set(a[i].v);
if( u_set!=v_set )
{
store[k++]=i;
sum += a[i].cost;
Union(u_set,v_set);
}
}


// second best MST start here
//if(k >= Node-1)ans = sum; // First MST Cost


min = INF;


for(y=0;y<k;y++)
{
sum = 0;
for(i=0;i<=Node;i++)
{
make_set(i);
}
for(i=cnt=0;i<Edge;i++)
{
if(store[y] != i)
{
u_set=find_set(a[i].u);
v_set=find_set(a[i].v);
if( u_set!=v_set )
{
cnt++;
sum += a[i].cost;
Union(u_set,v_set);
}
}
}
if(cnt >= Node-1 && sum < min) min = sum;
}
if(ans == -1)printf("Case #%d : No way\n",kase++);
else if(min == INF)printf("Case #%d : No second way\n",kase++);
else printf("Case #%d : %d\n",kase++,min);
}
return 0;
}
/*
Input:
4
5 4
1 2 5
3 2 5
4 2 5
5 4 5
5 3
1 2 5
3 2 5
5 4 5
5 5
1 2 5
3 2 5
4 2 5
5 4 5
4 5 6
1 0
Output:
Case #1 : No second way
Case #2 : No way
Case #3 : 21 // second best cost
Case #4 : No second way
*/

No comments:

Post a Comment