The Unique MST
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 22668 | Accepted: 8038 |
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'.
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! POJ的网站绝对有问题。昨天就有一题提交不了,换到HUD上就A了,今天这题同样没法提交,一提交就卡死,换到百炼上成功AC。
根据概念来做,如果在某一步合并的时候有多个可以选,那么就不唯一了。
#include <iostream>
#include <cstdio>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std; const int SIZE = ;
int FATHER[SIZE],N,M,NUM;
int MAP[SIZE][SIZE];
struct Node
{
int from,to,cost;
}G[SIZE * SIZE]; void ini(void);
int find_father(int);
void unite(int,int);
bool same(int,int);
int kruskal(void);
bool comp(const Node &,const Node &);
int main(void)
{
int t;
scanf("%d",&t);
while(t --)
{
scanf("%d%d",&N,&M);
ini();
for(int i = ;i < M;i ++)
{
scanf("%d%d%d",&G[NUM].from,&G[NUM].to,&G[NUM].cost);
NUM ++;
}
sort(G,G+NUM,comp);
kruskal();
} return ;
} void ini(void)
{
NUM = ;
for(int i = ;i <= N;i ++)
FATHER[i] = i;
} int find_father(int n)
{
if(FATHER[n] == n)
return n;
return FATHER[n] = find_father(FATHER[n]);
} void unite(int x,int y)
{
x = find_father(x);
y = find_father(y); if(x == y)
return ;
FATHER[x] = y;
} bool same(int x,int y)
{
return find_father(x) == find_father(y);
} bool comp(const Node & a,const Node & b)
{
return a.cost < b.cost;
} int kruskal(void)
{
int count = ,ans = ;
bool flag = true; for(int i = ;i < NUM;i ++)
if(!same(G[i].from,G[i].to))
{
if(i + < NUM && G[i].cost == G[i + ].cost && (G[i].from == G[i + ].from || G[i].from == G[i + ].to ||
G[i].to == G[i + ].to || G[i].to == G[i + ].from) && !same(G[i + ].from,G[i + ].to))
{
flag = false;
break;
}
unite(G[i].from,G[i].to);
count ++;
ans += G[i].cost;
if(count == N - )
break;
}
if(flag)
printf("%d\n",ans);
else
puts("Not Unique!");
}