LOJ - #116. 有源汇有上下界最大流(有源汇有上下界的最大流)
生活随笔
收集整理的這篇文章主要介紹了
LOJ - #116. 有源汇有上下界最大流(有源汇有上下界的最大流)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個 n 個點和 m 條邊的有向圖,每條邊都有一個流量限制 [ lower , upper ],給定源點 s 和匯點 t ,求出源點到匯點的最大流
題目分析:參考博客:https://zybuluo.com/xiaoziyao/note/1694812
無源匯上下界可行流:
有源匯上下界可行流:
設(shè)源點為 s ,匯點為 t
有源匯上下界最大流:
有源匯上下界最小流:
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<unordered_map> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=210;int du[N];//入度 struct Edge {int to,w,next; }edge[N*N];//邊數(shù)int head[N],cnt;void addedge(int u,int v,int w) {edge[cnt].to=v;edge[cnt].w=w;edge[cnt].next=head[u];head[u]=cnt++;edge[cnt].to=u;edge[cnt].w=0;//反向邊邊權(quán)設(shè)置為0edge[cnt].next=head[v];head[v]=cnt++; }int d[N],now[N];//深度 當(dāng)前弧優(yōu)化bool bfs(int s,int t)//尋找增廣路 {memset(d,0,sizeof(d));queue<int>q;q.push(s);now[s]=head[s];d[s]=1;while(!q.empty()){int u=q.front();q.pop();for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].to;int w=edge[i].w;if(d[v])continue;if(!w)continue;d[v]=d[u]+1;now[v]=head[v];q.push(v);if(v==t)return true;}}return false; }int dinic(int x,int t,int flow)//更新答案 {if(x==t)return flow;int rest=flow,i;for(i=now[x];i!=-1&&rest;i=edge[i].next){int v=edge[i].to;int w=edge[i].w;if(w&&d[v]==d[x]+1){int k=dinic(v,t,min(rest,w));if(!k)d[v]=0;edge[i].w-=k;edge[i^1].w+=k;rest-=k;}}now[x]=i;return flow-rest; }void init() {memset(now,0,sizeof(now));memset(head,-1,sizeof(head));cnt=0; }int solve(int st,int ed) {int ans=0,flow;while(bfs(st,ed))while(flow=dinic(st,ed,inf))ans+=flow;return ans; }int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);init();int n,m,s,t;scanf("%d%d%d%d",&n,&m,&s,&t);while(m--){int u,v,lower,upper;scanf("%d%d%d%d",&u,&v,&lower,&upper);addedge(u,v,upper-lower);du[u]-=lower,du[v]+=lower;}int st=N-1,ed=st-1,sum=0;for(int i=1;i<=n;i++){if(du[i]>0){addedge(st,i,du[i]);sum+=du[i];}elseaddedge(i,ed,-du[i]);}addedge(t,s,inf);if(solve(st,ed)!=sum){puts("please go home to sleep");return 0;}int ans=edge[cnt-1].w;edge[cnt-1].w=edge[cnt-2].w=0;printf("%d\n",ans+solve(s,t));return 0; }?
總結(jié)
以上是生活随笔為你收集整理的LOJ - #116. 有源汇有上下界最大流(有源汇有上下界的最大流)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洛谷 - P4323 [JSOI2016
- 下一篇: LOJ - #117. 有源汇有上下界最