http://poj.org/problem?id=1679
题意:问最小生成树是否唯一
思路:
用Kruskal先求最小生成树,结果即为min,把所用到的边记录下来(这里是记录的对应的下表),然后枚举这些边,
每次去掉一个边再求一次最小生成树,结果为tmin,如果能构成最小生成树tmin==min,则说明最小生成树不唯一
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!
代码自己YY吧……
#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;
}
分享到:
相关推荐
先利用prim算法求出最小生成树,然后通过往MST里加边来判断新生成的最小生成树是否具有最小的权值,POJ上The Unique MST(1679)题是要求判断最小生成树是否唯一,此题其实根本不用这样做,但是为了练习球次小生成树...
3. **P1679(Unique_MST_prim).cpp 和 P1679(Unique_MST_kruskal).cpp** - 这两个文件都涉及了“唯一最小生成树”问题。Prim和Kruskal是两种常见的求解最小生成树的算法。在某些情况下,图可能有唯一的最小生成树...
### POJ1679 TheUniqueMST **题目链接:** <http://acm.pku.edu.cn/JudgeOnline/problem?id=1679> **核心知识点:** - **问题描述:** 验证给定图的最小生成树是否唯一。 - **解题思路:** 可以先通过Prim或...
2. **POJ1679 TheUniqueMST** - **题意**:判断最小生成树是否唯一。 - **解法**:Prim算法即可解决,虽然实现起来容易出错。 3. **POJ2728 DesertKing** - **题意**:要求找到具有最优比率的生成树。 - **...
POJ1679 - The Unique MST - **题目链接**:[POJ1679](http://acm.pku.edu.cn/JudgeOnline/problem?id=1679) - **解法概述**:这是一道判断是否存在唯一 MST 的问题,可以通过 Prim 或 Kruskal 算法来验证。 - **...