「Luogu1231」教辅的组成

传送门
Luogu

解题思路

看到种匹配问题,马上想到最大流所以这就是一道SB题。
但是有一个小问题,就是每一本书都只能匹配一次,那么我们对所有书进行拆点即可,这个操作类似于这题

细节注意事项

  • 细节有点多,尤其是输入时的细节

参考代码

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <ctime>
#include <queue>
#define rg register
using namespace std;
template < class T > inline void read(T& s) {
	s = 0; int f = 0; char c = getchar();
	while (!isdigit(c)) f |= c == '-', c = getchar();
	while (isdigit(c)) s = s * 10 + c - 48, c = getchar();
	s = f ? -s : s;
}

const int _ = 40002;
const int __ = 100002;
const int INF = 2147483647;

int tot = 1, head[_], nxt[__ << 1], ver[__ << 1], cap[__ << 1];
inline void Add_edge(int u, int v, int d)
{ nxt[++tot] = head[u], head[u] = tot, ver[tot] = v, cap[tot] = d; }
inline void link(int u, int v, int d) { Add_edge(u, v, d), Add_edge(v, u, 0); }

int n1, n2, n3, m, s, t, dep[_], cur[_];

inline int bfs() {
	static queue < int > Q;
	memset(dep, 0, sizeof dep);
	dep[s] = 1, Q.push(s);
	while (!Q.empty()) {
		int u = Q.front(); Q.pop();
		for (rg int i = head[u]; i; i = nxt[i]) {
			int v = ver[i];
			if (dep[v] == 0 && cap[i] > 0)
				dep[v] = dep[u] + 1, Q.push(v);
		}
	}
	return dep[t] > 0;
}

inline int dfs(int u, int flow) {
	if (u == t) return flow;
	for (rg int& i = cur[u]; i; i = nxt[i]) {
		int v = ver[i];
		if (dep[v] == dep[u] + 1 && cap[i] > 0) {
			int res = dfs(v, min(flow, cap[i]));
			if (res) { cap[i] -= res, cap[i ^ 1] += res; return res; }
		}
	}
	return 0;
}

inline int Dinic() {
	int res = 0;
	while (bfs()) {
		for (rg int i = s; i <= t; ++i) cur[i] = head[i];
		while (int d = dfs(s, INF)) res += d;
	}
	return res;
}

int main() {
#ifndef ONLINE_JUDGE
	freopen("in.in", "r", stdin);
	freopen("out.out", "w", stdout);
#endif
	read(n1), read(n2), read(n3);
	s = 0, t = n2 + 2 * n1 + n3 + 1;
	read(m);
	for (rg int u, v, i = 1; i <= m; ++i)
		read(u), read(v), link(v, u + n2, 1);
	read(m);
	for (rg int u, v, i = 1; i <= m; ++i)
		read(u), read(v), link(u + n1 + n2, v + 2 * n1 + n2, 1);
	for (rg int i = 1; i <= n2; ++i) link(s, i, 1);
	for (rg int i = 1; i <= n1; ++i) link(i + n2, i + n1 + n2, 1);
	for (rg int i = 1; i <= n3; ++i) link(i + 2 * n1 + n2, t, 1);
	printf("%d\n", Dinic());
	return 0;
}

完结撒花 \(qwq\)

posted @ 2019-11-06 15:26  Sangber  阅读(109)  评论(0编辑  收藏  举报