POJ 2135 minimum cost maximum flow template title;
#include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <climits > #include <cctype> #include <iostream> #include <algorithm> #include <queue> #include < vector> #include <map> #include <set> #include <stack> #include <string> #define LL Long Long #
Define MAX 1010 #define EPS 1e-8 #define INF int_max using namespace std;
struct edge{int from, to,cap,flow,cost;};
vector<int>g[max];
vector<edge>edges;
int n;
void Init () {for (int i=0; i<max; i++) g[i].clear ();
Edges.clear ();
} void Addedge (int from, int to, int cap, int. cost) {Edges.push_back (Edge) {from,to,cap,0,cost});
Edges.push_back (Edge) {to,from,0,0,-cost});
int k = Edges.size ();
G[from].push_back (k-2);
G[to].push_back (k-1);
} int D[max],inq[max],p[max],a[max];
BOOL Bellman_ford (int s, int t, int& flow, int& cost) {for (int i=0; i<n; i++) d[i] = (i = = s? 0:inf);
memset (inq,0,sizeof (INQ)); Queue<int>q;
Inq[s] = 1;
P[s] = 0;
A[s] = INF;
Q.push (s);
while (!q.empty ()) {int u = q.front ();
Q.pop ();
Inq[u] = 0;
for (int i=0; i<g[u].size (); i++) {edge& e = edges[g[u][i]];
if (E.cap > E.flow && d[e.to] > D[u] + e.cost) {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]) {Q.push (e.to);
Inq[e.to] = 1;
}}}} if (d[t] = = INF) return false;
Flow + = A[t];
Cost + = A[t]*d[t];
int u = t;
while (U = s) {Edges[p[u]].flow + = a[t];
Edges[p[u]^1].flow-= a[t];
u = edges[p[u]].from;
} return true;
} int Mincost (int s, int t) {int flow = 0,cost = 0;
while (Bellman_ford (s,t,flow,cost));
return cost;
} int main () {int m;
while (scanf ("%d%d", &n,&m)! = EOF) {int x, y, Z;
Init ();
for (int i=0; i<m; i++) {scanf ("%d%d%d", &x,&y,&z);
Addedge (X,Y,1,Z);
Addedge (Y,X,1,Z);
} addedge (0,1,2,0);
Addedge (n,n+1,2,0); n + = 2;
printf ("%d\n", Mincost (0,n-1));
} return 0;
}