POJ 1679The Unique MST
来源:互联网 发布:广联达软件下载免费 编辑:程序博客网 时间:2024/06/09 23:21
题目链接
题意:无向带权图。T组数据,每组数据首先输入节点数N与边数M,如果存在最小生成树且唯一则输出最小生成树的权值和,否则(最小生成树不唯一或者不能构成最小生成树)输出“Not Unique!”。
题目解析:判断最小生成树是否唯一。首先明确最小生成树不唯一的条件是:
- 边数大于N-1
- 存在权值相等的边
- 在构建最小生成树的过程中,存在权值和已选取的边相等的边因为构成回路的原因不能被选取(注意:有些边无论如何构建最小生成树都不会被选取。如:
4 5
1 2 1
2 3 1
1 3 2
3 4 2
1 4 3)
明确之后,首先我们要在输入的过程记录下权值相等的边,其次通过Prim算法或者Kruskal算法求出最小生成树的权值,如果不能构成最小生成树,直接输出。然后依次把之前标记的权值相等的边剔除初始的图,再次构建最小生成树,如果构建的最小生成树的权值与初始的最小生成树的权值相等,则说明最小生成树不唯一。
///最小生成树不唯一的条件:1、边数大于节点数-1 2、存在权值相等的边,在构建最小生成树时由于构成回路的原因,有些权值与被选取的边相等的边没有被选取#include <iostream>#include <cstdio>#include <fstream>#include <algorithm>#include <cmath>#include <deque>#include <vector>#include <queue>#include <string>#include <cstring>#include <map>#include <stack>#include <set>#include <climits>#include <iomanip>using namespace std;const int MAXN=1e4+10;const int maxx=INT_MAX;struct node{ int s, e, data; bool flag;///记录是否存在权值相等的边} z[MAXN];int N, M, parent[MAXN], suy, sum, step[MAXN];void Init(){ for(int i=1; i<=N; i++) parent[i]=i;}int Find(int a){ while(parent[a]!=a) a=parent[a]; return a;}bool cmp(struct node A, struct node B){ return A.data<B.data;}int Kruskal(){ suy=0; sum=0; int t=0; Init(); sort(z,z+M,cmp); for(int i=0; i<M; i++) { int a=Find(z[i].s); int b=Find(z[i].e); if(a!=b) { parent[a]=b; suy+=z[i].data; t++; if(z[i].flag)///记录在构建最小生成树的过程中所用到的权值相等的边的序号 step[sum++]=i; } if(t>=N-1) break; } return t;}int main(){ int T; while(cin>>T) { while(T--) { cin>>N>>M; for(int i=0; i<M; i++) { cin>>z[i].s>>z[i].e>>z[i].data; z[i].flag=false; } for(int i=0; i<M; i++) { for(int j=0; j<M; j++) { if(i!=j&&z[i].data==z[j].data) { z[i].flag=true; break; } } } int t=Kruskal(); int ro=suy;///记录初始最小生成树的权值和 bool flew=true; if(t<N-1) flew=false; else { for(int i=0; i<sum; i++)///依次剔除检索 { int k=z[step[i]].data; z[step[i]].data=maxx; t=Kruskal(); if(t==N-1&&suy==ro) { flew=false; break; } else z[step[i]].data=k; } } if(flew) cout<<ro<<endl; else cout<<"Not Unique!"<<endl; } } return 0;}
阅读全文
0 0
- POJ 1679 The Unique MST
- poj 1679 The Unique MST
- poj 1679 The Unique MST
- POJ 1679 The Unique MST
- poj 1679 The Unique MST
- poj 1679 The Unique MST
- POJ-1679 The Unique MST
- POJ 1679 The Unique MST
- POJ 1679 The Unique MST
- POJ-1679-The Unique MST
- Poj 1679 The Unique MST
- poj 1679 The Unique MST
- POJ-1679-The Unique MST
- POJ 1679 The Unique MST
- POJ 1679 The Unique MST
- POJ-1679-The Unique MST
- poj 1679 The Unique MST
- poj 1679-The Unique MST
- ORA-00001: unique constraint pk_****_key violated oracle imp 语句导入数据对oracle的数据字段操作顺序
- WebCollector 爬百度 搜索关键字排名 为何过几天返回结果全部是0? 10C
- Java设计模式——外观模式
- JAVA生成二维码输出jsp页面
- 测试中
- POJ 1679The Unique MST
- div随着内容的增加高度也自适应增加
- F
- windows封装DLL
- 第一次使用Android Studio时你应该知道的一切配置(三):gradle项目构建
- codeforces 459E E. Pashmak and Graph(dp)
- Java之IO(二)缓冲流、转换流
- 2017多校训练Contest3: 1008 RXD and math hdu6063
- Openlayers之离线加载ArcGIS Server瓦片