Split charge Flow
---------------------------------------------------------------------
#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>#include <queue>#include <vector>#define REP (i,n) for (int i=0;i<n;++i)#define CLR (x,c) memset (x,c,sizeof (x) )using namespace std;const int maxn=2000+5;const int inf=0x3f3f3f3f;struct Edge {int from,to,cap,flow,cost;};struct MCMF {bool INQ[MAXN];int D[MAXN];int A[MAXN];int P[MAXN];int n,s,t;vector<int> G[MAXN];vector<edge> edges;void init (int n) {this->n=n;Rep (I,n) g[i].clear ();edges.clear ();}void Addedge (int u,int v,int cap,int cost) {Edges.push_back (Edge) {u,v,cap,0,cost});Edges.push_back (Edge) {v,u,0,0,-cost});G[u].push_back (Edges.size ()-2);G[v].push_back (Edges.size ()-1);}bool SPFA (int &flow,int &cost) {CLR (d,inf); CLR (inq,0) ;d[s]=0; inq[s]=1; p[s]=0; A[s]=inf ;queue<int> Q;Q.push (s);While (!q.empty ()) {int X=q.front (); Q.pop ();inq[x]=0;Rep (I,g[x].size ()) {Edge &e=edges[g[x][i]];if (d[e.to]>d[x]+e.cost && e.cap>e.flow) {D[e.to]=d[x]+e.cost;P[e.to]=g[x][i];a[e.to]=min (a[x],e.cap-e.flow);if (!inq[e.to]) {Q.push (e.to); inq[e.to]=1;}}}}if (D[t]==inf) return false;Flow+=a[t];Cost+=d[t]*a[t];int x=t;While (x!=s) {Edges[p[x]].flow+=a[t];Edges[p[x]^1].flow-=a[t];X=edges[p[x]].from;}return true;}int mincost (int s,int t) {this->s=s; this->t=t;int flow=0,cost=0;while (SPFA (Flow,cost));return cost;}} g;int main (){//freopen ("test.in", "R", stdin);//freopen ("Test.out", "w", stdout);int n,m;while (scanf ("%d%d", &n,&m) ==2) {G.init (n*2+1);int a,b,c;While (m--) {scanf ("%d%d%d", &a,&b,&c);if (a>1 && a<n) a+=n;G.addedge (a,b,1,c);}for (int i=2;i<n;++i) G.addedge (i,i+n,1,0);G.addedge (0,1,2,0); G.addedge (n,n*2,2,0);printf ("%d\n", G.mincost (0,n*2));}return 0;}
---------------------------------------------------------------------
UVa 1658 Admiral (minimum cost maximum flow)