#include <cstdio> #include <algorithm> #include <cstring> #include <vector> #include <queue> const int INF=0x3f3f3f3f; using namespace std; const int M=110; int n,m; vector<int> v[M]; int G[M][M]; struct Node { int u,v; int w; }; Node node[100000+10]; char vis[M][M]; bool cmp(Node a,Node b) { return a.w<b.w; } int p[M]; int f(int x) { return p[x]==x?x:p[x]=f(p[x]); } int MST() // kruskal build a new Graph by vector v. { int w=0; for(int i=0; i<n; i++) v[i].clear(); for(int i=0; i<n; i++) { p[i]=i; } sort(node,node+m,cmp); for(int i=0; i<m; i++) { if(f(node[i].u) != f(node[i].v)) { p[f(node[i].u)] = f(node[i].v); w+=node[i].w; v[node[i].u].push_back(node[i].v); v[node[i].v].push_back(node[i].u); vis[node[i].u][node[i].v]=1; vis[node[i].v][node[i].u]=1; } } return w; } int Max[M][M]; int viss[M]; queue<int>q; void BFS(int s) //BFS make the Max(u,v) means the max key of the path u->v in the MST. { memset(viss,0,sizeof(viss)); q.push(s); viss[s]=1; while(!q.empty()) { int temp = q.front(); q.pop(); for(int i=0; i<v[temp].size(); i++) { if(!viss[v[temp][i]] && !Max[v[temp][i]][s]) { q.push(v[temp][i]); viss[v[temp][i]]=1; Max[s][v[temp][i]] = Max[v[temp][i]][s] = max(G[temp][v[temp][i]],Max[s][temp]); } } } } int main() { int t; scanf("%d",&t); while(t--) { memset(vis,0,sizeof(vis)); memset(Max,0,sizeof(Max)); memset(G,0,sizeof(G)); scanf("%d %d",&n,&m); for(int i=0; i<m; i++) { scanf("%d %d %d",&node[i].u,&node[i].v,&node[i].w); node[i].u-=1; node[i].v-=1; G[node[i].u][node[i].v] = node[i].w; G[node[i].v][node[i].u] = node[i].w; } int ans1 = MST(); for(int i=0; i<n; i++) { BFS(i); } int ans2=INF; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(!vis[i][j] && G[i][j]) { ans2 = min(ans2,ans1+G[i][j]-Max[i][j]); } } } if(ans1 == ans2) { printf("Not Unique!\n"); } else { printf("%d\n",ans1); } } return 0; }
时间: 2024-12-21 02:14:21