poj2441(状压dp)

来源:互联网 发布:买卖点炒股软件 编辑:程序博客网 时间:2024/05/21 11:33

http://poj.org/problem?id=2441

Arrange the Bulls
Time Limit: 4000MS Memory Limit: 65536KTotal Submissions: 4810 Accepted: 1832

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 42 1 42 1 32 2 4

Sample Output

4

题意:有N头牛M个棚子,每头牛都有自己喜欢的棚子且每个棚子只能放一头牛,求方案数

题解:状态压缩dp(通过状态压缩来保存状态的dp)

例如,有五个棚子,用0代表无牛,用1代表有牛。那么01101就代表第1,3,4个棚子中有牛。

范围就是00000-11111。dp每一种牛棚状态即可。


ok[i][j]:表示第i头牛可以放入j棚

dp[j]:表示牛棚的j状态下i头牛入棚

状态转移方程:dp[i|(1<<k)]+=dp[i] (dp[i|(1<<k)]表示将第i+1头牛入k棚),这里也可改为dp[i|(1<<k)]=1,及该方案存在


一共有三重for循环

第一重:i枚举每一头牛

第二重:j枚举每一种牛棚状态(这里判断j状态是否有i-1头牛,及该状态只有一个空牛棚)

第三重:k枚举每一个牛棚(这里判断第i头牛是否可以放入k棚以及k棚是否有牛)


count:枚举牛棚的每一种状态,若改状态有n头牛 count+=dp[i];


代码:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int dp[(1<<20)+5];int ok[25][25];int n,m;void solve(){dp[0]=1;//初始化0头牛入0个棚有一种方案 for(int i=1;i<=n;i++)//枚举每一头牛 for(int j=(1<<m);j>=0;j--){//枚举每一种牛棚状态 if(dp[j])//j状态有i-1头牛 for(int k=1;k<=m;k++)//枚举每一个牛棚 if(ok[i][k]&&(j!=(j|(1<<(k-1)))))//判断i牛是否可以放入k棚&&k棚是否有牛 dp[j|(1<<(k-1))]+=dp[j]; //放牛 dp[j]=0;//清空j状态有i-1头牛的状态,以免枚举第i头牛时if(dp[j])处错误 }int cnt=0;for(int i=0;i<(1<<m);i++)cnt+=dp[i];printf("%d\n",cnt);return;}int main(){memset(dp,0,sizeof(dp));memset(ok,0,sizeof(ok));scanf("%d%d",&n,&m);for(int i=1;i<=n;i++){int num,tmp;scanf("%d",&num);while(num--){scanf("%d",&tmp);ok[i][tmp]=1;}}solve();return 0;}


0 0
原创粉丝点击