经典的二分图最大匹配问题,因为匈牙利算法我还没有认真去看过,想先试试下网络流的做法,即对所有女生增加一个超级源,对所有男生增加一个超级汇,然后按照题意的匹配由女生向男生连一条边,跑一个最大流就是答案(以上所有边容量均为 1 ),我是直接上 Dinic 算法的模板的:
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define sd(x) scanf("%d",&(x))
const int inf = 0x3fffffff; struct Edge {
int from, to, cap, flow;
Edge() {}
Edge(int from, int to, int cap, int flow):
from(from), to(to), cap(cap), flow(flow) {}
}; const int N = ; struct Dinic {
int s,t;
vector<Edge> edges;
vector<int> G[N];
bool vis[N];
int d[N];
int cur[N]; void clear() {
edges.clear();
for(int i = ; i < N; ++i)
G[i].clear();
}
void addEdge(int from, int to, int cap) {
edges.push_back(Edge(from, to, cap, ));
edges.push_back(Edge(to, from, , ));
int m = edges.size();
G[from].push_back(m - );
G[to].push_back(m - );
}
bool bfs() {
memset(vis,,sizeof(vis));
queue<int> q;
q.push(s);
d[s] = ;
vis[s] = ;
while(!q.empty()) {
int x = q.front(); q.pop();
int len = G[x].size();
for(int i = ; i < len; ++i) {
Edge &e = edges[G[x][i]];
if(!vis[e.to] && e.cap > e.flow) {
d[e.to] = d[x] + ;
vis[e.to] = ;
q.push(e.to);
}
}
}
return vis[t];
}
int dfsAll(int x, int a) {
if(x == t || a == ) return a;
int flow = , f, len = G[x].size();
for(int &i = cur[x]; i < len; ++i) {
Edge &e = edges[G[x][i]];
if(d[e.to] == d[x] + && (f = dfsAll(e.to, min(a, e.cap - e.flow)) > )) {
e.flow += f;
edges[G[x][i]^ ].flow -= f;
flow += f;
a -= f;
if(a == ) break;
}
}
return flow;
}
int Maxflow(int s, int t) {
this->s = s;
this->t = t;
int flow = ;
while(bfs()) {
memset(cur, , sizeof(cur));
flow += dfsAll(s,inf);
}
return flow;
}
} dinic; int c[]; #define sd2(x,y) scanf("%d%d",&(x),&(y))
#define sd3(x,y,z) scanf("%d%d%d",&(x),&(y),&(z)) int main() {
int n,m,k,x,y;
while(~sd3(k, m, n), k) {
dinic.clear();
while(k--) {
sd2(x,y);
y += m;
dinic.addEdge(x, y, );
// dinic.addEdge(y, x, 1);
}
for(int i = ; i <= m; ++i)
dinic.addEdge(, i, );
for(int i = m + ; i <= m + n; ++i)
dinic.addEdge(i, m + n + , );
printf("%d\n",dinic.Maxflow(, m + n + ));
}
return ;
}
最大流实现最佳匹配
需要注意的是男女生的编号,还有女生指向男生的是有向边,不需要两次的 addEdge。wa 了两次才找出所有问题。。。