POJ-1679 The Unique MST,次小生成树模板题

Time Limit: 1000MS   Memory Limit: 10000K
     

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!

Source

接触的第一道次小生成树的题,还是有很多不足。

题意:t组测试数据,n个点,m条边,求最小生成树是否唯一。

思路:我们知道最小生成树再加入任何一条边都会成环,而且新加的这条边绝对不小于环中的任何一条边。次小生成树就是第二小生成树,与最小生成树差值最小。也就是新加入的边与环中最大边差距尽量小,我们在求最小生成树的时候可以将任意两点间的最大边用邻接矩阵存起来,然后依次遍历所有不在MST中的边替换生成树中环中最大的边。然后得出的最小值便是次小生成树。这里只需判断求出的次小生成树是否等于最小生成树。是则Not
Unique!

const int INF=0x3f3f3f3f;
const int N=200+10;
int n,m,d[N],w[N][N],ma[N][N],vis[N],pre[N],used[N][N];
int prim()
{
memset(vis,0,sizeof(vis));
memset(used,0,sizeof(used));
memset(ma,0,sizeof(ma));
for(int i=1;i<=n;i++) d[i]=w[1][i],pre[i]=1;
vis[1]=1;
pre[1]=-1;
int ans=0;
for(int i=2;i<=n;i++)
{
int x,m=INF;
for(int j=1;j<=n;j++)
if(!vis[j]&&m>d[j])
m=d[x=j];
vis[x]=1;
ans+=m;
used[pre[x]][x]=used[x][pre[x]]=1;
for(int j=1;j<=n;j++)
{
if(vis[j]) ma[j][x]=ma[x][j]=max(ma[pre[x]][j],d[x]);
if(!vis[j]&&d[j]>w[x][j])
d[j]=w[x][j],pre[j]=x;
}
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<N;i++)
for(int j=1;j<N;j++)
w[i][j]=i==j?0:INF;
int u,v,c;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&c);
w[u][v]=w[v][u]=c;
}
int ans=prim();
int res=INF;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(i!=j&&!used[i][j]&&w[i][j]!=INF)
res=min(res,ans+w[i][j]-ma[i][j]);//用不在MST中的边替换环中最大的边。
if(res==ans) printf("Not Unique!\n");
else printf("%d\n",ans);
}
return 0;
}
上一篇:POJ1679 The Unique MST —— 次小生成树


下一篇:POJ 1679 The Unique MST (次小生成树kruskal算法)