【算法学习记录-散列】【PAT A1092】To Buy or Not to Buy
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 Eva must check whether a string in the shop contains all the beads she needs. She now comes to you for help: if the answer is Yes, please tell her the number of extra beads she has to buy; or if the answer is No, please tell her the number of beads missing from the string.
For the sake of simplicity, let's use the characters in the ranges [0-9], [a-z], and [A-Z] to represent the colors. For example, the 3rd string in Figure 1 is the one that Eva would like to make. Then the 1st string is okay since it contains all the necessary beads with 8 extra ones; yet the 2nd one is not since there is no black bead and one less red bead.

Figure 1
Input Specification:
Each input file contains one test case. Each case gives in two lines the strings of no more than 1000 beads which belong to the shop owner and Eva, respectively.
Output Specification:
For each test case, print your answer in one line. If the answer is Yes, then also output the number of extra beads Eva has to buy; or if the answer is No, then also output the number of beads missing from the string. There must be exactly 1 space between the answer and the number.
Sample Input 1:
ppRYYGrrYBR2258
YrR8RrY
Sample Output 1:
Yes 8
Sample Input 2:
ppRYYGrrYB225
YrR8RrY
Sample Output 2:
No 2
思路:
0、是前三题思路的综合(A1084 B1033 B1038),先计数,再匹配
1、整体思路
依然是使用字符的ASCII码对应数组下标,下标对应元素值为字符的出现次数
首先读入第一行字符串并计数,每次使数组元素值+1
再读入第二行字符串,题意要求的“制作手串”可以理解为,每有一个符合要求的“珠子”,对应数组元素值-1,若没有符合要求的“珠子”,则减到负值,表示欠缺
最后将数组元素正的负的分别全部相加,然后判断Yes还是No
2、题解代码
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 using namespace std; 5 6 int main() { 7 int arr[128]; 8 9 for (int i = 0; i < 128; i++) { 10 arr[i] = 0; 11 } 12 13 char str1[1010]; 14 cin>>str1; 15 int len1 = strlen(str1); 16 char c1; 17 for (int i = 0; i < len1; i++) { 18 c1 = str1[i]; 19 arr[c1]++; 20 } 21 22 char str2[1010]; 23 cin>>str2; 24 int len2 = strlen(str2); 25 char c2; 26 for (int i = 0; i < len2; i++) { 27 c2 = str2[i]; 28 arr[c2]--; 29 } 30 31 int count1 = 0; 32 int count2 = 0; 33 34 for (int i = 0; i < 128; i++) { 35 if (arr[i] > 0) { 36 count1 += arr[i]; 37 } else if (arr[i] < 0) { 38 count2 += arr[i]; 39 } 40 } 41 42 count2 = 0 - count2; 43 44 if (count2 != 0) { 45 printf("No %d", count2); 46 } else if (count2 == 0) { 47 printf("Yes %d", count1); 48 } 49 50 return 0; 51 }
浙公网安备 33010602011771号