Definition 1 (Spanning Tree): Consider a connected, undirected graph G = (V, E). A spanning tree of G is a subgraph of G, say T = (V', E'), with the following properties:
1. V' = V.
2. T is connected and acyclic.
Definition 2 (Minimum Spanning Tree): Consider an edge-weighted, connected, undirected graph G = (V, E). The minimum spanning tree T = (V, E') of G is the spanning tree that has the smallest total cost. The total cost of T means the sum of the weights on all the edges in E'.
2 3 3 1 2 1 2 3 2 3 1 3 4 4 1 2 2 2 3 2 3 4 2 4 1 2Sample Output
3 Not Unique!
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct STR
{
int x,y,z;
}a[10001];
int tree[10001],mark[10001];
int find(int m)
{
if(m==tree[m])
return m;
else
return tree[m]=find(tree[m]);
}
void merge(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx>fy)
tree[fx]=fy;
else
tree[fy]=fx;
}
bool comp(STR p,STR q)
{
return p.z<q.z;
}
int main()
{
int t,n,m,i,j,k,sum,sum1;
scanf("%d",&t);
while(t--)
{
memset(a,0,sizeof(a));
scanf("%d%d",&m,&n);
for(i=0;i<n;i++)
{
scanf("%d %d %d",&a[i].x,&a[i].y,&a[i].z);
}
sum=0;sort(a,a+n,comp);
memset(mark,0,sizeof(mark));
memset(tree,0,sizeof(tree));
for(i=0;i<m;i++){tree[i]=i;}
k=0;
for(i=0;i<n;i++)
{
if(find(a[i].x)!=find(a[i].y))
{
merge(a[i].x,a[i].y);
mark[i]=1;
sum=sum+a[i].z;
k++;
}
if(k>=m-1){break;}
}
int min=20000000;
for(i=0;i<n;i++)
{
if(mark[i]==0)
{
memset(tree,0,sizeof(tree));
for(j=0;j<m;j++){tree[j]=j;}
merge(a[i].x,a[i].y);
sum1=a[i].z;
k=1;
for(j=0;j<n;j++)
{
if(find(a[j].x)!=find(a[j].y))
{
merge(a[j].x,a[j].y);
sum1=sum1+a[j].z;
k++;
}
}
if(sum1<min&&k==m-1)
{
min=sum1;
}
}
}
if(sum==min)
printf("Not Unique!\n");
else
printf("%d\n",sum);
}
return 0;
}