P1231 教辅的组成

Sol

注意到书被用了两次,所以让它夹在中间,然后注意要拆点,因为这个点不能被用多次。

Code

#include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define pf push_front
#define desktop "C:\\Users\\incra\\Desktop\\"
#define IOS ios :: sync_with_stdio (false),cin.tie (0),cout.tie (0)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair <int,int> PII;
const int dx[] = {1,0,-1,0},dy[] = {0,-1,0,1};
template <typename T1,typename T2> bool tomax (T1 &x,T2 y) {
	if (y > x) return x = y,true;
	return false;
}
template <typename T1,typename T2> bool tomin (T1 &x,T2 y) {
	if (y < x) return x = y,true;
	return false;
}
LL power (LL a,LL b,LL p) {
	LL ans = 1;
	while (b) {
		if (b & 1) ans = ans * a % p;
		a = a * a % p;
		b >>= 1;
	}
	return ans;
}
int fastio = (IOS,0);
#define endl '\n'
#define puts(s) cout << (s) << endl
const int N = 40010,M = 1000010,INF = 1e8;
int n1,n2,n3,m1,m2,n,s,t;
int h[N],e[M],ne[M],w[M],idx;
int d[N],q[N],cur[N];
void add_edge_ (int a,int b,int c) {
	e[idx] = b;
	w[idx] = c;
	ne[idx] = h[a];
	h[a] = idx++;
}
void add_edge (int a,int b,int c) {
	add_edge_ (a,b,c),add_edge_ (b,a,0);
}
bool BFS () {
	memset (d,-1,sizeof (d));
	int hh = 0,tt = -1;
	q[++tt] = s;
	d[s] = 0;
    cur[s] = h[s];
	while (hh <= tt) {
		int u = q[hh++];
		for (int i = h[u];~i;i = ne[i]) {
			int v = e[i];
			if (d[v] == -1 && w[i]) {
				d[v] = d[u] + 1;
				q[++tt] = v;
                cur[v] = h[v];
				if (v == t) return 1;
			}
		}
	}
	return 0;
}
int maxflow (int u,int lim) {
	if (u == t) return lim;
	int ans = 0;
	for (int i = cur[u];~i && ans < lim;i = ne[i]) {
		cur[u] = i;
		int v = e[i];
		if (d[v] == d[u] + 1 && w[i]) {
			int tmp = maxflow (v,min (lim - ans,w[i]));
			if (!tmp) d[v] = -1;
			ans += tmp,w[i] -= tmp,w[i ^ 1] += tmp;
		}
	}
	return ans;
}
LL dinic () {
	LL ans = 0,flow;
	while (BFS ()) {
		while (flow = maxflow (s,INF)) ans += flow;
	}
	return ans;
}
void mian () {
	memset (h,-1,sizeof (h));
    cin >> n2 >> n1 >> n3;
    s = n1 + 2 * n2 + n3 + 1,t = s + 1;
    // [1,n1] 练习册
    // [n1 + 1,n1 + 2 * n2] 书
    // [n1 + n2 + 1,n1 + n2 + n3] 答案
    cin >> m1;
    while (m1--) {
        int a,b;
        cin >> b >> a;
        add_edge (a,n1 + b,1);
    }
    for (int i = 1;i <= n2;i++) add_edge (n1 + i,n1 + n2 + i,1);
    cin >> m2;
    while (m2--) {
        int a,b;
        cin >> a >> b;
        add_edge (n1 + n2 + a,n1 + 2 * n2 + b,1);
    }
    for (int i = 1;i <= n1;i++) add_edge (s,i,1);
    for (int i = 1;i <= n3;i++) add_edge (n1 + 2 * n2 + i,t,1);
    cout << dinic () << endl;
}
int main () {
	int T = 1;
	// cin >> T;
	while (T--) mian ();
	return 0;
}
posted @ 2025-04-17 17:49  incra  阅读(4)  评论(0)    收藏  举报