loj#117. 有源匯有上下界最小流
阿新 • • 發佈:2018-12-13
//#pragma GCC optimize(2) //#pragma GCC optimize(3) //#pragma GCC optimize(4) //#pragma GCC optimize("unroll-loops") //#pragma comment(linker, "/stack:200000000") //#pragma GCC optimize("Ofast,no-stack-protector") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #include<iostream> #include<queue> #include<cstring> using namespace std; const int N=50003+10,maxn=125003+10,inf=0x3f3f3f3f; struct edge{int to,Next,c,low;}e[maxn<<2]; int cnt,head[N],dis[N],in[N],out[N],cur[N],que[N]; int n,m,s,t; void add(int u,int v,int c,int low) { out[u]+=low;in[v]+=low; e[cnt].to=v;e[cnt].c=c;e[cnt].low=low;e[cnt].Next=head[u];head[u]=cnt++; e[cnt].to=u;e[cnt].c=0;e[cnt].low=low;e[cnt].Next=head[v];head[v]=cnt++; } bool bfs() { memset(dis,-1,sizeof dis); dis[s]=0; int Head=1,last=1;que[Head]=s; while(Head<=last) { int x=que[Head++]; if(x==t)return 1; for(int i=head[x];~i;i=e[i].Next) { int te=e[i].to; if(dis[te]==-1&&e[i].c>0) { dis[te]=dis[x]+1; que[++last]=te; } } } return 0; } int dfs(int x,int mx) { if(x==t )return mx; int flow = 0, f; for(int i=cur[x];~i;i=e[i].Next) { int te=e[cur[x]=i].to; if(e[i].c>0&&dis[te]==dis[x]+1&&(f=dfs(te,min(mx-flow,e[i].c)))) { e[i].c-=f;e[i^1].c+=f;flow+=f; if(flow == mx) break; } } if(!flow) dis[x] = 0; return flow; } int maxflow() { int ans=0,f; while(bfs()) { for(int i=0;i<=n+2;i++)cur[i]=head[i]; while((f=dfs(s,inf)))ans+=f; } return ans; } void init(){cnt=0;memset(head,-1,sizeof head);} int main() { // freopen("7.in","r",stdin); int ss,tt; scanf("%d%d%d%d",&n,&m,&ss,&tt); init(); for(int i=1; i<=m; i++) { int a,b,c,d; scanf("%d%d%d%d",&a,&b,&c,&d); add(a,b,d-c,c); } s=n+1,t=n+2; int sum=0; for(int i=1; i<=n; i++) { if(in[i]>out[i])sum+=in[i]-out[i],add(s,i,in[i]-out[i],0); else add(i,t,out[i]-in[i],0); } int flow=maxflow(); add(tt,ss,inf,0); flow+=maxflow(); if(sum!=flow)puts("please go home to sleep"); else printf("%d\n",e[cnt-1].c); return 0; } /******************** ********************/