pat 1004 To Buy or Not to Buy - Hard Version (35 分)
Eva would like to make a string of beads with her favorite colors so she went to a small shop to buy some beads. There were many colorful strings of beads. However the owner of the shop would only sell the strings in whole pieces. Hence in some cases Eva might have to buy several strings to get all the beads she needs. With a hundred strings in the shop, Eva needs your help to tell her whether or not she can get all the beads she needs with the least number of extra beads she has to pay for.
For the sake of simplicity, let's use the characters in the ranges [0-9], [a-z], and [A-Z] to represent the colors. In sample 1, buying the 2nd and the last two strings is the best way since there are only 3 extra beads. In sample 2, buying all the three strings won't help since there are three R
beads missing.
Input Specification:
Each input file contains one test case. Each case first gives in a line the string that Eva wants. Then a positive integer N(≤) is given in the next line, followed by N lines of strings that belong to the shop. All the strings contain no more than 1000 beads.
Output Specification:
For each test case, print your answer in one line. If the answer is Yes
, then also output the least number of extra beads Eva has to buy; or if the answer is No
, then also output the number of beads missing from all the strings. There must be exactly 1 space between the answer and the number.
Sample Input 1:
RYg5
8
gY5Ybf
8R5
12346789
gRg8h
5Y37
pRgYgbR52
8Y
8g
Sample Output 1:
Yes 3
Sample Input 2:
YrRR8RRrY
3
ppRGrrYB225
8ppGrrB25
Zd6KrY
Sample Output 2:
No 3
这题看似只能暴力搜索,但是$O(2^n)$让人不敢尝试,然后。。
然后还是尝试了,随便写了一个搜索,居然就过了,只能说pat的数据实在是太弱了。
1 #include<bits/stdc++.h> 2 using namespace std; 3 int const N=100+10; 4 int num[N<<1],cnt[N<<1],n,ans=300,c[N][N<<1],sel[N]; 5 string s,a[N]; 6 void dfs(int x,int ex){ 7 if(ex>=ans) return; 8 if(x>n) { 9 int check=0; 10 for(int i=48;i<130;i++) 11 if(cnt[i]<num[i]) check=1; 12 if(!check) ans=ex; 13 return ; 14 } 15 int tmp=ex; 16 for(int i=48;i<130;i++){ 17 if(cnt[i]>=num[i]) 18 ex+=c[x][i]; 19 else if(cnt[i]+c[x][i]>=num[i]) ex+=cnt[i]+c[x][i]-num[i]; 20 cnt[i]+=c[x][i]; 21 } 22 sel[x]=1; 23 dfs(x+1,ex); 24 sel[x]=0; 25 for(int i=48;i<130;i++) 26 cnt[i]-=c[x][i]; 27 dfs(x+1,tmp); 28 } 29 int main(){ 30 cin>>s; 31 for(int i=0;i<s.length();i++) 32 num[s[i]]++; 33 scanf("%d",&n); 34 for(int i=1;i<=n;i++) 35 { 36 cin>>a[i]; 37 for(int j=0;j<a[i].length();j++) 38 cnt[a[i][j]]++,c[i][a[i][j]]++; 39 } 40 int sum=0; 41 for(int i=0;i<200;i++) 42 if(cnt[i]<num[i]){ 43 sum+=num[i]-cnt[i]; 44 } 45 if(sum){ 46 printf("No %d\n",sum); 47 return 0; 48 } 49 memset(cnt,0,sizeof(cnt)); 50 dfs(1,0); 51 printf("Yes %d\n",ans); 52 return 0; 53 }