您的位置:首页 > 产品设计 > UI/UE

poj 1679 The Unique MST【次小生成树】【判断最小生成树的唯一性】

2017-03-14 09:03 344 查看
The Unique MST

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 29428 Accepted: 10530
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!

AC代码:

/*
思路:
把第一次求最小生成树的经过的边依次进行删除,再进行下一次最小生成树的计算,
直到剩下的计算的值和第一次求的值相等(不唯一)或者找不到与之相同的最小生成树(唯一)
*/
#include<stdio.h>
#include<stdlib.h>
#include<vector>
using namespace std;

vector<int>edge[300];

#define INF 100000000
#define MAX 300

int map[MAX][MAX];
int vis[MAX];

int Prim(int n,int flag)//flag == 1;时,把最小生成树记录在edge中。flag==0;时,用于计算去掉第一次的边的后的最小生成树
{
int lowcost[MAX];
int mst[MAX];
int i,j,min,minid,sum=0;
for (i=1;i<=n;i++)
{
lowcost[i]=INF;
vis[i]=0;
mst[i]=-1;
}
lowcost[1]=0;
for(i=1;i<=n;i++)
{
min=INF;
for (j=1;j<=n;j++)
{
if(lowcost[j]<min && !vis[j])
{
min=lowcost[j];
minid=j;
}
}
sum+=min;
vis[minid]=1;
if(flag)
{
if(mst[minid]!=-1)//以minid为起点的边加入最小生成树集合
{
edge[mst[minid]].push_back(minid);
}
}
for (j=1;j<=n;j++)
{
if(map[minid][j]<lowcost[j] && !vis[j])
{
lowcost[j]=map[minid][j];
if(flag) mst[j]=minid;//用于求路径
}
}

}
return sum;
}

int main()
{
int T,m,n;
int a,b,c,i,j,ans;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
map[i][i]=0;
map[i][j]=INF;
}
for(i=0;i<=n;i++)
edge[i].clear(); //清除edge容器
for (i=0;i<m;i++)
{
scanf("%d%d%d",&a,&b,&c);
map[a][b]=map[b][a]=c;
}
ans=Prim(n,1);//f注意这里的1
int ok = 0;
for (int s=1;s<=n;s++)
{
for (j=0;j<edge[s].size();j++)
{
int t=edge[s][j];//记录起点为s的边
int tmp=map[s][t];//记录st的距离
map[s][t]=map[t][s]=INF;//取消一条边
int temp=Prim(n,0);//注意这里0
map[t][s]=map[s][t]=tmp;//恢复取消的那条边
if(temp==ans)
{
ok=1;
break;
}
}
if(ok) break;
}
if(ok)
{
printf("Not Unique!\n");
}
else
{
printf("%d\n",ans);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息