POJ 1679 The Unique MST(次短生成树)

来源:互联网 发布:淘宝搜索广告位价格 编辑:程序博客网 时间:2024/06/03 19:01
Language:
The Unique MST
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 29098 Accepted: 10404

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

23 31 2 12 3 23 1 34 41 2 22 3 23 4 24 1 2

Sample Output

3Not Unique!

思路:找有没有次短生成树,先找出最小生成树,再把每条边替换,是否与最小生成树相同

#include<cstdio>#include<iostream>#include<algorithm>#define MAXN 201struct node {    int x,y;    int val;};node  a[MAXN*MAXN];int fa[MAXN],n,t,m,num[MAXN*MAXN],dis;bool flag;using namespace std;inline void read(int&x) {    x=0;int f=1;char c=getchar();    while(c>'9'||c<'0') {if(c=='-') f=-1;c=getchar();}    while(c>='0'&&c<='9') {x=(x<<1)+(x<<3)+c-48;c=getchar();}    x=x*f;}inline int find(int x) {    if(x==fa[x]) return x;    else return fa[x]=find(fa[x]);}inline bool cmp(node x,node y) {    return x.val<y.val;}inline void MST() {    int cnt=0;dis=0;    for(int i=1;i<=n;i++) fa[i]=i;    for(int i=1;i<=m;i++) {        int xx=find(a[i].x);        int yy=find(a[i].y);        if(xx!=yy) {            fa[xx]=yy;            dis+=a[i].val;            num[cnt++]=i;        }    }    flag=false;    for(int k=0;k<cnt;k++) {        for(int i=1;i<=n;i++) fa[i]=i;        int ans=0,sum=0,t=0;        for(int i=1;i<=m;i++) {            if(i==num[k]) continue;            int xx=find(a[i].x);            int yy=find(a[i].y);            if(xx!=yy) {                fa[xx]=yy;                ans+=a[i].val;                t++;            }        }        if(t!=cnt) continue;        if(ans==dis) {            flag=true;            return;        }    }}int main() {    read(t);    while(t--) {        read(n);read(m);        for(int i=1;i<=m;i++) {read(a[i].x);read(a[i].y);read(a[i].val);}        sort(a+1,a+1+m,cmp);        MST();        if(flag) printf("Not Unique!\n");        else printf("%d\n",dis);    }    return 0;}
View Code