首页 > 代码库 > POJ 1679 The Unique MST(次短生成树)
POJ 1679 The Unique MST(次短生成树)
Language: The Unique MST
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;}
POJ 1679 The Unique MST(次短生成树)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。