[codevs1227]草地排水<Dinic网络流最大流>

题目链接:http://codevs.cn/problem/1993/

    https://www.luogu.org/problemnew/show/P2740

 

之前一直都没去管网络流这算法,但是老师最近的noip考的范围越来越广,越来越说不清楚,所以我还是选择来看看网络流算法

这道题是个最大流的裸题,最大流的算法比较多,EK ,Dinic,SAP算法等,当然貌似是dinic算法在一般情况下比较优

我这道题就是用dinic做的

这道题是个裸题没啥好讲的,我在这憋了半天都不知道打啥,我还是后续补一个dinic算法 的介绍算了

然后这道题的bfs函数就是找增广路的,意思就是还有其他可以执行路径可以从1到n,然后dfs就是对这条路径进行处理,dfs里面有个f数组的处理那个位置的^运算是处理当前路径和与之对应的路径(反向弧或者正向弧)

然后其他就没有啥难理解的地方了

所以还是直接上代码吧

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<iostream>
 5 #include<queue>
 6 #include<cmath>
 7 #include<cstdlib>
 8 #include<stack>
 9 #define maxn 505
10 using namespace std;
11 
12 queue<int>q;
13 int c[maxn],head[maxn],f[maxn],n,m,dep[maxn],ans;
14 struct edge{
15     int u,v,w,nxt,flow;
16 }e[maxn];
17 
18 int read(){
19     int xx=0,ff=1;char ch=getchar();
20     while(ch<'0'||ch>'9'){if(ch=='-')ff=-1;ch=getchar();}
21     while(ch>='0'&&ch<='9'){xx=xx*10+ch-'0';ch=getchar();}
22     return xx*ff;
23 }
24 
25 int tot=1;
26 void adde(int u,int v,int w){
27     e[++tot].u=u;
28     c[tot]=w;
29     e[tot].v=v;e[tot].w=w;
30     e[tot].nxt=head[u];
31     head[u]=tot;
32 }
33 
34 int bfs(){
35     q.push(1);
36     memset(dep,-1,sizeof(dep));
37     dep[1]=0;
38     while(!q.empty()){
39         int u=q.front();q.pop();
40         for(int i=head[u];i!=-1;i=e[i].nxt){
41             int v=e[i].v;
42             if(dep[v]==-1&&c[i]-f[i]){
43                 dep[v]=dep[u]+1;
44                 q.push(v);
45             }
46         }    
47     }
48     if(dep[n]==-1)return 0;
49     else return 1;
50 }
51 
52 int dfs(int u,int lim){
53     if(u==n){ans+=lim;return lim;}
54     int t;
55     for(int i=head[u];i!=-1;i=e[i].nxt ){
56         int v=e[i].v;
57         if(c[i]-f[i]&&dep[u]+1==dep[v]&&(t=dfs(v,min(lim,c[i]-f[i])))){
58             f[i]+=t;f[i^1]-=t;return t;
59         }
60     }
61     return 0;
62 }
63 
64 int main(){
65     memset(head,-1,sizeof(head));
66     m=read();n=read();    
67     for(int i=1;i<=m;i++){
68         int u,v,w;
69         u=read();v=read();w=read();
70         adde(u,v,w);adde(v,u,0);
71     }
72     while(bfs()){
73         dfs(1,0x3f3f3f);
74     }
75     printf("%d",ans);
76 }
dinic

 

原文地址:https://www.cnblogs.com/Danzel-Aria233/p/7760444.html