Loj #116. 有源汇有上下界最大流
题意如文章标题。。。
在有源汇可行流上从S到T再跑一遍最大流,可行流中T->S的流量+这次的最大流流量就是答案。
#include<bits/stdc++.h> #define ll long long #define pb push_back #define maxn 305 using namespace std; const int inf=1<<30; struct lines{ int to,flow,cap; }l[100005]; vector<int> g[maxn]; int t=-1,n,m,S,T,SS,TT; int inside[maxn],mx,tot=0; int cur[maxn],d[maxn]; bool v[maxn],flag=0; inline void add(int from,int to,int cap){ l[++t]=(lines){to,0,cap},g[from].pb(t); l[++t]=(lines){from,0,0},g[to].pb(t); } inline bool BFS(int start){ memset(v,0,sizeof(v)); queue<int> q; int x; lines e; d[start]=0,v[start]=1,q.push(start); while(!q.empty()){ x=q.front(),q.pop(); for(int i=g[x].size()-1;i>=0;i--){ e=l[g[x][i]]; if(flag&&g[x][i]>mx) continue; if(e.flow<e.cap&&!v[e.to]){ v[e.to]=1,d[e.to]=d[x]+1; q.push(e.to); } } } return flag?v[T]:v[TT]; } int dfs(int x,int a){ if(!a||(flag&&x==T)||(!flag&&x==TT)) return a; int flow=0,f,sz=g[x].size(); for(int &i=cur[x];i<sz;i++){ if(flag&&g[x][i]>mx) continue; lines &e=l[g[x][i]]; if(d[e.to]==d[x]+1&&(f=dfs(e.to,min(a,e.cap-e.flow)))){ flow+=f,a-=f; e.flow+=f,l[g[x][i]^1].flow-=f; if(!a) break; } } return flow; } inline bool can(){ int an=0; while(BFS(SS)){ memset(cur,0,sizeof(cur)); an+=dfs(SS,inf); } return an==tot; } inline int calc(){ int an=0; while(BFS(S)){ memset(cur,0,sizeof(cur)); an+=dfs(S,inf); } return an; } int main(){ scanf("%d%d%d%d",&n,&m,&S,&T); int uu,vv,bt,cl; SS=0,TT=n+1; for(int i=1;i<=m;i++){ scanf("%d%d%d%d",&uu,&vv,&bt,&cl); add(uu,vv,cl-bt); inside[vv]+=bt; inside[uu]-=bt; } mx=t; for(int i=1;i<=n;i++){ if(inside[i]>0) add(SS,i,inside[i]),tot+=inside[i]; else add(i,TT,-inside[i]); } add(T,S,inf); if(!can()){ puts("please go home to sleep"); return 0; } flag=1; printf("%d\n",l[t-1].flow+calc()); return 0; }
我爱学习,学习使我快乐