#include <stdio.h> #include <string> #include <queue> #include <conio.h> using namespace std; #define N 105 #define inf 100000000 int g[N][N], d[N], num[N], pre[N]; int n, flow;
void init(int s, int t) { queue<int> que; int k; que.push(t); memset(d, 1, sizeof(d)); memset(num, 0, sizeof(num)); d[t] = 0; num[0] = 1;
while(que.empty() == 0) { k = que.front(); que.pop(); for(int i=0; i<n+2; i++) { if(d[i] >= n+2 && g[i][k] > 0) { d[i] = d[k] + 1; que.push(i); num[d[i]] ++; } } } }
int find_path(int i) { int j; for(j=0; j<n+2; j++) { if(g[i][j] > 0 && d[i] == d[j] + 1) return j; } return -1; }
int relable(int i) { int mm = inf; int j; for(j=0; j<n+2; j++) { if(g[i][j] > 0) mm = mm < d[j]+1 ? mm : d[j] + 1; } return mm == inf ? n : mm; }
int max_flow(int s, int t) { int flow = 0; int i, j, add, k;
i = s; memset(pre, -1, sizeof(pre)); while(d[s] < n+2) { j = find_path(i); if(j >= 0) { pre[j] = i; i = j; if(i == t) { add = inf; for(k=t; k!=s; k=pre[k]) add = add < g[pre[k]][k] ? add : g[pre[k]][k]; for(k=t; k!=s; k=pre[k]) { g[pre[k]][k] -= add; g[k][pre[k]] += add; } flow += add; i = s; } } else { int x = relable(i); num[x]++; num[d[i]]--; if(num[d[i]] == 0) return flow; d[i] = x; if(i != s) i = pre[i]; } } return flow; }
int main() { int i, j; int np, nc, m; int x, y, w; char ch;
freopen("in.txt", "r", stdin); while(scanf("%d%d%d%d", &n, &np, &nc, &m) != EOF) { memset(g, 0, sizeof(g)); for(i=0; i<m; i++) { scanf(" (%d,%d)%d", &x, &y, &w); g[x][y] = w; } for(i=0; i<np; i++) { scanf(" (%d)%d", &x, &w); g[n][x] = w; } for(i=0; i<nc; i++) { scanf(" (%d)%d", &x, &w); g[x][n+1] = w; } init(n, n+1); flow = max_flow(n, n+1); printf("%d\n", flow); } getch(); return 0; }
|