SAP + GAP 邻接表:https://blog.csdn.net/Adolphrocs/article/details/84779575
SAP + GAP 邻接矩阵:https://blog.csdn.net/Adolphrocs/article/details/84779661
dinic 邻接矩阵:https://blog.csdn.net/Adolphrocs/article/details/84779732
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn=205;
const int maxx=200005;
int edge;
int to[maxx], flow[maxx], nex[maxx];
int head[maxn];
int n, np, nc, m;
void addEdge(int v, int u, int cap){
to[edge] = u, flow[edge] = cap, nex[edge] = head[v], head[v] = edge++;
to[edge] = v, flow[edge] = 0, nex[edge] = head[u], head[u] = edge++;
}
int vis[maxn];
int pre[maxn];
bool bfs(int s,int e) {
queue<int> que;
pre[s] = -1;
memset(vis, -1, sizeof(vis));
que.push(s);
vis[s] = 0;
while(!que.empty()) {
int u = que.front();
que.pop();
for(int i = head[u]; ~i; i = nex[i]) {
int v = to[i];
if(vis[v] == -1 && flow[i]) {
vis[v] = vis[u] + 1;
if(v == e)
return true;
que.push(v);
}
}
}
return false;
}
int dfs(int s, int t, int f){
if(s == t || !f)
return f;
int r = 0;
for(int i = head[s]; ~i; i = nex[i]) {
int v = to[i];
if(vis[v] == vis[s] + 1 && flow[i]) {
int d = dfs(v, t, min(f, flow[i]));
if(d > 0) {
flow[i] -= d;
flow[i ^ 1] += d;
r += d;
f -= d;
if(!f)
break;
}
}
}
if(!r)
vis[s] = INF;
return r;
}
int maxFlow(int s, int e) {//然后直接调用这个即可
int ans = 0;
while(bfs(s, e))
ans += dfs(s, e, INF);
return ans;
}
void init() {//记得每次使用前初始化
memset(head, -1, sizeof(head));
edge = 0;
}
int main() {
while(~scanf("%d%d%d%d", &n, &np, &nc, &m)) {//n作为源点,n+1作为汇点
init();
int ai, bi, ci;
for(int i = 0; i < m; i++) { //ai到bi最大传输量为ci
while(getchar() != '(');
scanf("%d%*c%d%*c%d", &ai, &bi, &ci);
addEdge(ai, bi, ci);
}
for(int i = 0; i < np; i++) {//ai最大发电量为bi
while(getchar() != '(');
scanf("%d%*c%d", &ai, &bi);
addEdge(n, ai, bi);
}
for(int i = 0; i < nc; i++) {//ai最大消耗量为bi
while(getchar() != '(');
scanf("%d%*c%d", &ai, &bi);
addEdge(ai, n + 1, bi);
}
printf("%d\n", maxFlow(n, n + 1));
}
return 0;
}