【网络流】教辅的组成

P1231
n1本书,n2本练习册,n3本答案,有对应关系,求最大匹配。

一开始的想法是直接n1,n2,n3三组节点间建图,n2连源点,n3连汇点,容量设为1,跑一遍最大流。
发现WA了,因为这样可能出现一本书重复使用,而这种情况是错误的。解决的方法是“拆点”,将n1本书拆成两个连一条边,就能保证书中流过的流量也是1了。
另外,不优化的Dinic只A了三个点,又进行了当前弧优化,就AC了。


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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<memory.h>
#include<algorithm>
#include<queue>
using namespace std;
const int MAXN=40005;
const int MAXM=400005;
const int inf=2147483647;
int n,m,n1,n2,n3,m1,m2,x,y,T,S,ans,dep[MAXN];
struct EDGE{
int next;
int to;
int w;
};
EDGE g[MAXM*2];
int head[MAXN]={0},cur[MAXN],nume=-1;

inline void adde(int f,int t,int w){
g[++nume].next=head[f];
g[nume].to=t;
g[nume].w=w;
head[f]=nume;
}

inline int bfs(){
memset(dep,0,sizeof(dep));
queue<int> q;
int now;
int i;
while(!q.empty())
q.pop();
q.push(S);
dep[S]=1;
do{
now=q.front();
q.pop();
for(i=head[now];i!=-1;i=g[i].next)
if(g[i].w!=0&&dep[g[i].to]==0){
dep[g[i].to]=dep[now]+1;
q.push(g[i].to);
}
}while(!q.empty());
if(dep[T]==0)return 0;
return 1;
}

int dfs(int i,int m){
int t;
if(i==T)
return m;
for(int& j=cur[i];j!=-1;j=g[j].next)
if((dep[g[j].to]==dep[i]+1)&&g[j].w!=0){

t=dfs(g[j].to,min(m,g[j].w));
if(t>0){
g[j].w-=t;
g[j^1].w+=t;
return t;
}
}

return 0;
}

inline void dinic(){
int t,i;
while(bfs()){
for (i=1;i<=n;i++)
cur[i]=head[i];
while(t=dfs(S,inf))
ans+=t;

}
}

inline int bo1(int x){
return x*4;
}

inline int bo2(int x){
return x*4+1;
}

inline int ex(int x){
return x*4+2;
}

inline int an(int x){
return x*4+3;
}


int main(){
int i;
memset(head,-1,sizeof(head));
nume=-1;

scanf("%d%d%d",&n1,&n2,&n3);

S=1;
n=(max(max(n1,n2),n3)+1)*4;

T=n;
//printf("%d\n",T);
ans=0;

for(i=1;i<=n2;i++){
adde(S,ex(i),1);
adde(ex(i),S,0);
}
//source to exercise
scanf("%d",&m1);

for(i=1;i<=m1;i++){
scanf("%d%d",&x,&y);
adde(ex(y),bo1(x),1);
adde(bo1(x),ex(y),0);
}
//exercise to book1

for(i=1;i<=n1;i++){
adde(bo1(i),bo2(i),1);
adde(bo2(i),bo1(i),0);
}
//book1 to book2
scanf("%d",&m2);

for(i=1;i<=m2;i++){
scanf("%d%d",&x,&y);
adde(bo2(x),an(y),1);
adde(an(y),bo2(x),0);
}

//book2 to answer

for(i=1;i<=n3;i++){
adde(an(i),T,1);
adde(T,an(i),0);
}
//answer to sink
dinic();
printf("%d\n",ans);


return 0;
}