POJ1679:The Unique MST(最小生成树)
The Unique MST
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 38430 | Accepted: 14045 |
题目链接:http://poj.org/problem?id=1679
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:
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 <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
typedef long long ll;
const int N = ;
int t,n,m;
struct Edge{
int u,v,w;
bool operator < (const Edge &A)const{
return w<A.w;
}
}e[N*N];
int f[N];
int find(int x){
return f[x]==x?f[x]:f[x]=find(f[x]);
}
int Kruskal(){
int ans=,cnt,j;
for(int i=;i<=n+;i++) f[i]=i;
for(int i=;i<=m;i++){
j=i;cnt=;
while(e[i].w==e[j].w && j<=m) j++,cnt++;
for(int k=i;k<j;k++){
int fx=find(e[k].u),fy=find(e[k].v);
if(fx==fy) cnt--;
}
for(int k=i;k<j;k++){
int fx=find(e[k].u),fy=find(e[k].v);
if(fx!=fy){
f[fx]=fy;
ans+=e[i].w;
cnt--;
}
}
if(cnt>) return -;
}
return ans ;
}
int main(){
cin>>t;
while(t--){
scanf("%d%d",&n,&m);
for(int i=;i<=m;i++){
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
e[i].u=u;e[i].v=v;e[i].w=w;
}
sort(e+,e+m+);
int ans = Kruskal();
if(ans==-) puts("Not Unique!");
else printf("%d\n",ans);
}
return ;
}
最新文章
- Eclipse的link方式安装JBPM6插件(JBPM学习之一)
- 关于file的上传文件
- spring源码学习之【准备】jdk动态代理例子
- JVM性能优化,提高Java的伸缩性
- mysql管理员操作
- Permutations java实现
- 用 JavaScript 修改样式元素
- delphi 控制 EXCEL 数据透视表
- linux内核--进程地址空间(三)
- Mysql配置调优(转自阿铭论坛)
- 基于Jquery 简单实用的弹出提示框
- 自用lca模板
- COM原理与实现之一
- 排序算法入门之选择排序-Java实现
- 动态的加载显示oracle警告日志文件内容
- Linux下命令行cURL的10种常见用法示例
- alter system set events
- git 从远程拉取代码、推代码的步骤
- Python select 详解(转)
- 数据结构与算法--最小生成树之Kruskal算法