天天看點

PAT_甲級_1092 To Buy or Not to Buy (20point(s)) (C++)【散列】

目錄

​​1,題目描述​​

​​題目大意​​

​​2,思路​​

​​3,AC代碼​​

​​4,解題過程​​

​​第一搏​​

​​第二搏​​

1,題目描述

PAT_甲級_1092 To Buy or Not to Buy (20point(s)) (C++)【散列】
PAT_甲級_1092 To Buy or Not to Buy (20point(s)) (C++)【散列】

Sample Input 1:

ppRYYGrrYBR2258
YrR8RrY      

Sample Output 1:

Yes 8      

Sample Input 2:

ppRYYGrrYB225
YrR8RrY      

Sample Output 2:

No 2      

題目大意

判斷一個字元串中是否完全包含另一個字元串的所有字元(不需要連續,隻要有,且數目足夠)。

2,思路

使用一個map<char, int>:shop;

對商店中含有的字元:

PAT_甲級_1092 To Buy or Not to Buy (20point(s)) (C++)【散列】

;對商店中沒有的字元:

PAT_甲級_1092 To Buy or Not to Buy (20point(s)) (C++)【散列】

;周遊shop,判斷是否有不足的情況,并輸出:

PAT_甲級_1092 To Buy or Not to Buy (20point(s)) (C++)【散列】

3,AC代碼

#include<bits/stdc++.h>
using namespace std;
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    map<char, int> shop;
    string s;
    getline(cin, s);
    for(auto it : s)
        shop[it]++;
    getline(cin, s);
    for(auto it : s)
        shop[it]--;
    int a = 0, b = 0;       //a需要多買的珠子 b缺少的珠子
    for(auto it : shop){
        if(it.second < 0)
            b -= it.second;
        else
            a += it.second;
    }
    if(b == 0)
        cout<<"Yes"<<' '<<a;
    else
        cout<<"No"<<' '<<b;
    return 0;
}      

4,解題過程

第一搏

map可以很友善地解決問題

#include<bits/stdc++.h>
using namespace std;

int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    map<char, int> shop, eva;
    char c;
    int num1 = 0, num2 = 0, ans = 0;
    c = getchar();
    while(c != '\n'){
        shop[c]++;
        num1++;
        c = getchar();
    }
    c = getchar();
    while(c != '\n'){
        eva[c]++;
        num2++;
        c = getchar();
    }
    bool flag = true;
    for(auto it : eva){
        if(shop[it.first] < it.second){
            flag = false;
            ans += (it.second - shop[it.first]);
        }
    }
    if(flag)
        cout<<"Yes"<<' '<<num1 - num2;
    else
        cout<<"No"<<' '<<ans;
    return 0;
}      
PAT_甲級_1092 To Buy or Not to Buy (20point(s)) (C++)【散列】

第二搏

繼續閱讀