Description

Problem D: Headmaster's Headache |
Time limit: 2 seconds |
The headmaster of Spring Field School is considering employing some new teachers for certain subjects. There are a number of teachers applying for the posts. Each teacher is able to teach one or more subjects. The headmaster wants to select applicants so that each subject is taught by at least two teachers, and the overall cost is minimized.
Input
The input consists of several test cases. The format of each of them is explained below:
The first line contains three positive integers S, M and N. S (≤ 8) is the number of subjects,M (≤ 20) is the number of serving teachers, and N (≤ 100) is the number of applicants.
Each of the following M lines describes a serving teacher. It first gives the cost of employing him/her (10000 ≤C ≤ 50000), followed by a list of subjects that he/she can teach. The subjects are numbered from 1 toS. You must keep on employing all of them. After that there areN lines, giving the details of the applicants in the same format.
Input is terminated by a null case whereS = 0. This case should not be processed.
Output
For each test case, give the minimum cost to employ the teachers under the constraints.
Sample Input
2 2 2 10000 1 20000 2 30000 1 2 40000 1 2 0 0 0
Sample Output
60000
题目描述:有s门课,m个教师,n个应聘者,要求每门课至少有两个人教,教师全选,求最小话费额。
思路:s<=8,状压dp,设s1是一门课有一个人教的集合,s2是每门课有两个人教的集合,可得答案为dp[s1][s2];
由于每个应聘者有选或者不选两种方案。所以可以用01背包的思想。对于p[i],ts1=p[i]|s1,ts2=(p[i]&s1)|s2,
dp[ts1][ts2]=min(dp[ts1][ts2],dp[s1][s2]+cost[i]),注意用逆序枚举,以避免重复。
#include <iomanip> #include <map> #include <queue> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <cmath> #include <cstdlib> #include <string> #include <cstdio> using namespace std; const int inf=1e9; #define LL long long int s,m,n; int cost[300],p[300+10],cnt[10]; LL dp[1<<10][1<<10]; int main() { while(scanf("%d%d%d",&s,&m,&n)&&s) { memset(cnt,0,sizeof(cnt)); int sum=0,ts1=0,ts2=0; for(int i=1;i<=m+n;i++){ char ss[1000]; p[i]=0; scanf("%d",&cost[i]); gets(ss); for(int j=0;j<strlen(ss);j++){ if(isdigit(ss[j])){ p[i]|=(1<<(ss[j]-'0'-1)); if(i<=m) cnt[ss[j]-'0']++; } } if(i<=m){ sum+=cost[i]; ts1|=p[i]; } } for(int i=1;i<=s;i++){ if(cnt[i]>1){ ts2|=(1<<(i-1)); } } for(int i=0;i<(1<<s);i++){ for(int j=0;j<(1<<s);j++){ dp[i][j]=inf; } } dp[ts1][ts2]=sum; for(int i=m+1;i<=m+n;i++){ for(int s1=(1<<s)-1;s1>=0;s1--){ for(int s2=(1<<s)-1;s2>=0;s2--){ if(dp[s1][s2]>=inf) continue; int ns1=s1|p[i]; int ns2=(s1&p[i])|s2; dp[ns1][ns2]=min(dp[ns1][ns2],dp[s1][s2]+cost[i]); } } } cout<<dp[(1<<s)-1][(1<<s)-1]<<endl; } return 0; }