-
Notifications
You must be signed in to change notification settings - Fork 0
/
dinic.cpp
137 lines (109 loc) · 3.15 KB
/
dinic.cpp
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// BOJ 13161 분단의 슬픔
#include <bits/stdc++.h>
#define sz size()
#define bk back()
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
int dfs(int cur, int f, vector<vector<int>> &graph, vector<vector<int>> &capacity, vector<vector<int>> &flow, vector<int> &level, vector<int> &work, int sink) {
if (cur == sink)
return f;
for (int &i = work[cur]; i < graph[cur].sz; i++) {
int nxt = graph[cur][i];
if (capacity[cur][nxt] <= flow[cur][nxt] || level[nxt] != level[cur] + 1)
continue;
int k = dfs(nxt, min(capacity[cur][nxt] - flow[cur][nxt], f), graph, capacity, flow, level, work, sink);
if (k > 0) {
flow[cur][nxt] += k;
flow[nxt][cur] -= k;
return k;
}
}
return 0;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
int source = n + 1;
int sink = n + 2;
vector<int> v(n + 1);
for (int i = 1; i <= n; i++)
cin >> v[i];
vector<vector<int>> graph(n + 3);
vector<vector<int>> capacity(n + 3, vector<int>(n + 3));
vector<vector<int>> flow(n + 3, vector<int>(n + 3));
for (int i = 1; i <= n; i++) {
if (v[i] == 1) {
graph[source].push_back(i);
graph[i].push_back(source);
capacity[source][i] = INT_MAX;
} else if (v[i] == 2) {
graph[i].push_back(sink);
graph[sink].push_back(i);
capacity[i][sink] = INT_MAX;
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> capacity[i][j];
if (capacity[i][j])
graph[i].push_back(j);
}
}
int ans = 0;
vector<int> level(n + 3);
vector<int> work(n + 3);
deque<int> dq;
while (1) {
fill(level.begin(), level.end(), -1);
level[source] = 0;
dq.clear();
dq.push_back(source);
while (dq.sz) {
int cur = dq.front();
dq.pop_front();
for (int nxt : graph[cur]) {
if (capacity[cur][nxt] > flow[cur][nxt] && level[nxt] == -1) {
level[nxt] = level[cur] + 1;
dq.push_back(nxt);
}
}
}
if (level[sink] == -1)
break;
fill(work.begin(), work.end(), 0);
while (1) {
int k = dfs(source, INT_MAX, graph, capacity, flow, level, work, sink);
ans += k;
if (k == 0)
break;
}
}
dq.clear();
dq.push_back(source);
vector<bool> vst(n + 3);
while (dq.sz) {
int cur = dq.front();
dq.pop_front();
for (int nxt : graph[cur]) {
if (capacity[cur][nxt] > flow[cur][nxt] && !vst[nxt]) {
vst[nxt] = true;
dq.push_back(nxt);
}
}
}
cout << ans << '\n';
for (int i = 1; i <= n; i++)
if (vst[i])
cout << i << ' ';
cout << '\n';
for (int i = 1; i <= n; i++)
if (!vst[i])
cout << i << ' ';
cout << '\n';
}