模板://hdu 2063
Hopcroft-Carp 时间复杂度为 O(sqrt(V)*E);
而匈牙利算法为 O(V*E);
#include <stdio.h>
#include <ctime>
#include <math.h>
#include <limits.h>
#include <complex>
#include <string>
#include <functional>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <list>
#include <bitset>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <time.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
using namespace std;
const int N = 1005;
const int INF = 1 << 28;
int g[N][N];
int Mx[N];
int My[N];
int dx[N];
int dy[N];
bool used[N];
int Nx, Ny, dis;
bool searchP()
{
dis = INF;
int i, v, u;
std::queue<int> Q;
memset(dx, -1, sizeof(dx));
memset(dy, -1, sizeof(dy));
for (i = 0; i<Nx; i++)
{
if (Mx[i] == -1)
{
Q.push(i);
dx[i] = 0;
}
}
while (!Q.empty())
{
u = Q.front();
Q.pop();
if (dx[u]>dis) break;
for (v = 0; v<Ny; v++)
{
if (g[u][v] && dy[v] == -1)
{
dy[v] = dx[u] + 1;
if (My[v] == -1) dis = dy[v];
else
{
dx[My[v]] = dy[v] + 1;
Q.push(My[v]);
}
}
}
}
return dis != INF;
}
bool DFS(int u)
{
int v;
for (v = 0; v<Ny; v++)
{
if (g[u][v] && !used[v] && dy[v] == dx[u] + 1)
{
used[v] = true;
if (My[v] != -1 && dy[v] == dis) continue;
if (My[v] == -1 || DFS(My[v]))
{
My[v] = u;
Mx[u] = v;
return true;
}
}
}
return false;
}
int Hungary()
{
int u;
int ret = 0;
memset(Mx, -1, sizeof(Mx));
memset(My, -1, sizeof(My));
while (searchP())
{
memset(used, false, sizeof(used));
for (u = 0; u<Nx; u++)
if (Mx[u] == -1 && DFS(u)) ret++;
}
return ret;
}
int main()
{
int k, u, v;
while (~scanf("%d", &k) ,k)
{
scanf("%d%d", &Nx, &Ny);
memset(g, 0, sizeof(g));
Ny = Nx>Ny ? Nx : Ny;
while (k--)
{
scanf("%d%d", &u, &v);
u--; v--;
g[u][v] = 1;
}
int ans = Hungary();
printf("%d\n", ans);
}
return 0;
}
时间: 2024-10-24 01:26:09