[题目链接]
https://www.luogu.org/problemnew/show/P1640
[算法]
二分图匹配
实现时需要常数优化和特判
[代码]
//code by byf and lmj
#include <bits/stdc++.h> #define MAXN 2000005 using namespace std; int n,tot=0,match[MAXN],head[MAXN]; bool visited[MAXN]; struct edge { int to,nxt; } e[MAXN << 1]; template <typename T> inline void read(T &x) { int f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } inline void addedge(int u,int v) { tot++; e[tot] = (edge){v,head[u]}; head[u] = tot; } inline bool hungary(int u) { int v; visited[u] = true; for (register int i = head[u]; i; i = e[i].nxt) { v = e[i].to; if (!visited[v]) { visited[v] = true; if (!match[v] || hungary(match[v])) { match[v] = u; return true; } } } return false; } int main() { read(n); for (register int i = 1; i <= n; ++i) { int a,b; read(a); read(b); addedge(a,i+n); addedge(b,i+n); } if (n <= 5E4) { for (register int i = 1; i <= n; ++i) { memset(visited,false,sizeof(visited)); if (!hungary(i)) { cout << i - 1 << endl; return 0; } } cout << n << endl; return 0; } for (register int i = 1; i <= 10005; ++i) { for (register int j = 1; j <= 20005; ++j) visited[j] = false; if (!hungary(i)) { cout << i - 1 << endl; return 0; } } cout << n << endl; return 0; }