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!
給你一張圖,問你能不能構造出兩棵不同的最小生成樹,方法是先構造出一個最小生成樹,然后枚舉該生成樹的某一條邊不能用,再次構造生成樹,比較生成樹權值。
#include<iostream>#include<string.h>#include<stdio.h>#include<string>#include<vector>#include<algorithm>using namespace std;int n,m;struct edge{ int beg, endd, len; edge(){} edge(int a, int b, int c){ beg = a, endd = b, len = c; }}e[5005];bool cmp(edge a,edge b){ return a.len < b.len;}int f[105];int F(int x){ if (f[x] == x)return x; return f[x] = F(f[x]);}vector<int> ansn;int main(){ int x, y,z,t; scanf("%d", &t); while (t--){ ansn.clear(); scanf("%d%d", &n, &m); for (int i = 0; i < m; i++){ scanf("%d%d%d", &x, &y, &z); e[i] = edge(x, y, z); } sort(e, e + m, cmp); int ans = 0; for (int i = 1; i <= n; i++){ f[i] = i; } for (int i = 0; i < m; i++){ int a = e[i].beg, b = e[i].endd, c = e[i].len; if (F(a) != F(b)){ ansn.push_back(i); ans += c; f[F(a)] = F(b); } } bool same = 0; int total = ansn.size(); for (int i = 0; i < total; i++){ int cntans = 0,cntto=0; for (int k = 1; k <= n; k++){ f[k] = k; } for (int j = 0; j < m; j++){ if (j != ansn[i]){ int a = e[j].beg, b = e[j].endd, c = e[j].len; if (F(a) != F(b)){ cntans += c; cntto++; f[F(a)] = F(b); } } } if (cntto == total&&cntans == ans){ same = 1; break; } } if (same){ printf("Not Unique!/n"); } else{ printf("%d/n", ans); } } return 0;}新聞熱點
疑難解答