当前弧优化、单路增广
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n, m, ss, tt, uu, vv, ww, cnt, hea[10005], maxFlow, cur[10005], lev[10005];
const int oo=0x3f3f3f3f;
queue<int> d;
struct Edge{
int too, nxt, val;
}edge[200005];
void add_edge(int fro, int too, int val){
edge[cnt].nxt = hea[fro];
edge[cnt].too = too;
edge[cnt].val = val;
hea[fro] = cnt++;
}
bool bfs(){
memset(lev, 0, sizeof(lev));
lev[ss] = 1;
d.push(ss);
while(!d.empty()){
int x=d.front();
d.pop();
for(int i=hea[x]; i!=-1; i=edge[i].nxt){
int t=edge[i].too;
if(!lev[t] && edge[i].val>0){
d.push(t);
lev[t] = lev[x] + 1;
}
}
}
return lev[tt]!=0;
}
int dfs(int x, int lim){
if(x==tt) return lim;
for(int &i=cur[x]; i!=-1; i=edge[i].nxt){
int t=edge[i].too;
if(lev[t]==lev[x]+1 && edge[i].val>0){
int temp=dfs(t, min(lim, edge[i].val));
if(temp>0){
edge[i].val -= temp;
edge[i^1].val += temp;
return temp;
}
}
}
return 0;
}
void dinic(){
while(bfs()){
for(int i=1; i<=n; i++) cur[i] = hea[i];
int temp;
while(temp=dfs(ss, oo)) maxFlow += temp;
}
}
int main(){
cin>>n>>m>>ss>>tt;
memset(hea, -1, sizeof(hea));
for(int i=1; i<=m; i++){
scanf("%d %d %d", &uu, &vv, &ww);
add_edge(uu, vv, ww);
add_edge(vv, uu, 0);
}
dinic();
cout<<maxFlow<<endl;
return 0;
}
裸dinic
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
struct Edge{
int too, nxt, val;
}edge[200005];
int n, m, uu, vv, ww, cnt=0, maxFlow, hea[10005], ss, tt, lev[10005];
const int oo=0x3f3f3f3f;
queue<int> d;
void add_edge(int fro, int too, int val){
edge[cnt].nxt = hea[fro];
edge[cnt].too = too;
edge[cnt].val = val;
hea[fro] = cnt++;
}
bool bfs(){
memset(lev, 0, sizeof(lev));
lev[ss] = 1;
d.push(ss);
while(!d.empty()){
int x=d.front();
d.pop();
for(int i=hea[x]; i!=-1; i=edge[i].nxt){
int t=edge[i].too;
if(!lev[t] && edge[i].val>0){
lev[t] = lev[x] + 1;
d.push(t);
}
}
}
return lev[tt]!=0;
}
int dfs(int x, int lim){
if(x==tt) return lim;
int addFlow=0;
for(int i=hea[x]; i!=-1 && addFlow<lim; i=edge[i].nxt){
int t=edge[i].too;
if(lev[t]==lev[x]+1 && edge[i].val>0){
int tmp=dfs(t, min(lim-addFlow, edge[i].val));
edge[i].val -= tmp;
edge[i^1].val += tmp;
addFlow += tmp;
}
}
return addFlow;
}
int main(){
cin>>n>>m>>ss>>tt;
memset(hea, -1, sizeof(hea));
for(int i=1; i<=m; i++){
scanf("%d %d %d", &uu, &vv, &ww);
add_edge(uu, vv, ww);
add_edge(vv, uu, 0);
}
while(bfs()) maxFlow += dfs(ss, oo);
cout<<maxFlow<<endl;
return 0;
}