1. 程式人生 > >「POJ1679 」The Unique MST

「POJ1679 」The Unique MST

ive ted not single 題目 mea 輸出格式 ati 原本

題目描述

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‘.

輸入格式

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.

輸出格式

For each input, if the MST is unique, print the total cost of it, or otherwise print the string ‘Not Unique!‘.

樣例輸入

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

樣例輸出e

3
Not Unique!

題目大意

  • 給出一個有 n 個結點,m 條邊的無向圖,判斷其最小生成樹是否唯一。若唯一輸出結果,不唯一輸出“Not Unique!”

解題思路

  • 我們考慮MST 什麽時候唯一?顯然當加入一條非樹邊時MST會形成環。
  • 因此找到環上除了新加入的邊外權值最大的邊。當該邊權值小於這條非樹邊,則MST唯一。
  • 因此先利用Kruskal算法求出最小生成樹結果,再將形成最小生成樹的路徑進行標記,每次去掉一個最小生成樹的邊,用其他邊代替,若能找到最小生成樹的結果還為原本結果,即說明最小生成樹不唯一。

「POJ1679 」The Unique MST