【次小生成树】POJ 1679 The Unique MST

[url]http://poj.org/problem?id=1679[/url]

[b][size=medium]
[color=red]题意:问最小生成树是否唯一[/color]

思路:
用Kruskal先求最小生成树,结果即为min,把所用到的边记录下来(这里是记录的对应的下表),然后枚举这些边,
每次去掉一个边再求一次最小生成树,结果为tmin,如果能构成最小生成树tmin==min,则说明最小生成树不唯一

[color=blue]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![/color]

代码自己YY吧……
[/size][/b]

#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <set>
//#include <map>
#include <queue>
#include <utility>
#include <stack>
#include <list>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
//#include <ctime>
#include <ctype.h>
using namespace std;
#define inf 0x3fffffff

int n, k, pre[105], num[10005], ind;
struct road{
int a, b;
int weight;
}r[10005];

bool cmp (road x, road y)
{
return x.weight < y.weight;
}

int find (int a)
{
while (a != pre[a])
a = pre[a];
return a;
}

int MST (int key)
{
int mincost = 0, i, tp = 0, A, B;
for (i = 1; i <= n; i++)
pre[i] = i;
for (i = 0; i < k; i++)
{
if (i == key)
continue;
A = find (r[i].a);
B = find (r[i].b);
if (A != B)
{
if (key == -1)
num[ind++] = i;
mincost += r[i].weight;
pre[B] = A;
}
}
for (i = 1; i <= n; i++)
{
if (pre[i] == i)
{
tp++;
if (tp > 1)
return inf;
}
}
return mincost;
}

int main()
{
int m, t, i, a, b, w, mins, tmins, tp;
scanf ("%d", &t);
while (t--)
{
k = ind = 0;
scanf ("%d%d", &n, &m);
while (m--)
{
scanf ("%d%d%d", &a, &b, &w);
r[k].a = a;
r[k].b = b;
r[k].weight = w;
k++;
}
sort (r, r+k, cmp);
mins = MST (-1);
tmins = inf;
for (i = 0; i < ind; i++)
{
tp = MST (num[i]);
if (tmins > tp)
tmins = tp;
}
if (tmins > mins)
printf ("%d\n", mins);
else puts ("Not Unique!");
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值