PAT1092:To Buy or Not to Buy
1092. To Buy or Not to Buy (20)
時間限制 100 ms 內存限制 65536 kB 代碼長度限制 16000 B 判題程序 Standard 作者 CHEN, YueEva 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.
ppRYYGrrYBR2258 YrR8RrYSample Output 1:
Yes 8Sample Input 2:
ppRYYGrrYB225 YrR8RrYSample Output 1:
No 2
思路
用map模擬一個字典。nomiss記錄滿足需求的珠子數,buy記錄買來的項鏈上多余珠子數。
1.把需要的項鏈的珠子放進字典裏並計數,如dic<珠子類別,珠子數>形式。
2.檢查買來的項鏈上的每一個珠子,如果在字典裏存在,則字典對應的珠子數減1,減1後如果為0則把對應珠子從字典裏刪掉。如果不存在buy++。
3.檢查字典是否為空,為空表示買來的項鏈滿足需求的項鏈,輸出多買的珠子數量buy;不為空表示買來的項鏈的珠子類別沒有滿足需求的項鏈,輸出需求項鏈缺失的珠子數量miss(miss = 需求項鏈的長度- nomiss)
代碼
#include<iostream> #include<string> #include<map> using namespace std; int main() { string shop,need; while(cin >> shop >> need) { //Initialize int buy = 0; int nomiss = 0; map<char,int> dic; for(int i = 0;i < need.size();i++) { if(dic.count(need[i]) > 0) dic[need[i]]++; else dic.insert(pair<char,int>(need[i],1)); } for(int i = 0;i < shop.size();i++) { if(dic.count(shop[i]) > 0) { if(--dic[shop[i]] == 0) { dic.erase(shop[i]); } nomiss++; } else buy++; } if(dic.empty()) cout << "Yes" << " " << buy; else cout << "No" << " " << need.size() - nomiss; } }
PAT1092:To Buy or Not to Buy