Disease Management
Description
Alas! A set of D (1 <= D <= 15) diseases (numbered 1..D) is running through the farm. Farmer John would like to milk as many of his N (1 <= N <= 1,000) cows as possible. If the milked cows carry more than K (1 <= K <= D) different diseases among them, then the milk will be too contaminated and will have to be discarded in its entirety. Please help determine the largest number of cows FJ can milk without having to discard the milk.
Input
* Line 1: Three space-separated integers: N, D, and K
* Lines 2..N+1: Line i+1 describes the diseases of cow i with a list of 1 or more space-separated integers. The first integer, d_i, is the count of cow i's diseases; the next d_i integers enumerate the actual diseases. Of course, the list is empty if d_i is 0.
Output
* Line 1: M, the maximum number of cows which can be milked.
Sample Input
6 3 2
0
1 1
1 2
1 3
2 2 1
2 2 1
Sample Output
5 思路:需要用到位运算,D最为16,用一个int数(32位 > 16位,足够表示)的每个二进制位表示病毒的存在与否,1为存在,0不存在,这样复杂度为2^16*n(通过剪枝实际达不到这么大),可以接受。因此有两种方法解本题,(1),dfs,枚举D的k-组合。(2),通过二进制枚举D的k-组合。
用dfs,最后程序跑得时间是32ms,二进制枚举跑得时间是285ms,如此大的差距,原因就是二进制把所有组合都枚举完了,其中包含很多冗余状态,说白了就是大爆力。 DFS版:(32ms)
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<string>
#include<algorithm>
#define MAXN 1111
using namespace std;
int cow[MAXN],vis[MAXN],N,D,K,ans;
void dfs(int idx,int cnt,int sum){
if(cnt == K){
int num = ;
for(int i = ;i < N;i ++)
if(cow[i] == (cow[i] & sum)) num++;
ans = max(ans,num);
return;
}
for(int i = idx;i < D;i ++){
if(!vis[i]){
vis[i] = ;
dfs(i+,cnt+,sum|( << i));
vis[i] = ;
}
}
}
int main(){
int tmp,kind;
// freopen("in.c","r",stdin);
while(~scanf("%d%d%d",&N,&D,&K)){
memset(cow,,sizeof(cow));
memset(vis,,sizeof(vis));
for(int i = ;i < N;i ++){
scanf("%d",&tmp);
for(int j = ;j < tmp;j ++){
scanf("%d",&kind);
cow[i] |= ( << (kind-));
}
}
ans = ;
dfs(,,);
printf("%d\n",ans);
}
return ;
}
二进制枚举版:(285ms)
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<string>
#include<algorithm>
#define MAXN 1111
using namespace std;
int cow[MAXN];
int count_digit(int n){
int cnt = ;
for(int i = ;i < ;i ++)
if(n & ( << i)) cnt ++;
return cnt;
}
int main(){
int n,m,k,tmp,kind;
//freopen("in.c","r",stdin);
while(~scanf("%d%d%d",&n,&m,&k)){
memset(cow,,sizeof(cow));
for(int i = ;i < n;i ++){
scanf("%d",&tmp);
for(int j = ;j < tmp;j ++){
scanf("%d",&kind);
cow[i] |= ( << (kind-));
}
}
int ans = ;
for(int i = ;i < ( << m);i ++){
int sum = ,cnt = ;
if(count_digit(i) > k) continue;
for(int j = ;j < n;j ++)
if((cow[j] | i) == i) cnt++;
ans = max(ans,cnt);
}
printf("%d\n",ans);
}
return ;
}