码迷,mamicode.com
首页 > 编程语言 > 详细

网络流——增广路算法(dinic)模板

时间:2016-06-18 14:10:02      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 #include<iostream>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<cstdio>
 6 #include<queue>
 7 using namespace std;
 8 struct data
 9 {
10     int from,to,next,cup,flow;
11     data(){from=-1,to=-1,next=-1,cup=-1,flow=-1;}
12 }e[200];
13 int cnt=0,head[200],head1[200];
14 int dis[200];
15 bool vis[200];
16 void add(int u,int v,int w){e[cnt].from=u,e[cnt].to=v,e[cnt].next=head[u],head[u]=cnt,e[cnt].cup=w,e[cnt].flow=0;cnt++;}
17 int s,t;
18 bool bfs()
19 {
20     memset(vis,0,sizeof(vis));
21     memset(dis,0,sizeof(dis));
22     int f=2147483647;
23     queue<int> q;
24     q.push(s);
25     vis[s]=1;
26     dis[s]=0;
27     while(!q.empty())
28     {
29         int n=q.front();
30         q.pop();
31         for(int i=head[n];i>=0;i=e[i].next)
32         {
33             if(!vis[e[i].to]&&e[i].cup>e[i].flow)
34             {
35                 vis[e[i].to]=1;
36                 dis[e[i].to]=dis[n]+1;
37                 q.push(e[i].to);
38             }
39         }
40     }
41     return vis[t];
42 }
43 int dfs(int n,int a)
44 {
45     if(n==t||a==0) return a;
46     int flow=0,f;
47     for(int i=head1[n];i>=0;i=e[i].next)
48     {
49         head1[n]=e[i].next;
50         if(dis[e[i].to]==dis[n]+1&&(f=dfs(e[i].to,min(a,e[i].cup-e[i].flow)))>0)
51         {
52             e[i].flow+=f;
53             e[i^1].flow-=f;
54             flow+=f;
55             a-=f;
56             if(a==0) break;
57         }
58     }
59     return flow;
60 }
61 int dinic()
62 {
63     int sum=0;
64     while(bfs())
65     {
66         for(int i=1;i<=t;i++)head1[i]=head[i];
67         sum+=dfs(s,2147483647);
68     }
69     return sum;
70 }
71 int main()
72 {
73     memset(head,-1,sizeof(head));
74     int n,m;
75     scanf("%d%d",&n,&m);
76     for(int i=1;i<=m;i++)
77     {
78         int s,t,w;
79         scanf("%d%d%d",&s,&t,&w);
80         add(s,t,w);
81         add(t,s,0);
82     }
83     s=1,t=n;
84     printf("%d",dinic());
85 }
View Code

 

网络流——增广路算法(dinic)模板

标签:

原文地址:http://www.cnblogs.com/wls001/p/5596042.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!