码迷,mamicode.com
首页 > 其他好文 > 详细

【luogu P3376 网络最大流】 模板

时间:2018-05-19 13:11:07      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:color   ini   main   col   +=   const   tps   push   class   

题目链接:https://www.luogu.org/problemnew/show/P3376

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

 

【luogu P3376 网络最大流】 模板

标签:color   ini   main   col   +=   const   tps   push   class   

原文地址:https://www.cnblogs.com/MisakaAzusa/p/9059811.html

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