1688: [Usaco2005 Open]Disease Manangement 疾病管理
Time Limit: 5 Sec
Memory Limit: 64 MB
Submit: 518
Solved: 341
[ Submit][ Status][ Discuss]
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. 有N头牛,它们可能患有D种病,现在从这些牛中选出若干头来,但选出来的牛患病的集合中不过超过K种病.
Output
* Line 1: M, the maximum number of cows which can be milked.
Sample Input
6 3 2
0---------第一头牛患0种病
1 1------第二头牛患一种病,为第一种病.
1 2
1 3
2 2 1
2 2 1
Sample Output
5
OUTPUT DETAILS:
If FJ milks cows 1, 2, 3, 5, and 6, then the milk will have only two
diseases (#1 and #2), which is no greater than K (2).
HINT
Source
题目大意:最多选出多少头奶牛使所患的疾病总数不超过K
题解:状压DP
因为奶牛数很大,所有把奶牛的编号作为一个维是很不现实的,我刚开始想看能不能通过状态来确定这只奶牛在之前是否出现过,但是根本无法实现,因为如果两个奶牛010,101,和一只奶牛111对答案的贡献是相同的。
那么转换一下思路,我们先不管状态,把所有可能的组合先计算出来,然后判断是否合法。组合是有点类似01背包的姿势,状态从大到小枚举,保证不重复选取。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define N 16
using namespace std;
int n,m,k,d,mi[N];
int f[1<<N];
int a[1003],pd[1<<N];
int main()
{
scanf("%d%d%d",&n,&d,&k);
mi[0]=1;
for (int i=1;i<=d;i++)
mi[i]=mi[i-1]<<1;
for (int i=1;i<=n;i++)
{
int x; scanf("%d",&x);
for (int j=1;j<=x;j++)
{
int y;
scanf("%d",&y);
a[i]+=mi[y-1];
}
}
int tot=(1<<d)-1;
memset(f,0,sizeof(f));
for (int i=0;i<=tot;i++)
{
int t=0;
for (int j=i;j;j>>=1)
if (j&1) t++; //cout<<t<<endl;
if (t<=k) pd[i]=1;
}
for (int i=1;i<=n;i++)
for (int j=tot;j>=0;j--)
f[j|a[i]]=max(f[j|a[i]],f[j]+1);
int ans=0;
for (int i=0;i<=tot;i++)
if (pd[i]) ans=max(ans,f[i]);
printf("%d\n",ans);
}