0
点赞
收藏
分享

微信扫一扫

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++)【散列】_1092

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

 

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++)【散列】_1092_03

;对商店中没有的字符:

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

;遍历shop,判断是否有不足的情况,并输出:

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

 

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++)【散列】_C++_06

第二搏

总感觉写的有点繁琐。。。再次请教大神

果然,只需要一个map即可!

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

举报

相关推荐

0 条评论