完全参考自:
http://www.cnblogs.com/wally/archive/2013/08/29/3288898.html
建好图,套个模板就OK了。
code:
#include <bits/stdc++.h>
using namespace std;
const int N = 105;
const int M = 1005;
const int INF = 0x3f3f3f3f;
typedef long long LL;
struct Edge {
int from, to, cap, flow, cost ,next;
}edge[512345];
struct MCMF {
int s, t, cnt;
int head[N], a[N], d[N], p[N];
bool inq[N];
int init(int ss, int tt) {
s = ss, t = tt;
cnt = 0;
memset(head, -1, sizeof(head));
}
inline void addEdge(int u, int v, int cap, int cost) {
edge[cnt] = (Edge){u, v, cap, 0, cost, head[u]};
head[u] = cnt++;
edge[cnt] = (Edge){v, u, 0, 0, -cost, head[v]};
head[v] = cnt++;
}
bool SPFA(int &flow, int &cost) {
memset(d, INF, sizeof(d));
memset(inq, false, sizeof(inq));
queue <int> q;
q.push(s), inq[s] = true;
a[s] = INF, d[s] = 0, p[s] = -1;
while(!q.empty()) {
int u = q.front();
q.pop(), inq[u] = false;
for(int i = head[u];i != -1; i = edge[i].next) {
Edge &e = edge[i];
if(e.cap > e.flow && d[e.to] > d[u]+e.cost) {
d[e.to] = d[u]+e.cost;
a[e.to] = min(a[u], e.cap-e.flow);
p[e.to] = i;
if(!inq[e.to]) {
inq[e.to] = true;
q.push(e.to);
}
}
}
}
if(d[t] == INF) return false;
cost += d[t]*a[t];
flow += a[t];
int u = t;
while(u != s) {
edge[p[u]].flow += a[t];
edge[p[u]^1].flow -= a[t];
u = edge[p[u]].from;
}
return true;
}
void solve(int& flow, int& cost) {
while(SPFA(flow, cost));
}
}mcmf;
int n, m, s, t;
int in[N], out[N];
int main() {
int T, cas = 0;
scanf("%d" ,&T);
while(T--) {
scanf("%d%d%d%d", &n, &m, &s, &t);
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
mcmf.init(0, n+1);
in[s]++, out[t]++;
int sum = 0;
{
int u, v, a, b;
for(int i = 0;i < m; i++) {
scanf("%d%d%d%d", &u, &v, &a, &b);
if(a > b){
mcmf.addEdge(u, v, 1, a-b);
sum += b;
}
else{
mcmf.addEdge(v, u, 1, b-a);
in[v]++, out[u]++;
sum += a;
}
}
}
int tolflow = 0;
for(int i = 1;i <= n; i++) {
if(in[i] == out[i]) continue;
if(in[i] > out[i]) {
mcmf.addEdge(0, i, in[i]-out[i], 0);
tolflow += in[i]-out[i];
}
else
mcmf.addEdge(i, n+1, out[i]-in[i], 0);
}
printf("Case %d: ", ++cas);
int flow = 0, cost = 0;
mcmf.solve(flow, cost);
if(flow == tolflow)
printf("%d\n", sum+cost);
else
puts("impossible");
}
return 0;
}