文章標題 POJ 2441 :Arrange the Bulls(狀壓DP)

Arrange the Bulls

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個位置,每隻牛有自己喜歡的k個位置,當有一隻佔據了一個位置,這個位置就不能有其他的牛,現在要我們求出這m個位置分配給n只牛有多少方案數。
分析:顯然,當n > m時,方案數爲0;由題意可以知道m<=20,所以可以用狀態壓縮,用dp[i][j]表示前i只牛所形成的狀態爲j時的方案數,但是直接開開不下,然後我們可以發現類似揹包問題直接從大往小的狀態下可以直接開一個一維數組就行了。
代碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <vector>
using namespace std;
typedef long long ll;

const int mod=1e9+7;
const int maxn=(1<<20)+10;

int n,m;
int dp[maxn];
int k,tmp;
int mp[25][25];

int main()
{
    while (scanf ("%d%d",&n,&m)!=EOF){
        for (int i=0;i<n;i++){
            scanf ("%d",&k);
            while (k--){
                scanf ("%d",&tmp);
                tmp--;
                mp[i][tmp]=1;
//標記能在tmp這個位置
            }
        }
        if (n>m){
            printf ("0\n");
            continue;
        }
        memset (dp,0,sizeof (dp));
        dp[0]=1;
        for (int i=0;i<n;i++){
            for (int j=(1<<m)-1;j>=0;j--){
                if (dp[j]==0)continue;//表示前i-1只牛沒有形成這個狀態
                for (int k=0;k<m;k++){//枚舉m個場地 
                    if((1<<k)&j)continue;//如果k這個位置已經有人佔據了
                    if (mp[i][k]==0)continue;//如果第i只牛不能在第k個位置就跳過
                    int pos=j|(1<<k);
                    dp[pos]+=dp[j]; 
                } 
                dp[j]=0;//表示前i只已經沒有這種狀態了 
            }
        }
        int ans=0;
        for(int i=0;i<(1<<m);i++){
//求值
            ans+=dp[i];
        } 
        printf ("%d\n",ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章