Arrange the Bulls

Time Limit: 4000MS Memory Limit: 65536K

Description

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.

Input

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.
Output

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

Sample Input

3 4
2 1 4
2 1 3
2 2 4

Sample Output

4

思路:

状态压缩dp,题目要有多少种方案,如果用二维数组的话超内存,所以我用了一维数组,dp的话,难点从来都是状态方程的那个循环,首先第一层循环是遍历奶牛的头数,第二个循环是将谷仓的能给奶牛选择的排列都列在一个集合里面,第三个循环就是第j个谷仓里面是否有奶牛,没有的话,且第i头奶牛喜欢这个仓的时候,就将集合加入这个仓,最后因为之前添加了元素了所以,之前的集合就要变成0。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 20;
int dp[1 << maxn + 5] = {0};
int book[maxn + 10][maxn + 10] = {0};
int main() {
	int n, m, k;
	scanf("%d %d", &n, &m);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &k);
		while (k--) {
			int a;
			scanf("%d", &a);
			book[i][a - 1] = 1;
		}
	}
	dp[0] = 1;
	for (int i = 1; i <= n; i++) {
		for (int s =  (1 << m) - 1; s >= 0; s--) {
			if (dp[s] != 0) {
				for (int j = 0; j < m; j++) {
					if (!(s >> j & 1) && book[i][j] != 0) {
						dp[s | (1 << j)] += dp[s];
					}
				}
				dp[s] = 0;
			}
		}
	}	
	int ans = 0;
	for (int i = 0; i < 1 << m; i++) ans += dp[i];
	printf("%d\n", ans);
	return 0;
}