-
Arrange the BullsTime Limit:4000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu
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.
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
题意:牛想玩篮球,而且每头牛不喜欢独享一个牛棚,问你能够满足以上条件的情况有几种。
解题思路:这题不好说,我已经在代码上注明了,大家看完应该能看懂。这题对于刚入门的一定要反复思考,完全想明白了那你就是一个质的飞跃。
<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>