洛谷P3376
https://www.luogu.com.cn/problem/P3376
Dinic算法
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=5e2+7;
const int maxm=2e5+7;
const ll INF=1e18;
int n,m,s,t;
//struct node{
// int e;
// ll v;
// int nxt;
//}edge[maxm];
int e[maxm],nxt[maxm];
ll val[maxm];
int dis[maxn];
int head[maxn];
int cnt=0;
int cur[maxn];
ll minn(ll a, ll b){
return a>b?b:a;
}
void add(int u,int v,int w){
// edge[cnt].e=v;
// edge[cnt].v=w;
// edge[cnt].nxt=head[u];
e[cnt]=v;
val[cnt]=w;
nxt[cnt]=head[u];
head[u]=cnt++;
}
inline bool bfs(){
for(int i=1;i<=n;i++) dis[i]=-1;
dis[s]=0;
queue<int> q;
q.push(s);
while(!q.empty()){
int r=q.front();
q.pop();
// for(int i=head[r];i!=0;i=edge[i].nxt){
for(int i=head[r];i!=-1;i=nxt[i]){
// int j=edge[i].e;
int j=e[i];
// if(dis[j]==-1&&edge[i].v){
if(dis[j]==-1&&val[i]>0){
dis[j]=dis[r]+1;
q.push(j);
if(j==t) return 1;
}
}
}
return 0;
}
ll dfs(int u,ll flo){
if(u==t) return flo;
ll ans=0;
// for(int i=cur[u];i!=0;i=edge[i].nxt){
for(ll i=cur[u];i!=-1&&flo;i=nxt[i]){
// if(detla<=0) break;
cur[u]=i;
// int v=edge[i].e;
int v=e[i];
// if(dis[v]==(dis[u]+1)&&edge[i].v){
if(dis[v]==(dis[u]+1)&&val[i]){
// ll b=dfs(v,minn(edge[i].v,detla));
ll b=dfs(v,minn(val[i],flo));
if(!b) dis[b]=-1;//剪枝
// edge[i].v-=b;edge[i^1].v+=b;
val[i]-=b; val[i^1]+=b;
flo-=b;
ans+=b;
}
}
return ans;
}
ll dini(){
ll ans=0;
while(bfs()){
for(int i=1;i<=n;i++) cur[i]=head[i];
ans+=dfs(s,INF);
}
return ans;
}
int main(){
memset(head,-1,sizeof head);
scanf("%d%d%d%d",&n,&m,&s,&t);
for(int i=0;i<m;i++){
int a,b;
int c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
add(b,a,0);
}
printf("%lld",dini());
return 0;
}