版本比较
费用流
正文
增加 50 行删除 11 行
12345667899101112131413141516171818192021222 行未改动25262728292930313132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980814882838485868754888990915892939495964 行未改动101102103104105711061071081091101111121131141151161175 行未改动```cppstruct node{ ll to,flow,cost,rev;};ll now[MAXN],dep[MAXN];ll now[MAXN],dep[MAXN],h[MAXN];bool vis[MAXN];vector<node>ed[MAXN];bool bfs(ll n,ll s,ll t)void spf(ll n,ll s,ll t){ for(int i=1;i<=n;i++) { now[i]=0; dep[i]=inf; h[i]=inf; vis[i]=0; } queue<ll>g; g.push(s); dep[s]=0; h[s]=0; while(!g.empty()) { ll u=g.front(); g.pop();2 行未改动 { ll to=ed[u][i].to; ll flow=ed[u][i].flow; ll cost=ed[u][i].cost; if(dep[to]>dep[u]+cost&&flow) if(h[to]>h[u]+cost&&flow) { dep[to]=dep[u]+cost; h[to]=h[u]+cost; if(!vis[to]) { vis[to]=1; g.push(to); } } } }}bool dij(ll n,ll s,ll t){ for(int i=1;i<=n;i++) { now[i]=0; dep[i]=inf; vis[i]=0; } priority_queue<pair<ll,ll> >g; g.push({0,s}); dep[s]=0; while(!g.empty()) { ll u=g.top().second; g.pop(); if(vis[u])continue; vis[u]=1; for(int i=0;i<ed[u].size();i++) { ll to=ed[u][i].to; ll flow=ed[u][i].flow; ll cost=ed[u][i].cost+h[u]-h[to]; if(dep[to]>dep[u]+cost&&flow) { dep[to]=dep[u]+cost; g.push({-dep[to],to}); } } } for(int i=1;i<=n;i++) { vis[i]=0; } if(dep[t]<inf)return 1; return 0;}pair<ll,ll> dfs(ll u,ll x,ll t){ if(u==t)return {x,0}; pair<ll,ll> ans={0ll,0ll}; vis[u]=1; for(int i=0;i<ed[u].size()&&x;i++) for(int i=now[u];i<ed[u].size()&&x;i++) { now[u]=i; ll to=ed[u][i].to; ll flow=ed[u][i].flow; ll cost=ed[u][i].cost; if(flow&&dep[u]+cost==dep[to]&&!vis[to]) if(flow&&dep[u]+cost+h[u]-h[to]==dep[to]&&!vis[to]) { pair<ll,ll> tt=dfs(to,min(x,flow),t); ll ttt=tt.first; if(!ttt)dep[to]=0; if(!ttt)vis[to]=1; ed[u][i].flow-=ttt; ed[to][ed[u][i].rev].flow+=ttt; ans={ans.first+ttt,ans.second+ttt*cost+tt.second}; x-=ttt;4 行未改动}pair<ll,ll> dinic(ll n,ll s,ll t){ pair<ll,ll> ans={0,0}; spf(n,s,t); while(bfs(n,s,t)) while(dij(n,s,t)) { pair<ll,ll> tt=dfs(s,inf,t); ans={ans.first+tt.first,ans.second+tt.second}; for(int i=1;i<=n;i++) { h[i]+=dep[i]; } } return ans;}void add(ll u,ll to,ll flow,ll cost)5 行未改动