poj-1469-COURSES-二分图匹配-匈牙利算法(模板)

时间:2023-01-22 12:06:52

题意:N个学生,P个课程,问能不能找到课程的P个匹配。

思路:【早上睡醒了再写】

代码:

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = ;
int n, p;
vector<int> g[maxn];
int from[maxn], tot;
bool use[maxn]; bool match(int x)
{
for (int i = ; i < g[x].size(); i ++) {
if(!use[g[x][i]]) {
use[g[x][i]] = true;
if(from[g[x][i]] == - || match(from[g[x][i]])) {
from[g[x][i]] = x;
return true;
}
}
}
return false;
} int hungary()
{
tot = ;
memset(from, -, sizeof(from));
for(int i = ; i <= n; i ++) {
memset(use, , sizeof(use));
if(match(i)) tot ++;
}
return tot;
} int main()
{
int t; cin>>t;
while(t--) {
for(int i = ; i < maxn; i++) g[i].clear();
scanf("%d%d", &p, &n);
for(int i = ; i <= p; i++) {
int k; scanf("%d", &k);
for(int j = ; j < k; j++) {
int a; scanf("%d", &a);
g[i].push_back(a);
}
}
int res = hungary();
//cout<<res<<endl;
if(res == p) printf("YES\n");
else printf("NO\n");
}
}