生活随笔
收集整理的這篇文章主要介紹了
【模板】网络最大流
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目描述
如題,給出一個(gè)網(wǎng)絡(luò)圖,以及其源點(diǎn)和匯點(diǎn),求出其網(wǎng)絡(luò)最大流。
輸入輸出格式
輸入格式:
第一行包含四個(gè)正整數(shù)N、M、S、T,分別表示點(diǎn)的個(gè)數(shù)、有向邊的個(gè)數(shù)、源點(diǎn)序號(hào)、匯點(diǎn)序號(hào)。
接下來M行每行包含三個(gè)正整數(shù)ui、vi、wi,表示第i條有向邊從ui出發(fā),到達(dá)vi,邊權(quán)為wi(即該邊最大流量為wi)
輸出格式:
一行,包含一個(gè)正整數(shù),即為該網(wǎng)絡(luò)的最大流。
輸入輸出樣例
輸入樣例#1:
4 5 4 3
4 2 30
4 3 20
2 3 20
2 1 30
1 3 40
輸出樣例#1:
50
說明
時(shí)空限制:1000ms,128M
數(shù)據(jù)規(guī)模:
對(duì)于30%的數(shù)據(jù):N<=10,M<=25
對(duì)于70%的數(shù)據(jù):N<=200,M<=1000
對(duì)于100%的數(shù)據(jù):N<=10000,M<=100000
樣例說明:
題目中存在3條路徑:
4–>2–>3,該路線可通過20的流量
4–>3,可通過20的流量
4–>2–>1–>3,可通過10的流量(邊4–>2之前已經(jīng)耗費(fèi)了20的流量)
故流量總計(jì)20+20+10=50。輸出50。
.
.
.
.
.
程序:
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;int ls[100001],dis[100001];
int n,m,s,t,cnt,ans,x,y,w;queue<int> q;
struct edge
{int y,w,op,next;
}a[500000];void add(int x,int y,int w)
{a[++cnt]=(edge){y,w,cnt+1,ls[x]}; ls[x]=cnt;a[++cnt]=(edge){x,0,cnt-1,ls[y]};ls[y]=cnt;
}bool bfs()
{while (!q.empty()) q.pop();for (int i=1;i<=n;i++) dis[i]=2147483647; dis[s]=0; q.push(s);while (!q.empty()) {int x=q.front();q.pop();for (int i=ls[x];i>0;i=a[i].next){int y=a[i].y;if ((a[i].w)&&(dis[y]>dis[x]+1)){dis[y]=dis[x]+1;if (y==t) return 1;q.push(y);}}}return 0;
}int dfs(int x,int q)
{if (x==t) return q;int sum=0;for (int i=ls[x];i>0;i=a[i].next){int y=a[i].y;if ((a[i].w)&&(dis[y]==dis[x]+1)) {int f=dfs(y,min(a[i].w,q-sum)); if (!f) dis[y]=-1;a[i].w-=f; a[a[i].op].w+=f;sum+=f;if (sum==q) break;}}return sum;
}int dinic()
{int ans=0;while (bfs()) ans+=dfs(s,2147483647); return ans;
}int main()
{scanf("%d%d%d%d",&n,&m,&s,&t);for (int i=1;i<=m;i++){scanf("%d%d%d",&x,&y,&w);add(x,y,w);}ans=dinic();printf("%d",ans);
}
轉(zhuǎn)載于:https://www.cnblogs.com/YYC-0304/p/11094944.html
總結(jié)
以上是生活随笔為你收集整理的【模板】网络最大流的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。