POJ 2441 Arrange the Bulls(狀態壓縮DP入門)

- Arrange the BullsTime Limit:4000MS    Memory Limit:65536KB    64bit IO Format:%lld & %llu

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


題意:牛想玩籃球,而且每頭牛不喜歡獨享一個牛棚,問你能夠滿足以上條件的情況有幾種。


解題思路:這題不好說,我已經在代碼上註明了,大家看完應該能看懂。這題對於剛入門的一定要反覆思考,完全想明白了那你就是一個質的飛躍。


<span style="font-size:18px;">#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int n,m;
int dp[1<<21],a[21][21];///a用於記錄牛是否喜歡這個房間,1代表喜歡,0代表不喜歡
int main()
{
    while(~scanf("%d %d",&n,&m))
    {
        int x;
        memset(a,0,sizeof(a));
        for(int i=1;i<=n;i++){
            scanf("%d",&x);
            for(int j=0;j<x;j++){
                int lie;
                scanf("%d",&lie);
                a[i][lie-1]=1;
            }
        }
        if(n>m){
            printf("0\n");
            continue;
        }
        memset(dp,0,sizeof(dp));
        dp[0]=1;/// 一開始全都爲空
        for(int i=1;i<=n;i++){ /// 枚舉每一頭牛
            for(int j=(1<<m)-1;j>=0;j--){ /// 枚舉每一個集合
                if(dp[j]){ ///如果這個集合存在
                    for(int k=0;k<m;k++){ /// 枚舉每一個房間
                        if(((1<<k)&j)!=0) continue; /// 如果這個集合的這個房間已經有人了
                        if(a[i][k]==0) continue; /// 如果牛不喜歡這個房間
                        int temp=(1<<k)|j; /// 這個新集合的值
                        dp[temp]+=dp[j]; /// 這個新集合賦值,其實就是1
                    }
                }
                dp[j]=0; /// 枚舉的集合變成了新集合,所以舊集合需要消除
            }
        }
        int ans=0;
        for(int i=0;i<(1<<m);i++) /// 最終留下來的集合就是滿足條件的了
            ans+=dp[i];
        printf("%d\n",ans);
    }
    return 0;
}</span>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章