算法思路:二分图。
匈牙利算法,简单的模板题。最大匹配数 = p(课程数),打印“YES”。输入要用scanf,cin会超时。
//模板开始
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
#include <set>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <string.h>
#include <queue>
#define SZ(x) (int(x.size()))
using namespace std;
int toInt(string s){
istringstream sin(s);
int t;
sin>>t;
return t;
}
template<class T> string toString(T x){
ostringstream sout;
sout<<x;
return sout.str();
}
typedef long long int64;
int64 toInt64(string s){
istringstream sin(s);
int64 t;
sin>>t;
return t;
}
template<class T> T gcd(T a, T b){
if(a<0)
return gcd(-a, b);
if(b<0)
return gcd(a, -b);
return (b == 0)? a : gcd(b, a % b);
}
//模板结束(通用部分)
#define ifs cin
#define MAX 405
int juzhen[MAX][MAX];
int used[MAX];
int mat[MAX];
void init()
{
memset(juzhen, 0, sizeof(juzhen));
}
int Augment(int s, int n, int x)
{
int i;
for(i = s; i <= n; i++)
{
if(!used[i] && juzhen[x][i])
{
used[i] = 1;
if(mat[i] == -1 || Augment(s, n, mat[i]))
{
mat[i] = x;
return 1;
}
}
}
return 0;
}
int Hungary(int s, int n)
{
int i, sum = 0;
memset(mat, -1, sizeof(mat));
for(i = s; i <= n; i++)
{
memset(used, 0, sizeof(used));
if(Augment(s, n, i))
{
sum++;
}
}
return sum;
}
//【图论02】二分图 1003 Courses
int main()
{
//ifstream ifs("shuju.txt", ios::in);
int cases, p, n;
int a, b;
ifs>>cases;
while(cases--)
{
//ifs>>p>>n;
scanf("%d%d", &p, &n);
memset(juzhen, 0, sizeof(juzhen));
for(int i = 1; i <= p; i++)
{
//ifs>>a;
scanf("%d", &a);
for(int j = 0; j < a; j++)
{
//ifs>>b;
scanf("%d", &b);
juzhen[i][p + b] = 1;
//juzhen[m + b][a] = 1;
}
}
int max_match = Hungary(1, p + n);
if(max_match == p)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
return 0;
}