Title Link: http://www.lightoj.com/volume_showproblem.php?problem=1380
The smallest tree diagram is the smallest spanning trees of the graph. The ordinary prim cannot be solved.
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <string>#include <queue>using namespace STD;Const intINF =0x3f3f3f3f;Const intMAXN =1010;Const intMAXM =400100;structedge{intU, V, cost;}; Edge EDGE[MAXM];intPRE[MAXN], ID[MAXN], VISIT[MAXN], IN[MAXN];intZhuliu (intRootintNintM, Edge edge[]) {intres =0, u, v; while(1) { for(inti =0; I < n; i++) In[i] = INF; for(inti =0; I < m; i++)if(edge[i].u! = edge[i].v && edge[i].cost < IN[EDGE[I].V]) {PRE[EDGE[I].V] = edge[i].u; IN[EDGE[I].V] = Edge[i].cost; } for(inti =0; I < n; i++)if(I! = root && in[i] = = INF)return-1;intTN =0;memset(ID,-1,sizeof(ID));memset(Visit,-1,sizeof(visit)); In[root] =0; for(inti =0; I < n; i++) {res + = In[i]; v = i; while(Visit[v]! = i && id[v] = =-1&& v! = root) {Visit[v] = i; v = pre[v]; }if(v! = root && id[v] = =-1) { for(intU = pre[v]; U! = V; u = pre[u]) id[u] = TN; ID[V] = tn++; } }if(TN = =0) Break; for(inti =0; I < n; i++)if(Id[i] = =-1) Id[i] = tn++; for(inti =0; I < m;) {v = edge[i].v; EDGE[I].U = id[edge[i].u]; EDGE[I].V = id[edge[i].v];if(edge[i].u! = edge[i].v) Edge[i++].cost-= In[v];ElseSwap (Edge[i], edge[--m]); } n = tn; root = Id[root]; }returnRes;}intG[MAXN][MAXN];inta[ -];intsum[ -];voidInitintN) { for(inti =0; I <= N; i++) for(intj =0; J <= N; J + +) {if(i = = j) G[i][j] =0;ElseG[I][J] = g[j][i] = INF; }}intMain () {intT, N, M, k,a,b,c;scanf("%lld", &t); for(intKK =1; KK <= T; kk++) {scanf("%d%d%d", &n, &m, &k); Init (n); while(m--) {scanf("%d%d%d", &a, &b, &c);if(G[a][b] > C) g[a][b] = C; }intL =0; for(inti =0; I < n; i++) for(intj =0; J <= N; J + +) {if(G[i][j] < INF) {edge[l].u = i; EDGE[L].V = j; Edge[l++].cost = G[i][j]; } }intAns = Zhuliu (K,n,l,edge);if(ans! =-1)printf("Case%d:%d\n", KK, ans);Else printf("Case%d:impossible\n", KK); }return 0;}
Lightoj 1380–teleport "minimum tree diagram"