UVA 1658 Admiral Topic: in the figure to find two lines that do not intersect, the cost of these two lines is required to be the least. Problem-solving ideas: or the issue of the demolition of the building map. First, each point must be split into two points, such as a point split into A->a '. The two-point capacity between the start and end points is 2 and the cost is 0, ensuring that only two lines are found. The remaining points have a capacity of 1 for 0, guaranteed to go only once per point, and no overlap between the two lines. Then, according to the requirements of the question to continue to build the map. Each set of data reads in a, B, C, the edge capacity of a ' to B ' is 1, the cost is C. After the figure is finished, use Bellman-ford to realize MCMF.
#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <cstdlib>#include <queue>using namespace STD;typedef Long LongllConst intN =2005;Const intINF =0x3f3f3f3f;intN, M, S, t;intA[n], Pre[n], d[n], inq[n];structedge{intFrom, to, cap, flow; llCos;}; vector<Edge>Edges vector<int>G[n];voidInit () { for(inti =0; I <2N i++) g[i].clear (); Edges.clear ();}voidAddedge (intFromintTo,intCapintFlow, LLCos{Edges.push_back (Edge) {from, to, Cap,0,Cos}); Edges.push_back (Edge) {To, from,0,0, -Cos});intm = Edges.size (); G[from].push_back (M-2); G[to].push_back (M-1);}voidInput () {Addedge (1, n +1,2,0,0); for(inti =2; I <= N-1; i++) {Addedge (i, i + N,1,0,0); } Addedge (N,2N2,0,0);intU, v; ll C; for(inti =0; I < m; i++) {scanf("%d%d%lld", &u, &v, &c); Addedge (U + N, V,1,0, c); }}intBF (intSintTint& Flow, ll& cost) { Queue<int>Q;memset(INQ,0,sizeof(INQ));memsetA0,sizeof(a));memset(Pre,0,sizeof(pre)); for(inti =0; I <=2* n +1; i++) D[i] = INF; D[s] =0; A[s] = INF; Inq[s] =1;intFlag =1; Pre[s] =0; Q.push (s); while(! Q.empty ()) {intU = Q.front (); Q.pop (); Inq[u] =0; for(inti =0; I < g[u].size (); i++) {Edge &e = edges[g[u][i]];if(E.cap > E.flow && d[e.to] > D[u] + E.Cos) {d[e.to] = D[u] + E.Cos; A[e.to] = min (A[u], e.cap-e.flow); Pre[e.to] = G[u][i];if(!inq[e.to]) {Inq[e.to] =1; Q.push (e.to); }}} flag =0; }if(D[t] = = INF)return 0; Flow + = A[t]; Cost + = (LL) d[t] * (LL) a[t]; for(intu = t; U! = S; U = edges[pre[u]].from) {Edges[pre[u]].flow + = a[t]; edges[pre[u]^1].flow-= a[t]; }return 1;}intMCMF (intSintT, ll& cost) {intFlow =0; Cost =0; while(BF (S, t, flow, cost));returnFlow;}intMain () { while(scanf("%d%d", &n, &m) = =2) {s =1, t =2N ll cost; Init (); Input (); MCMF (S, t, cost);printf("%lld\n", cost); }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
UVA 1658 Admiral (minimum charge maximum flow)