POJ 2441 Arrange the Bulls(状压dp)

Arrange the Bulls
Time Limit: 4000MS   Memory Limit: 65536K
Total Submissions: 5471   Accepted: 2088

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

题解:
数组直接开二维会MLE,后来一想可以把n的循环拿到
最外面,然后开一个滚动数组。
dp[i][j],i表示还未使用的栅栏的集合,j表示匹配
到前j头牛有几种可能。
代码:
#include<cstdio>
#include<string.h>
#include<algorithm>
#include<vector>
using namespace std;
int dp[1<<20][2],tol=0,head[22];
struct node
{
    int to,next;
}G[404];
void add(int a,int b)
{
    G[tol].to=b;
    G[tol].next=head[a];
    head[a]=tol++;
}
int main()
{
    memset(head,-1,sizeof(head));
    int n,m;
    scanf("%d%d",&n,&m);
    if(n>m)
    {
        printf("0\n");
        return 0;
    }
    for(int i=0;i<n;i++)
    {
        int T;scanf("%d",&T);
        while(T--)
        {
            int x;scanf("%d",&x);
            add(i+1,x-1);
        }
    }
    dp[(1<<m)-1][0]=1;
    int t;
    for(int i=1;i<=n;i++)
    {
        t=i%2;
        for(int S=(1<<m)-1;S>=0;S--)
        {
            if(!dp[S][t^1])continue;//剪枝,若dp[S][t^1]==0,后面的循环无效
            //没加这个剪枝前3200ms,加了之后125ms,可见dp[S][t^1]!=0的状态不多
            for(int j=head[i];j!=-1;j=G[j].next)
            {
                int x=G[j].to;
                if(S>>x&1)
                {
                    dp[(~(1<<x))&S][t]+=dp[S][t^1];
                }
            } 
            dp[S][t^1]=0;
        }
    }
    int ans=0;
    for(int i=0;i<(1<<m);i++)
        ans+=dp[i][t];
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/albertluf/article/details/80316724
今日推荐