1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include <iostream> #include <iostream> #include <string.h>
using namespace std; const int maxn = 1e3+5; const int INF = 0x3f3f3f3f;
bool vis[maxn]; int dist[maxn]; int e[maxn][maxn]; int n,m; int sum; bool use[maxn][maxn]; int maxdist[maxn][maxn]; int pre[maxn];
int prim() { sum = 0; memset(vis,0,sizeof vis); memset(use,0,sizeof use); memset(maxdist,0,sizeof maxdist); vis[1] = 1; for (int i=2; i<=n; i++) { dist[i] = e[1][i]; pre[i] = 1; } pre[1] = 0;
for (int i=1; i<n; i++) { int minn = INF; int point = INF; for (int j=1; j<=n; j++) { if (!vis[j] && dist[j]<minn) { point = j; minn = dist[j]; } } vis[point] = 1; sum += minn; use[point][pre[point]] = use[pre[point]][point] = 1;
for (int j=1; j<=n; j++) { if (vis[j]) maxdist[j][point] = maxdist[point][j] =max(maxdist[j][pre[point]],dist[point]); if (!vis[j] && e[point][j] < dist[j]) { dist[j] = e[point][j]; pre[j] = point; } } } return sum; } int superprim() { int ans = INF; for (int i=1; i<=n; i++) { for (int j=i+1; j<=n; j++) { if (!use[i][j] && e[i][j]!=INF) ans = min(sum+e[i][j]-maxdist[i][j],ans); } } return ans; }
int main() {
int times; cin >> times; while (times--) { cin >> n >> m; memset(e,0x3f,sizeof e); for (int i=1; i<=m; i++) { int u,v,w; cin >> u >> v >> w; e[u][v] = e[v][u] = min(e[u][v],w); } if(prim()==superprim()) printf("Not Unique!\n"); else printf("%d\n",sum); } return 0; }
|