# hdu1083 Courses--最大匹配 & HK算法

323人阅读 评论(0)

#define _CRT_SECURE_NO_DEPRECATE

#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#define INF 99999999;
using namespace std;

int t;
int dis;
int p, n;
int a[105][305];
int cx[305];
int cy[305];
int dx[305];
int dy[305];
bool vis[305];

bool searchPath()
{
queue<int> Q;
memset(dx, -1, sizeof(dx));
memset(dy, -1, sizeof(dy));
dis = INF;
for (int i = 1; i <= p; i++)
{
if (cx[i] == -1)
{
Q.push(i);
dx[i] = 0;
}
}

while (!Q.empty())
{
int u = Q.front();
Q.pop();
if (dx[u] > dis)
break;
for (int v = 1; v <= n; v++)
{
if (a[u][v] && dy[v] == -1)
{
dy[v] = dx[u] + 1;
if (cy[v] == -1)
dis = dy[v];
else
{
dx[cy[v]] = dy[v] + 1;
Q.push(cy[v]);
}
}
}
}
return dis != INF;
}

int findPath(int u)
{
for (int v = 1; v <= n; v++)
{
if (!vis[v] && a[u][v] && dy[v] == dx[u] + 1)
{
vis[v] = 1;
if (cy[v] != -1 && dy[v] == dis)
continue;
if (cy[v] == -1 || findPath(cy[v]))
{
cy[v] = u;
cx[u] = v;
return 1;
}
}
}
return 0;
}

int maxMatch()
{
int ans = 0;
memset(cx, -1, sizeof(cx));
memset(cy, -1, sizeof(cy));
while (searchPath())
{
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= p; i++)
{
if (cx[i] == -1)
ans += findPath(i);
}
}
return ans;
}

int main()
{
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &p, &n);
memset(a, 0, sizeof(a));

for (int i = 1; i <= p; i++)
{
int num, x;
scanf("%d", &num);
for (int j = 1; j <= num; j++)
{
scanf("%d", &x);
a[i][x] = 1;
}
}
printf("%s\n", maxMatch() == p ? "YES" : "NO");
}

return 0;
}

2
0

个人资料
• 访问：444086次
• 积分：7713
• 等级：
• 排名：第3285名
• 原创：395篇
• 转载：52篇
• 译文：0篇
• 评论：45条
最新评论