【模板】网络最大流
题目跳转
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
uint8_t buf[1<<20],*p1,*p2;
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
ll rd(){
ll x=0,f=1,ch=gc();
while(ch!=EOF&&(ch<'0'||ch>'9')){
if(ch=='-'){
f=-1;
}
ch=gc();
}
if(ch==EOF){
return x;
}
while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch-'0');
ch=gc();
}
return x*f;
}
uint8_t obuf[1<<20],*op=obuf;
#define fls() (fwrite(obuf,1,op-obuf,stdout),op=obuf,0)
#define pc(ch) (op==obuf+(1<<20)?fls():0,*op++=(ch))
void write(ll x){
if(x<0){
x=-x;
pc('-');
}
if(x>9){
write(x/10);
}
pc(x%10+'0');
}
const ll maxm=5e3+5,maxn=2e2+5,inf=1e18;
ll n,m,s,t,ecnt=1,head[maxn],now[maxn],dis[maxn],ans,mp[maxn][maxn];
queue<ll> q;
struct node{
ll nxt,to,val;
}e[maxm<<1];
void adde(ll u,ll v,ll w){
e[++ecnt].nxt=head[u];
e[ecnt].to=v;
e[ecnt].val=w;
head[u]=ecnt;
}
bool bfs(){
q=queue<ll>();
for(ll i=1;i<=n;i++){
dis[i]=inf;
}
q.push(s);
dis[s]=0;
now[s]=head[s];
while(!q.empty()){
ll x=q.front();
q.pop();
for(ll i=head[x];i;i=e[i].nxt){
ll y=e[i].to;
if(e[i].val>0&&dis[y]==inf){
now[y]=head[y];
dis[y]=dis[x]+1;
if(y==t){
return true;
}
q.push(y);
}
}
}
return false;
}
ll dfs(ll x,ll sum){
if(x==t){
return sum;
}
ll k,res=0;
for(ll i=now[x];i&∑i=e[i].nxt){
now[x]=i;
ll y=e[i].to;
if(e[i].val>0&&dis[y]==dis[x]+1){
k=dfs(y,min(sum,e[i].val));
if(k==0){
dis[y]=inf;
}else{
e[i].val-=k;
e[i^1].val+=k;
res+=k;
sum-=k;
}
}
}
return res;
}
int main(){
n=rd();
m=rd();
s=rd();
t=rd();
for(ll i=1;i<=m;i++){
ll u=rd(),v=rd(),w=rd();
mp[u][v]+=w;
}
for(ll i=28;i>=0;i-=4){
for(ll u=1;u<=n;u++){
for(ll v=u+1;v<=n;v++){
if((mp[u][v]>0||mp[v][u]>0)&&(mp[u][v]>=(1<<i)||mp[v][u]>=(1<<i))){
adde(u,v,mp[u][v]);
adde(v,u,mp[v][u]);
mp[u][v]=0;
mp[v][u]=0;
}
}
}
while(bfs()){
ans+=dfs(s,inf);
}
}
write(ans);
fls();
return 0;
}
Goodbye!

浙公网安备 33010602011771号