您的位置:首页 > 其它

poj 2441 Arrange the Bulls(状态压缩dp)

2015-08-28 20:23 337 查看
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


Source

POJ Monthly,TN

状态压缩 + 滚动数组 + 位运算

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 26
int like

;
int dp[2][1<<20];
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)==2){

for(int i=1;i<=n;i++){
int s;
scanf("%d",&s);
for(int j=1;j<=s;j++){
scanf("%d",&like[i][j]);
}
}

dp[0][0]=1;
for(int i=1;i<=n;i++){
for(int j=0;j<(1<<m);j++){
if(dp[(i-1)&1][j]){
for(int k=1;k<=m;k++){
if(like[i][k] && (j&(1<<(like[i][k]-1)))==0 ){
dp[i&1][j|(1<<(like[i][k]-1))]+=dp[(i-1)&1][j];
}
}
}
}
memset(dp[(i-1)&1],0,sizeof(dp[(i-1)&1]));
}
int ans=0;
for(int i=0;i<(1<<m);i++){
ans+=dp[n&1][i];
}
printf("%d\n",ans);
}
return 0;
}


View Code

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: