2013
11-11

# Arrange the Bulls

Farmer Johnson’s Bulls love playing basketball very much. But none of them would like to play basketball with the other bulls because they believe that the others are all very weak. Farmer Johnson has N cows (we number the cows from 1 to N) and M barns (we number the barns from 1 to M), which is his bulls’ basketball fields. However, his bulls are all very captious, they only like to play in some specific barns, and don’t want to share a barn with the others.

So it is difficult for Farmer Johnson to arrange his bulls, he wants you to help him. Of course, find one solution is easy, but your task is to find how many solutions there are.

You should know that a solution is a situation that every bull can play basketball in a barn he likes and no two bulls share a barn.

To make the problem a little easy, it is assumed that the number of solutions will not exceed 10000000.

In the first line of input contains two integers N and M (1 <= N <= 20, 1 <= M <= 20). Then come N lines. The i-th line first contains an integer P (1 <= P <= M) referring to the number of barns cow i likes to play in. Then follow P integers, which give the number of there P barns.

Print a single integer in a line, which is the number of solutions.

3 4
2 1 4
2 1 3
2 2 4


4

//* @author:
/*
题意:
N个牛，M个牲口棚(barn)，每个牛都有几个自己喜欢的barn，要求为每个牛分配一个barn，
使得每个牛所分到的barn都是自己喜欢的，且每个barn至多只能容纳一个牛。求合法的分配方案的种数。（N,M<=20）

第一行是N和M(1<=N<=20, 1<=M<=20);
接下来的N行:
第i行的第一个数字是第i个牛喜欢的barn数,其它数字是第i个牛喜欢的barn序号(1<=i<=N)

分配方案的种数
*/
import java.util.*;
public class Main
{
static final int N=20+2;
static final int M=1<< 20+1;

public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n, m, p;
int mat[][]=new int[N][N];
int dp[][]=new int[2][M];
int i, k, j, next;
n=sc.nextInt();
m=sc.nextInt();
for (i = 1; i <= n; i++)
{
p=sc.nextInt();
while ((p--)!=0)
{
k=sc.nextInt();
mat[i][k] = 1;
}
}

int s = 0;
dp[s][0] = 1;
for (i = 1; i <= n; i++)
{
for (j = 0; j < (1 << m); j++)
{
if (dp[s][j]!=0)
{
for (k = 1; k <= m; k++)
{
if (mat[i][k] == 1)
{
next = j | (1 << (k - 1));
if (next != j)      // 第k个barn没被占用
dp[(s + 1) % 2][next] += dp[s][j];
}

}
dp[s][j] = 0;
}
}

s = (s + 1) % 2;
}
int sum = 0;
for (i = 0; i < (1 << m); i++) sum += dp[s][i];
System.out.printf("%d\n", sum);
}
}