Title: Give a graph with weights to find a minimum loop through the start S and end point T.
Problem Analysis: Establish network, with S as the source point, T is the meeting point, and the capacity of each edge is 1, the unit cost is the edge weight value. To find the minimum cost flow, the minimum cost of augmentation two times is the answer.
The code is as follows:
# include<iostream># include<cstdio># include<cmath># include<string># include<vector ># include<list># include<set># include<map># include<queue># include<cstring># Include<algorithm>using namespace std;# define LL long long# define REP (i,s,n) for (int i=s;i<n;++i) # define CL (A, b) memset (A,b,sizeof (a)) # define CLL (A,b,n) Fill (a,a+n,b) const double inf=1e30;const int Inf=1<<30;const int n=105 ; struct edge{int fr,to,cap,flow,cost; Edge (int _fr,int _to,int _cap,int _flow,int _cost): fr (_fr), to (_to), Cap (_CAP), Flow (_flow), Cost (_cost) {}};vector< Edge>edges;vector<int>g[n];int p[n],a[n],d[n],inq[n];void init (int N) {edges.clear (); REP (I,0,n) g[i].clear ();} void Addedge (int u,int v,int cost) {Edges.push_back (Edge (u,v,1,0,cost)); Edges.push_back (Edge (v,u,0,0,-cost)); int m=edges.size (); G[u].push_back (m-2); G[v].push_back (m-1);} BOOL Bellmanford (int s,int t,int &flow,int &cost) { CL (inq,0); CLL (d,inf,t+1); D[s]=0,inq[s]=1,p[s]=0,a[s]=inf; queue<int>q; Q.push (s); while (!q.empty ()) {int U=q.front (); Q.pop (); inq[u]=0; REP (I,0,g[u].size ()) {Edge &e=edges[G[u][i]]; if (d[e.to]>d[u]+e.cost&&e.cap>e.flow) {d[e.to]=d[u]+e.cost; P[e.to]=g[u][i]; A[e.to]=min (A[u],e.cap-e.flow); if (!inq[e.to]) {inq[e.to]=1; Q.push (e.to); }}}} if (D[t]==inf) return false; FLOW+=A[T]; COST+=A[T]*D[T]; for (int x=t;x!=s;x=edges[p[x]].fr) {edges[p[x]].flow+=a[t]; EDGES[P[X]^1].FLOW-=A[T]; } return true; void solve (int s,int t) {int flow=0,cost=0; if (! Bellmanford (S,t,flow,cost)) printf ("Back to jail\n"); else{if (Bellmanford (s,t,flow,cost)) printf ("%d\n", cost); else printf ("Back to jail\n"); }}int Main () {int S,T,n,m,a,b,c; while (scanf ("%d", &n) &&n) {s=0,t=n-1; Init (n); scanf ("%d", &m); while (m--) {scanf ("%d%d%d", &a,&b,&c); Addedge (A-1,B-1,C); Addedge (B-1,A-1,C); } solve (s,t); } return 0;}
UVA-10806 Dijkstra, Dijkstra. (Minimum cost flow, network flow modeling)