Net FLow Template

时间:2023-12-05 12:37:56

EK  Template :

bool bfs(int src, int des){
memset(pre, -, sizeof(pre));
while(!que.empty()) que.pop();
pre[src] = ;
int index;
que.push(src);
while(!que.empty()){
index = que.front();
que.pop();
for(int i = src; i <= des; ++i){
if(pre[i] == - && map[index][i] > ){
pre[i] = index;
if(i == des) return true;
que.push(i);
}
}
}
return false;
} int MaxFlow(int src, int des){
int maxflow = ;
while(bfs(src, des)){
int minflow = INF;
int i;
for(i = des; i != src; i = pre[i])
minflow = min(minflow, map[pre[i]][i]);
for(i = des; i != src; i = pre[i]){
map[pre[i]][i] -= minflow;
map[i][pre[i]] += minflow;
}
maxflow += minflow;
}
return maxflow;
}

SAP + GAP  Template :

int sap(int u,int flow){
if(u == src) return flow;
int ans = , i, t;
for(i = src; i <= des; ++i)
if(map[u][i] && dis[u] == dis[i] + ){
t = sap(i, min(flow - ans, map[u][i]));
map[u][i] -= t, map[i][u] += t,ans += t;
if(ans == flow) return ans;
}
if(dis[src] >= n + ) return ans;
if(!--gap[dis[u]]) dis[src] = n + ;
++gap[++dis[u]];
return ans;
}
	src = 1, des = n;
for(gap[0] = n + 2; dis[src] < n + 2; )
ans += sap(src,INF);