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
| #include <iostream> #include <algorithm> #include <string.h> #include <vector>
using namespace std; const int maxn = 1e3+5; const int inf = 0x3f3f3f3f;
int dist[maxn], e[maxn][maxn],pre[maxn],maxdist[maxn][maxn],use[maxn][maxn]; bool vis[maxn]; vector<pair<int, int>> edge[maxn]; int n, m;
int prim() { memset(dist, inf, sizeof dist); memset(vis,0,sizeof vis); dist[1] = 0; int ans = 0; for (int i = 1; i <= n; i++) { int minn = inf, point = -1; for (int j = 1; j <= n; j++) if (!vis[j] && minn > dist[j]) { minn = dist[j]; point = j; } if (point == -1) return -1; vis[point] = 1; ans += dist[point]; for (int j = 1; j <= n; j++) if (vis[j]) maxdist[point][j] = maxdist[j][point] = j == point ? 0 : max(maxdist[pre[point]][j], dist[point]); else if (dist[j] > e[point][j]) dist[j] = e[point][j], pre[j] = point; } return ans; } int check(int sum) { int ans = inf; for (int u=1; u<=n; u++) for (int i = 0; i < edge[u].size(); i++) { int v = edge[u][i].first, w = edge[u][i].second; if ((pre[v] != u && pre[u] != v) || e[u][v] != w || use[u][v]) ans = min(ans,sum - maxdist[u][v] + w); if ((pre[v] == u || pre[u] == v) && e[u][v] == w) use[u][v] = use[v][u] = 1; } return ans; } int main() { int times; cin >> times; for (int casei = 1; casei <= times; casei++) { memset(e, inf, sizeof e); memset(use,0,sizeof use); scanf("%d%d",&n,&m); for (int i = 1; i <= m; i++) { int u, v, w; scanf("%d%d%d",&u,&v,&w); e[u][v] = e[v][u] = min(e[u][v],w); if (u > v) swap(u,v); edge[u].push_back(make_pair(v,w)); } printf("Case #%d : ",casei); int ans = prim(); if (ans == -1) printf("No way\n"); else { ans = check(ans); ans == inf ? printf("No second way\n") : printf("%d\n",ans); } for (int i = 1; i <= n; i++) edge[i].clear(); } return 0; }
|