PAT 乙级练习 题解合集
题目
萌萌哒表情符号通常由“手”、“眼”、“口”三个主要部分组成。简单起见,我们假设一个表情符号是按下列格式输出的:
[左手]([左眼][口][右眼])[右手]
现给出可选用的符号集合,请你按用户的要求输出表情。
输入格式:
输入首先在前三行顺序对应给出手、眼、口的可选符号集。每个符号括在一对方括号 []内。题目保证每个集合都至少有一个符号,并不超过 10 个符号;每个符号包含 1 到 4 个非空字符。
之后一行给出一个正整数 K,为用户请求的个数。随后 K 行,每行给出一个用户的符号选择,顺序为左手、左眼、口、右眼、右手——这里只给出符号在相应集合中的序号(从 1 开始),数字间以空格分隔。
输出格式:
对每个用户请求,在一行中输出生成的表情。若用户选择的序号不存在,则输出 Are you kidding me? @\/@
。
输入样例:
[╮][╭][o][~\][/~] [<][>]
[╯][╰][^][-][=][>][<][@][⊙]
[Д][▽][_][ε][^] ...
4
1 1 2 2 2
6 8 1 5 5
3 3 4 3 3
2 10 3 9 3
输出样例:
╮(╯▽╰)╭
<(@Д=)/~
o(^ε^)o
Are you kidding me? @\/@
思路
我用了比较偷懒的办法,更优雅的方法是把所有可用的表情字符串放在 3 个vector<string>
里面,而我是每次要用的时候都临时去找…不过这题数据量不大,无所谓了。
代码解释:
- 把前三行直接存在三个字符串里面;
- 对于每一行输入的序号,用
output
来组装最终的输出; string findEmoji(const string &str, int no);
这个函数在str
字符串里找到第no
对'['
和']'
中间的字符串并将其返回,如果用户选择的序号不存在,返回'['
(因为我相信'['
这个字符既然是输入的界定符,就不会出现在表情里面,于是拿它来处理异常输入)。- 不断地用
findEmoji
函数组装生成output
- 组装完成后判断
output
中是否有'['
,如果有的话说明有用户选择的序号不存在,没有的话正常输出。
注意Are you kidding me? @\/@
中的'\'
在代码中要用"\\"
输出。
学到的东西:
string
的成员函数size_t find (char c, size_t pos = 0) const;
,如果没找到的话返回的是std::string::npos
,找到的话返回的是对应的下标,所以不能写if (str.find(x))
这样的判断,和 C 语言里面的strchr
返回指针和空指针不一样。
代码
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string findEmoji(const string &str, int no) {
string output, noGood = "[";
int index = 0, cnt = 0;
while (cnt < no && index != str.size()) {
if (str[index] == '[')
++cnt;
++index;
if (cnt == no)
break;
}
if (index == str.size())
return noGood;
while (str[index] != ']')
output += str[index++];
return output;
}
int main() {
string hands, eyes, mouths;
getline(cin, hands);
getline(cin, eyes);
getline(cin, mouths);
int k, input;
cin >> k;
while (k--) {
vector<int> nums;
string output;
for (int i = 0; i != 5; ++i) {
cin >> input;
nums.push_back(input);
}
output += findEmoji(hands, nums[0]);
output += '(';
output += findEmoji(eyes, nums[1]);
output += findEmoji(mouths, nums[2]);
output += findEmoji(eyes, nums[3]);
output += ')';
output += findEmoji(hands, nums[4]);
if (output.find('[') != string::npos)
cout << "Are you kidding me? @\\/@\n";
else
cout << output << "\n";
}
return 0;
}