Description
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
Output
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>