【题解】教辅的组成

题目戳我

\(\text{Solution:}\)

显然是一个类似于二分图,实际上却有三部分的图的“最大匹配”。

显然,我们可以想到书向练习册,练习册向答案的建图方式。但这样显然是错的。因为每册练习册被用到了多次。

鉴于题目中给出的是书向某物的关系,我们就让书当作图中最中间的一排点。即 练习册\(\to\)\(\to\)答案。

为了保证书只用一次,我们要对书进行拆点。即,将书分成两种点:入点和出点,练习册连入点,出点连答案,入点向出点连一条容量是\(1\)的有向边。

这样可以保证每一本书一定最多被用了一次。

剩下的考虑如何建立超级源点和超级汇点。显然,每一册练习册向源点连容量为\(1\)的边\((S\to practice),\)答案向汇点连容量为\(1\)的边\((answer\to T).\)

笔者第一次交的时候因为忽略的最后一步限制答案的边容量导致答案错误,值得反思。

#include<bits/stdc++.h>
using namespace std;
const int MAXN=2e5+10;
int head[MAXN],tot=1,N1,N2,S,T;
int N3,M1,M2,dep[MAXN],cur[MAXN];
const int inf=(1<<30);
struct edge{
	int nxt,to,flow;
}e[MAXN];
inline void add(int x,int y,int w){
	e[++tot].to=y;e[tot].nxt=head[x];e[tot].flow=w;head[x]=tot;
	e[++tot].to=x;e[tot].nxt=head[y];e[tot].flow=0;head[y]=tot;
}
bool bfs(int s,int t){
	memset(dep,0,sizeof(dep));
	queue<int>q;q.push(s);
	dep[s]=1;cur[s]=head[s];
	while(!q.empty()){
		s=q.front();q.pop();
		for(int i=head[s];i;i=e[i].nxt){
			int j=e[i].to;
			if(!dep[j]&&e[i].flow){
				dep[j]=dep[s]+1;
				cur[j]=head[j];
				if(j==t)return true;
				q.push(j);
			}
		}
	}
	return false;
}
int dfs(int s,int flow,int t){
	if(flow<=0||s==t)return flow;
	int rest=flow;
	for(int i=cur[s];i;i=e[i].nxt){
		int j=e[i].to;
		if(dep[j]==dep[s]+1&&e[i].flow){
			int tmp=dfs(j,min(rest,e[i].flow),t);
			if(tmp<=0)dep[j]=0;
			rest-=tmp;e[i].flow-=tmp;e[i^1].flow+=tmp;
			if(rest<=0)break;
		}
	}
	return flow-rest;
}
int dinic(int s,int t){
	int ans=0;
	for(;bfs(s,t);)ans+=dfs(s,inf,t);
	return ans;
}
int main(){
	scanf("%d%d%d",&N1,&N2,&N3);
	scanf("%d",&M1);
	//we are given the relation between the book and the (Answer&practice)
	//in:i out:i+N1+N2+N3(book)
	//practice:i+N1
	//answer:i+N1+N2
	//S->practice->bookin->bookout->answer->T
	//0->i+N1->i->i+N1+N2+N3->i+N1+N2->N1+N2+N3+N1+1 
	for(int i=1;i<=N1;++i)add(i,i+N1+N2+N3,1);
	for(int i=1;i<=M1;++i){
		//book -> practice
		int x,y;
		scanf("%d%d",&x,&y);
		add(y+N1,x,1);
	}
	scanf("%d",&M2);
	for(int i=1;i<=M2;++i){
		//book -> answer
		int x,y;
		scanf("%d%d",&x,&y);
		add(x+N1+N2+N3,y+N1+N2,1);
	}
	S=T+N1+N2+N3+N1+2,T=N1+N2+N3+N1+1;
	for(int i=1;i<=N2;++i)add(S,i+N1,1);
	for(int i=1;i<=N3;++i)add(i+N1+N2,T,1);//!
	printf("%d\n",dinic(S,T));
	return 0;
} 
posted @ 2020-08-19 23:31  Refined_heart  阅读(136)  评论(0编辑  收藏  举报