标签:
这题数据比较水,次小生成树最后要判断是否联通,这里写错了,照样过了。。。
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 const int maxn = 105; 6 struct node 7 { 8 int u,v,w; 9 }e[maxn*maxn]; 10 int fa[maxn],MST[maxn]; 11 bool cmp(node a,node b) 12 { 13 return a.w<b.w; 14 } 15 int findd(int x) 16 { 17 int rt = x; 18 while(rt!=fa[rt])rt = fa[rt]; 19 while(x!=rt) 20 { 21 int t = fa[x]; 22 fa[x] = rt; 23 x = t; 24 } 25 return rt; 26 } 27 int main() 28 { 29 int T;scanf("%d",&T); 30 while(T--) 31 { 32 int n,m;scanf("%d%d",&n,&m); 33 for(int i = 1;i<=m;++i) 34 scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w); 35 sort(e+1,e+1+m,cmp); 36 for(int i = 1;i<=n;++i)fa[i] = i; 37 int cnt = 0,w_MST = 0; 38 for(int i = 1;i<=m;++i) 39 { 40 int fx = findd(e[i].u),fy = findd(e[i].v); 41 if(fx==fy)continue; 42 fa[fx] = fy; 43 MST[++cnt] = i; 44 w_MST+=e[i].w; 45 } 46 int flag = 1; 47 for(int i = 1;i<=cnt;++i) 48 { 49 for(int j = 1;j<=n;++j)fa[j] = j; 50 int sum = 0; 51 for(int j = 1;j<=m;++j)if(j!=MST[i]) 52 { 53 int fx = findd(e[j].u),fy = findd(e[j].v); 54 if(fx==fy)continue; 55 fa[fx] = fy; 56 sum+=e[j].w; 57 } 58 int ok = 1; 59 for(int j = 2;j<=n;++j)if(fa[j]!=fa[1])//error 60 { 61 ok = 0;break; 62 } 63 64 if(ok && sum==w_MST){flag = 0;break;} 65 } 66 if(flag)printf("%d\n",w_MST); 67 else printf("Not Unique!\n"); 68 } 69 return 0; 70 }
标签:
原文地址:http://www.cnblogs.com/GJKACAC/p/4675608.html