【luogu P1231 教辅的组成】 题解
题目链接:https://www.luogu.org/problemnew/show/P1231
对于每本书只能用一次,所以拆点再建边
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 50000 + 10;
const int inf = 1e9;
int n1, n2, n3, m1, m2, s, t, maxflow, deep[maxn];
struct edge{
int flow, next, to;
}e[maxn<<3];
int head[maxn], cnt = -1;
queue<int> q;
void add(int u, int v, int w)
{
e[++cnt].flow = w; e[cnt].next = head[u]; e[cnt].to = v; head[u] = cnt;
e[++cnt].flow = 0; e[cnt].next = head[v]; e[cnt].to = u; head[v] = cnt;
}
bool bfs(int s, int t)
{
memset(deep, 0x7f, sizeof(deep));
while(!q.empty()) q.pop();
q.push(s); deep[s] = 0;
while(!q.empty())
{
int now = q.front(); q.pop();
for(int i = head[now]; i != -1; i = e[i].next)
{
if(deep[e[i].to] > inf && e[i].flow)
{
deep[e[i].to] = deep[now] + 1;
q.push(e[i].to);
}
}
}
if(deep[t] < inf) return true;
else return false;
}
int dfs(int now, int t, int limit)
{
if(!limit || now == t) return limit;
int flow = 0, f;
for(int i = head[now]; i != -1; i = e[i].next)
{
if(deep[e[i].to] == deep[now] + 1 && (f = dfs(e[i].to, t, min(e[i].flow, limit))))
{
flow += f;
limit -= f;
e[i].flow -= f;
e[i^1].flow += f;
if(!limit) break;
}
}
return flow;
}
void Dinic(int s, int t)
{
while(bfs(s, t))
maxflow += dfs(s, t, inf);
}
int main()
{
memset(head, -1, sizeof(head));
scanf("%d%d%d", &n1, &n2, &n3);
s = 1, t = n1*2 + n2 + n3 + 2;
for(int i = 1; i <= n1; i++)
{
add(i + 1, i + n1 + n2 + n3 + 1, 1);
}
scanf("%d",&m1);
for(int i = 1; i <= m1; i++)
{
int u, v;
scanf("%d%d",&u,&v);
add(v + 1 + n1, u + 1, 1);
}
scanf("%d",&m2);
for(int i = 1; i <= m2; i++)
{
int u, v;
scanf("%d%d",&u,&v);
add(u + n1 + n2 + n3 + 1, v + n1 + n2 + 1, 1);
}
for(int i = 1; i <= n2; i++)
add(s, i + n1 + 1, 1);
for(int i = 1; i <= n3; i++)
add(i + n1 + n2 + 1, t, 1);
Dinic(s, t);
printf("%d",maxflow);
return 0;
}
隐约雷鸣,阴霾天空,但盼风雨来,能留你在此。
隐约雷鸣,阴霾天空,即使天无雨,我亦留此地。
![](https://images.cnblogs.com/cnblogs_com/MisakaAzusa/1169114/o_a0c3752e09f79052b15f108c0cf3d7ca7acbd5b0.gif)