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
| #include"bits/stdc++.h" using namespace std; const int maxn = 105; const int maxm = 10005; struct edge { int u,v,w; }e[maxm]; int n,m,root,mn[maxn],fa[maxn],tp[maxn],lp[maxn],tot,ans; int zl() { while (233) { for(int i=1;i<=n;i++) { mn[i] = 1e9; fa[i] = tp[i] = lp[i] = 0; } for(int i=1,u,v,w;i<=m;i++) if(e[i].u!=e[i].v&&(w=e[i].w)<mn[v=e[i].v]) { mn[v] = w; fa[v] = e[i].u; } mn[root] = 0; for(int u=1;u<=n;u++){ ans += mn[u]; if (mn[u]==1e9) return -1; } for (int u=1,v=1;u<=n;u++,v=u) { while (v!=root&&tp[v]!=u&&!lp[v]) { tp[v] = u; v = fa[v]; } if (v!=root&&!lp[v]) { lp[v] = ++tot; for (int k=fa[v];k!=v;k=fa[k]) lp[k] = tot; } } if (!tot) return ans; for (int i=1;i<=n;i++) if(!lp[i]) lp[i] = ++tot; for (int i=1;i<=m;i++) { e[i].w -= mn[e[i].v]; e[i].u = lp[e[i].u]; e[i].v = lp[e[i].v]; } n = tot; root = lp[root]; tot = 0; } }
int main(){ cin>>n>>m>>root; for(int i=1;i<=m;i++) { int u,v,w; cin>>u>>v>>w; e[i] = {u,v,w}; } cout<<zl()<<endl; return 0; }
|