注意的是:
需要判定最小生成树是不是唯一的路径,这个可以能过prim,然后把另入的最后一条边与后面的边相比较,如果后面的边还有可以满足与前面一样的路径长则 not unique
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m;
int t;
#define N 101
bool vist[N];
struct my
{
int x,y;
int v;
}go[N*N];
int f[N];
bool cmp(my a,my b)
{
return a.v<b.v;
}
int find(int i)
{
return i==f[i]?f[i]:f[i]=find(f[i]);
}
int main()
{
freopen("in.txt","r",stdin);
int i,j,k;
cin>>t;
while (t--)
{
cin>>n>>m;
memset(vist,false,sizeof(vist));
for (i=0;i<m;i++)
cin>>go[i].x>>go[i].y>>go[i].v;
sort(go,go+m,cmp);
int ans=0;
j=1;
for (i=1;i<=n;i++)
f[i]=i;
int temp=go[0].v;
bool unique=false;
for (i=0;i<m;i++)
{
int x=find(go[i].x);
int y=find(go[i].y);
//cout<<x<<' '<<y<<endl;
if (x!=y)
{
ans+=go[i].v;
j++;
if (j==n)
{
if (i==m-1||go[i+1].v>go[i].v)
break;
for (int e=i+1;e<m&&go[e].v==go[i].v;e++)
{
x=find(go[e].x);
y=find(go[e].y);
if (x!=y)
{
unique=true;
break;
}
}
break;
}
else
{
f[x]=y;
}
}
}
if (unique)
cout<<"Not Unique!"<<endl;
else
cout<<ans<<endl;
}
return 0;
}
The Unique MST
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 13852 | Accepted: 4796 |
Description
Given a connected undirected graph, tell if its minimum spanning tree is unique.
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'.
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'.
Input
The first line contains a single integer t (1 <= t <= 20), the number of test cases. Each case represents a graph. It begins with a line containing two integers n and m (1 <= n <= 100), the number of nodes and edges. Each of the following m lines contains a triple (xi, yi, wi), indicating that xi and yi are connected by an edge with weight = wi. For any two nodes, there is at most one edge connecting them.
Output
For each input, if the MST is unique, print the total cost of it, or otherwise print the string 'Not Unique!'.
Sample Input
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 2
Sample Output
3 Not Unique!
Source