The Unique MST ( 次小生成树 + kruskal模板 )

The Unique MST ( 次小生成树 + kruskal模板 )

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 
#include 
#include 

using namespace std;

struct node {
    int from,to,w;
    int via;
} a[20010];
vector  G[110]; // 与当前节点连接的所有点(包括自己)
int maxd[110][110];  // 存两点路径上的最长边
int pre[110];
int n,m;

bool rule( node a, node b )
{
    return a.wsum ) {
        cout << sum << endl;
    }
    else if ( cisum=sum ) {
        cout << "Not Unique!" << endl;
    }
}

int main()
{
    int listt;
    cin >> listt;
    while ( listt-- ) {
        cin >> n >> m;
        for ( int i=0; i> a[i].from >> a[i].to >> a[i].w;
            a[i].via = 0;
        }
        kruskal();
    }

    return 0;
}

 

你可能感兴趣的:(专题八,生成树,算法树之图论)