大意不再赘述。
思路:网络流入门题,解这一题的关键在于题目的理解与图的构造,由于是多源点、汇点,我们可以认为地添加一个源点s = n+1, 汇点t = n+2。
网络流 = 模板+数学建模。
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <string> using namespace std; const int MAXN = 1010; const int MAXM = 1010*1010; const int INF = 0x3f3f3f3f; struct Edge { int v, next; int f; }edge[MAXM]; int cnt; int n, np, nc, m; int s, t; int first[MAXN], level[MAXN]; int q[MAXN]; void init() { cnt = 0; memset(first, -1, sizeof(first)); memset(q, 0, sizeof(q)); } void read_graph(int u, int v, int f) { edge[cnt].v = v, edge[cnt].f = f; edge[cnt].next = first[u], first[u] = cnt++; edge[cnt].v = u, edge[cnt].f = 0; edge[cnt].next = first[v], first[v] = cnt++; } int bfs(int s, int t) { memset(level, 0, sizeof(level)); level[s] = 1; int front = 0, rear = 1; q[front] = s; while(front < rear) { int x = q[front++]; if(x == t) return 1; for(int e = first[x]; e != -1; e = edge[e].next) { int v = edge[e].v, f = edge[e].f; if(!level[v] && f) { level[v] = level[x] + 1; q[rear++] = v; } } } return 0; } int dfs(int u, int maxf, int t) { if(u == t) return maxf; int ret = 0; for(int e = first[u]; e != -1; e = edge[e].next) { int v = edge[e].v, f = edge[e].f; if(level[v] == level[u] + 1 && f) { int Min = min(maxf-ret, f); f = dfs(v, Min, t); edge[e].f -= f; edge[e^1].f += f; ret += f; if(ret == maxf) return ret; } } return ret; } int Dinic(int s, int t) { int ans = 0; while(bfs(s, t)) ans += dfs(s, INF, t); return ans; } void read_case() { init(); s = n+1, t = n+2; for(int i = 1; i <= m; i++) { int u, v, f; while(getchar() != '(' ) ; scanf("%d,%d)%d", &u, &v, &f); read_graph(u, v, f); } for(int i = 1; i <= np; i++) { int v, f; while(getchar() != '(' ) ; scanf("%d)%d", &v, &f); read_graph(s, v, f); } for(int i = 1; i <= nc; i++) { int u, f; while(getchar() != '(' ) ; scanf("%d)%d", &u, &f); read_graph(u, t, f); } } void solve() { read_case(); int ans = Dinic(s, t); printf("%d\n", ans); } int main() { while(~scanf("%d%d%d%d", &n, &np, &nc, &m)) { solve(); } return 0; }