最大流
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define MAXVERTEX 20
#define MAXARC 2001
#define INF 0x7fffffff
using namespace std;
struct Edge {
int v, w, next;
}edge[MAXARC];
int vertex, arc, cnt_edge, head[MAXVERTEX];
int pre[MAXVERTEX], dis[MAXVERTEX], cur[MAXVERTEX], gap[MAXVERTEX];
void Insert_Edge( int u , int v , int w ) {
edge[cnt_edge].v = v; edge[cnt_edge].w = w;
edge[cnt_edge].next = head[u]; head[u] = cnt_edge ++;
}
int i_sap(int source, int sink)
{
int u(source), v, min_dis, max_flow(0), path_flow(INF);
memset(gap, 0, sizeof(gap));
memset(dis, 0, sizeof(dis));
for(int i = 0; i <= sink; i ++)
cur[i] = head[i];
gap[0] = sink; pre[source] = source;
while( dis[source] < sink ) {
loop:
for( int &i = cur[u]; -1 != i; i = edge[i].next ) {
v = edge[i].v;
if( !edge[i].w || (dis[u] != dis[v]+1) ) continue;
pre[v] = u; path_flow = min(path_flow, edge[i].w);
u = v;
if( v == sink ) {
for(u = pre[u]; v != source; v = u, u = pre[u]) {
edge[cur[u]].w -= path_flow; edge[cur[u]^1].w += path_flow;
}
max_flow += path_flow; path_flow = INF;
}
goto loop;
}
min_dis = sink;
for(int i = head[u]; -1 != i; i = edge[i].next) {
v = edge[i].v;
if( edge[i].w && (min_dis > dis[v]) ) {
cur[u] = i; min_dis = dis[v];
}
}
if( --gap[dis[u]] == 0 ) break;
gap[ dis[u] = min_dis+1 ]++;
u = pre[u];
}
return max_flow;
}
int main(int argc, char const *argv[])
{
//freopen("test.in", "r", stdin);
int cnt(1), cas, s, f, v;
scanf("%d", &cas);
while( cas-- ) {
cnt_edge = 0;
scanf("%d %d", &vertex, &arc);
memset(head, -1, sizeof(int)*vertex);
for(int i = 0; i < arc; i ++) {
scanf("%d %d %d", &s, &f, &v);
Insert_Edge(s, f, v);
Insert_Edge(f, s, 0);
}
printf("Case %d: %d\n", cnt ++, i_sap(1, vertex));
}
return 0;
}