我是靠谱客的博主 迷人苗条,最近开发中收集的这篇文章主要介绍POJ 1679 (次最小生成树),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

题目:

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<iostream>
#include<cstdio>
#include<algorithm>
#define Max 99999999
using namespace std;
int t,n,m;
int a[102],st[102];
struct node{
int x;
int y;
int d;
}g[10000],gg[10000];
void init()
{
int i,j;
for(i=0;i<=n;i++)
{
a[i]=i;
}
}
int find(int x)
{
if(x==a[x])return a[x];
a[x]=find(a[x]);
return a[x];
}
bool Union(int x,int y)
{
int xx=find(x);
int yy=find(y);
if(xx==yy)return false;
a[xx]=yy;
return true;
}
bool cmp(node p,node q)
{
return p.d <q.d ;
}
int main()
{
cin>>t;
while(t--)
{
scanf("%d%d",&n,&m);
int i,j,k,l;
init();
for(i=0;i<m;i++)
{
scanf("%d%d%d",&j,&k,&l);
g[i].x =j;g[i].y =k;
g[i].d =l;
}
int sum;
sort(g,g+m,cmp);
for(i=0,k=0,sum=0;i<m;i++)
{
if(Union(g[i].x ,g[i].y ))
{
sum=sum+g[i].d ;
st[k]=i;k++;//用st数组记录边
}
}
int ans;
for(i=0;i<k;i++)//遍历去掉一条边
{
ans=0;
l=g[st[i]].d ;
g[st[i]].d =Max;
for(j=0;j<m;j++)
{
gg[j].x =g[j].x ;
gg[j].y =g[j].y ;
gg[j].d =g[j].d ;
}
sort(gg,gg+m,cmp);
init();
for(j=0;j<m;j++)
{
if(Union(gg[j].x ,gg[j].y ))
{
ans=ans+gg[j].d ;
}
}
g[st[i]].d =l;
if(ans==sum)break;
}
if(i<k)
printf("Not Unique!n");
else printf("%dn",sum);
}
return 0;
}

 

最后

以上就是迷人苗条为你收集整理的POJ 1679 (次最小生成树)的全部内容,希望文章能够帮你解决POJ 1679 (次最小生成树)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(28)

评论列表共有 0 条评论

立即
投稿
返回
顶部