https://vjudge.net/problem/HDU-2444
开启kuangbin连通图专题刷题~
能用HK绝不用匈牙利,最后的倔强
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 205;
int n, m;
int cnth, cntl;
int mx[maxn], my[maxn];
int dx[maxn], dy[maxn];
int link[maxn];
bool vis[maxn];
int head[maxn];
int x[maxn], y[maxn];
int cnt;
int dis;
//vector<int> G[maxn];
struct node
{
int to, next;
}e[maxn*maxn];
void init()
{
// for(int i = 1; i <= n; i ++)
// G[i].clear();
cnt = 0;
memset(head, -1, sizeof(head));
memset(link, -1, sizeof(link));
memset(mx, -1, sizeof(mx));
memset(my, -1, sizeof(my));
}
void addedge(int u, int v)
{
e[cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt ++;
}
bool searchP()
{
queue<int> q;
dis = inf;
memset(dx, -1, sizeof(dx));
memset(dy, -1, sizeof(dy));
for(int i = 1; i <= n; i ++)
{
if(mx[i] == -1)
{
q.push(i);
dx[i] = 0;
}
}
while(! q.empty())
{
int u = q.front();
q.pop();
if(dx[u] > dis) break;
//int sz = G[u].size();
for(int i = head[u]; ~i; i = e[i].next)
{
//int v = G[u][i];
int v = e[i].to;
if(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 sz = G[u].size();
for(int i = head[u]; ~i; i = e[i].next)
{
//int v = G[u][i];
int v = e[i].to;
if(! vis[v] && dy[v] == dx[u] + 1)
{
vis[v] = 1;
if(my[v] != -1 && dy[v] == dis) continue;
if(my[v] == -1 || dfs(my[v]))
{
my[v] = u;
mx[u] = v;
return 1;
}
}
}
return 0;
}
struct node1
{
int l, r, now;
}h[7], l[7];
int vs[maxn];
bool flag1;
void color(int u, int col)
{
int tmp = vs[u];
vs[u] = 1 - col;
if(tmp + vs[u] == 1)
{
flag1 = 0;
return ;
}
for(int i = head[u]; ~i; i = e[i].next)
{
int v = e[i].to;
color(v, vs[u]);
}
}
int main()
{
while(scanf("%d%d", &n, &m) != EOF)
{
init();
int u, v;
for(int i = 1; i <= m; i ++)
{
scanf("%d%d", &u, &v);
addedge(u, v);
}
bool flag = 1;
memset(vs, -1, sizeof(vs));
for(int i = 1; i <= n; i ++)
{
flag1 = 1;
if(vs[i] == -1)
{
color(i, 1);
if(! flag1)
{
flag = 0;
break;
}
}
}
if(! flag)
{
printf("No\n");
continue;
}
// cnt = 0;
// memset(head, -1, sizeof(head));
int cnt1 = 0, cnt2 = 0;
for(int i = 1; i <= n; i ++)
{
if(vs[i] == 0)
x[++ cnt1] = i;
else y[++ cnt2] = i;
}
n = cnt1, m = cnt2;
// for(int i = 1; i <= cnt1; i ++)
// cout<<x[i]<<endl;
// cout<<endl;
// for(int i = 1; i <= cnt2; i ++)
// cout<<y[i]<<endl;
int ans = 0;
while(searchP())
{
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= n; i ++)
if(mx[i] == -1 && dfs(i))
ans ++;
}
printf("%d\n", ans);
}
return 0;
}