【模板】最小费用最大流
题目跳转
代码
#include<bits/stdc++.h>
using namespace std;
typedef int ll;
typedef pair<ll,ll> pll;
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 maxn=5e3+5,maxm=5e4+5,inf=1e9;
ll n,m,s,t,ecnt=1,head[maxn],dis[maxn],now[maxn],h[maxn],ans1,ans2;
bool vis[maxn];
queue<ll> q;
priority_queue<pll,vector<pll>,greater<pll>> pq;
struct node{
ll nxt,to,lim,val;
}e[maxm<<1];
void adde(ll u,ll v,ll w,ll c){
e[++ecnt].nxt=head[u];
e[ecnt].to=v;
e[ecnt].lim=w;
e[ecnt].val=c;
head[u]=ecnt;
e[++ecnt].nxt=head[v];
e[ecnt].to=u;
e[ecnt].lim=0;
e[ecnt].val=-c;
head[v]=ecnt;
}
void spfa(){
for(ll i=0;i<=n;i++){
h[i]=inf;
}
q.push(s);
vis[s]=true;
h[s]=0;
while(!q.empty()){
ll x=q.front();
q.pop();
vis[x]=false;
for(ll i=head[x];i;i=e[i].nxt){
ll y=e[i].to;
if(e[i].lim>0&&h[y]>h[x]+e[i].val){
h[y]=h[x]+e[i].val;
if(!vis[y]){
vis[y]=true;
q.push(y);
}
}
}
}
}
bool dijkstra(){
for(ll i=0;i<=n;i++){
vis[i]=false;
dis[i]=inf;
}
pq=priority_queue<pll,vector<pll>,greater<pll>>();
pq.push({0,s});
dis[s]=0;
while(!pq.empty()){
ll x=pq.top().second;
pq.pop();
if(!vis[x]){
vis[x]=true;
for(ll i=head[x];i;i=e[i].nxt){
ll y=e[i].to;
if(e[i].lim>0&&dis[y]>dis[x]+e[i].val+h[x]-h[y]){
dis[y]=dis[x]+e[i].val+h[x]-h[y];
pq.push({dis[y],y});
}
}
}
}
return dis[t]!=inf;
}
ll dfs(ll x,ll sum){
if(x==t){
return sum;
}
ll res=0,k;
vis[x]=true;
for(ll i=now[x];i&∑i=e[i].nxt){
now[x]=i;
ll y=e[i].to;
if(e[i].lim>0&&!vis[y]&&h[y]==h[x]+e[i].val){
k=dfs(y,min(sum,e[i].lim));
e[i].lim-=k;
e[i^1].lim+=k;
sum-=k;
res+=k;
ans2+=k*e[i].val;
}
}
vis[x]=false;
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(),c=rd();
adde(u,v,w,c);
}
spfa();
while(dijkstra()){
for(ll i=0;i<=n;i++){
vis[i]=false;
now[i]=head[i];
if(dis[i]!=inf){
h[i]+=dis[i];
}
}
ans1+=dfs(s,inf);
}
write(ans1);
pc(' ');
write(ans2);
fls();
return 0;
}
Goodbye!

浙公网安备 33010602011771号