Description
Given a connected undirected graph, tell if its minimum spanning tree is unique.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
次小生成樹問題,看了我好久,感覺還是差那麼一點點啊,看了好多大神的博客,自己重寫了一下,終於過了,思路還不是很清晰啊,prim算法中運用的dp的思想,對dp還是不怎麼懂啊,下階段要好好看看dp,krusal的次小生成樹還沒怎麼看懂,還是要多做題;
參考了博客http://blog.csdn.net/jarily/article/details/8912538
直接把其中的算法介紹部分轉過來啦,還是要多看幾遍
這裡面的用了一個path數組儲存兩點中權值最大的那條路徑;
low數組保存邊的權值;
用pre數組保存前驅的位置,用一個uesd數組標記是否在生成樹中;
#include如果生成的次小生成樹和最小生成樹相等說明不唯一,不相等說明唯一;#include #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) const int maxn=100+5; const int INF=0x3fffffff; int map[maxn][maxn],low[maxn]; int path[maxn][maxn],pre[maxn];//從i到j的路徑上最大邊的權值 int visit[maxn],used[maxn][maxn];//標記數組 int n,m; int prim() { int i,j,pos,mst=0; memset(visit,0,sizeof(visit));//初始化 memset(path,0,sizeof(path)); memset(used,0,sizeof(used)); visit[1]=1; for(i=1;i<=n;i++) { low[i]=map[1][i]; pre[i]=1;//記錄前驅 } for(i=1;i map[pos][j]) { low[j]=map[pos][j];//更新low數組 pre[j]=pos; } } } return mst; } int main() { int t,x,y,w,i,j; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); for(i=1;i<=n;i++) for(j=1;j<=n;j++) map[i][j]=INF;//把map初始化為INF for(i=1;i<=m;i++) { scanf("%d%d%d",&x,&y,&w); map[x][y]=map[y][x]=w; } int mst; int res=INF; mst=prim(); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { if(i!=j&& !used[i][j]) res=min(res,mst+map[i][j]-path[i][j]);//生成次小生成樹 } if(res==mst) puts("Not Unique!"); else printf("%d\n",mst); } return 0; }
最小生成樹中加入一條邊,再刪除最小生成樹中的一條邊,就得到次小生成樹,這裡主要進行了預處理,對權值較大的路徑進行預處理。
這個博客的次小生成樹講的不錯 http://www.cnblogs.com/hxsyl/p/3290832.html
kruskal待更新;