洛谷P2740 草地排水Drainage Ditches 题解

题目大意

最大流板子题。

解题思路

板子题。

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <queue>
#include <deque>
#include <cstring>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#include <list>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <unordered_map>
using namespace std;
#pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#define rep(i,a,n) for (int i=a;i<=n;i++)
#define per(i,a,n) for (int i=a;i>=n;i--)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define pll pair<ll,ll>
#define pii pair<int,int>
#define bg begin
#define rbg rbegin
#define ed end
#define endl '\n'
#define dbg(x) cout << #x << "===" << x << endl
typedef double db;
typedef long long ll;
typedef unsigned long long ull;

const int INF = 1e9;
struct {
int to, next, val;
}edge[1010];
int n, m, s, t;
int cnt, head[1010];
int dep[1010];
int cur[1010];

void build(int u, int v, int val) {
edge[cnt].to = v, edge[cnt].val = val;
edge[cnt].next = head[u], head[u] = cnt++;
}

int bfs() {
queue<int> q;
q.push(s);
memset(dep, -1, sizeof(dep));
dep[s] = 0;
while (!q.empty()) {
int node = q.front(); q.pop();
for (int i = head[node]; ~i; i = edge[i].next) {
int v = edge[i].to;
if (dep[v] == -1 && edge[i].val > 0)
dep[v] = dep[node] + 1, q.push(v);
}
}
return ~dep[t];
}

int dfs(int pos, int flow) {
if (pos == t) return flow;
int tmp = 0, res = 0;
for (int& i = cur[pos]; ~i; i = edge[i].next) {
int v = edge[i].to;
if (dep[v] == (dep[pos] + 1) && edge[i].val > 0) {
tmp = dfs(v, min(flow, edge[i].val));
if (!tmp) continue;
flow -= tmp;
res += tmp;
edge[i].val -= tmp;
edge[i ^ 1].val += tmp;
if (!flow) break;
}
}
return res;
}

int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> m >> n;
s = 1, t = n;
cnt = 0;
memset(head, -1, sizeof(head));
rep(i, 1, m) {
int u, v, w;
cin >> u >> v >> w;
build(u, v, w);
build(v, u, 0);
}
int ans = 0;
while (bfs()) {
rep(i, 1, n) cur[i] = head[i];
ans += dfs(s, INF);
}
cout << ans << endl;
return 0;
}
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • © 2015-2021 sakurakarma
  • Powered by Hexo Theme Ayer
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信