【POJ】1679 The Unique MST
题目链接:http://poj.org/problem?id=1679
题意:给你一组数据,让你判断是否是唯一的最小生成树。
题解:这里用的是kuangbin大佬的次小生成树的模板。直接判断一下次小生成树的最小花费和最小生成树的是否一样即可。
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 using namespace std; 6 const int maxn = 110; 7 const int inf = 0x3f3f3f3f; 8 9 bool vis[maxn]; 10 int lowc[maxn]; 11 int pre[maxn]; 12 int Max[maxn][maxn];//Max[i][j]表示在最小生成树中从i到j的路径中的最大边权 13 bool used[maxn][maxn]; 14 int mp[maxn][maxn]; 15 int n,m; 16 17 18 int prim(){ 19 int ans = 0; 20 memset(vis,false,sizeof(vis)); 21 memset(Max,0,sizeof(Max)); 22 memset(used,false,sizeof(used)); 23 24 vis[0] = true; 25 pre[0] = -1; 26 27 for(int i = 1; i < n; i++){ 28 lowc[i] = mp[0][i]; 29 pre[i] = 0; 30 } 31 32 lowc[0] = 0; 33 for(int i = 1 ; i < n;i++){ 34 int minc = inf; 35 int p = -1; 36 for(int j = 0; j < n;j++) 37 if(!vis[j] && minc > lowc[j]){ 38 minc = lowc[j]; 39 p = j; 40 } 41 if(minc == inf) return -1; 42 ans += minc; 43 vis[p] = true; 44 used[p][ pre[p] ] = used[ pre[p] ][p] = true; 45 for(int j = 0 ; j < n; j++){ 46 if(vis[j]) 47 Max[j][p] = Max[p][j] = max(Max[j][ pre[p] ],lowc[p]); 48 if(!vis[j] && (lowc[j] > mp[p][j] ) ){ 49 lowc[j] = mp[p][j]; 50 pre[j] = p; 51 } 52 } 53 } 54 return ans; 55 } 56 int ans; 57 int smst(){ 58 int minn = inf; 59 for(int i = 0; i < n; i++) 60 for(int j = i+1 ; j < n;j++) 61 if(mp[i][j] != inf && !used[i][j]){ 62 minn = min(minn, ans + mp[i][j] - Max[i][j]); 63 } 64 if(minn == inf) return -1;//不存在 65 return minn; 66 } 67 68 int main(){ 69 int T; 70 cin>>T; 71 while(T--){ 72 cin>>n>>m; 73 int x,y,w; 74 memset(mp,inf,sizeof(mp)); 75 for(int i = 0; i < n ;i++){ 76 mp[i][i] = 0; 77 } 78 while(m--){ 79 cin>>x>>y>>w; 80 x--,y--; 81 mp[x][y] = mp[y][x] = w; 82 } 83 ans = prim(); 84 //cout<<smst()<<endl; 85 if(ans == -1){ 86 cout<<"Not Unique!"<<endl; 87 } 88 else if( ans == smst()){ 89 cout<<"Not Unique!"<<endl; 90 } 91 else{ 92 cout<<ans<<endl; 93 } 94 } 95 96 return 0; 97 }