「网络流24题」试题库问题-题解

题目传送门: 「Luogu P2763」试题库问题

题目大意

假设一个试题库中有$n$道试题,每道试题都标明了所属类别,同一道题可能有多个类别属性,现要从题库中抽取$m$道题组成试卷,并要求试卷包含指定类型的试题,输出出题方案

题解

建图: 类型与汇点连容量为题目数的边;题目与源点连容量为$1$的边;题目与所属类型连容量为$1$的边
结果: 如果满流则可以实现(沿满流输出即可),没有满流输出No Solution!

代码

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
#include <bits/stdc++.h>
using namespace std;

const int maxn = 2020;
const int inf = 0x3f3f3f3f;

bool vis[maxn];
int k, n, s, t, sum, d[maxn], cur[maxn];
int ans[maxn], ansi;
struct Edge {
int from, to, cap, flow;
Edge(int u, int v, int c, int f): from(u), to(v), cap(c), flow(f){}
};
vector<Edge> edges;
vector<int> G[maxn];
void add(int u, int v, int c) {
edges.push_back(Edge(u, v, c, 0));
edges.push_back(Edge(v, u, 0, 0));
int mm = edges.size();
G[u].push_back(mm - 2);
G[v].push_back(mm - 1);
}

bool bfs() {
memset(vis, 0, sizeof(vis));
queue<int> Q;
Q.push(s);
d[s] = 0; vis[s] = true;
while (!Q.empty()) {
int x = Q.front(); Q.pop();
for (int i = 0; i < G[x].size(); ++i) {
Edge& e = edges[G[x][i]];
if (!vis[e.to] && e.cap > e.flow) {
vis[e.to] = 1;
d[e.to] = d[x] + 1;
Q.push(e.to);
}
}
}
return vis[t];
}

int dfs(int x, int a) {
if (x == t || a == 0) return a;
int flow = 0, f;
for (int& i = cur[x]; i < G[x].size(); ++i) {
Edge& e = edges[G[x][i]];
if (d[x] + 1 == d[e.to] && (f = dfs(e.to, min(a, e.cap - e.flow))) > 0) {
e.flow += f;
edges[G[x][i] ^ 1].flow -= f;
flow += f;
a -= f;
if (a == 0) break;
}
}
return flow;
}

int MaxFlow(int s, int t) {
int flow = 0;
while (bfs()) {
memset(cur, 0, sizeof(cur));
flow += dfs(s, inf);
}
return flow;
}

int main() {
scanf("%d %d", &k, &n);
s = 0; t = n + k + 1;
for (int i = 1; i <= k; ++i) {
int type;
scanf("%d", &type);
sum += type; add(n + i, t, type);
}
for (int i = 1; i <= n; ++i) {
add(s, i, 1);
int p, type;
scanf("%d", &p);
for (int j = 1; j <= p; ++j) {
scanf("%d", &type);
add(i, type + n, 1);
}
}
int maxflow = MaxFlow(s, t);
if (maxflow == sum) {
for (int i = n + 1; i <= n + k; ++i) {
printf("%d: ", i - n);
for (int j = 0; j < G[i].size(); ++j) {
Edge& e = edges[G[i][j]];
if (e.cap == 0 && e.flow != 0) {
printf("%d ", e.to);
}
}
printf("\n");
}
} else {
printf("No Solution!\n");
}
return 0;
}

「网络流24题」试题库问题-题解

https://blog.tonycrane.cc/p/5a8ce31f.html

作者

TonyCrane

发布于

2019-05-02

更新于

2020-05-05

许可协议