poj 2441 Arrange the Bulls

Arrange the Bulls
Time Limit: 4000MS   Memory Limit: 65536K
Total Submissions: 5427   Accepted: 2069

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

题意:把n头牛放进m个棚,并且每头牛都要住进自己喜欢的棚,一共有多少放法。
思路:状压dp,dp[i][j]:前i头牛的放法是状态j时的放法数。
转移方程:定义dp[i-1][k],即前i-1头牛放法是状态k,并且设第i头牛要放入位置j,if(k&(1<<j)==0),即状态k的第j个位置空着,则第i头牛可以入住位置j,dp[i][k|1<<j]+=dp[i-1][k]
AC代码:
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include<vector>
#include<algorithm>
#include<cstring>
#include<bitset>
using namespace std;
#define N_MAX 21
#define M_MAX 21
#define MOD 10000000
#define INF 0x3f3f3f3f
int n, m;
vector<int> can_in[N_MAX];
int dp[2][1 << M_MAX];

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) {
        int p; scanf("%d", &p);
        while (p--) {
            int a; scanf("%d", &a); a--;
            can_in[i].push_back(a);
        }
    }
    int allstates = 1 << m;
    for (int j = 0; j < can_in[0].size(); j++) {
        dp[0][1 << can_in[0][j]] = 1;
    }
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < can_in[i].size(); j++) {
            for (int k = 0; k < allstates; k++) {
                if (dp[(i - 1)&1][k] && !(k >> can_in[i][j] & 1)) {
                    dp[i&1][k | 1 << can_in[i][j]] += dp[(i - 1)&1][k];
                }
            }
        }
    }
    int sum = 0;
    for (int i = 0; i < allstates; i++) {
        bitset<32>bit(i);
        if(bit.count()==n)
        sum += dp[(n - 1) & 1][i];
    }
    printf("%d\n", sum);

    return 0;
}

 

posted on 2018-04-06 13:59  ZefengYao  阅读(145)  评论(0编辑  收藏  举报

导航