牛客春招刷题训练营 - 3.10题解 | C++
活动地址: 牛客春招刷题训练营 - 编程打卡活动
简单题:字符串最后一个单词的长度
用 while(cin) 不断读入以空格隔开的字符串,然后用一个len变量不断自己覆盖自己,最后一次覆盖的结果就是最后一个单词的长度。
#include <iostream> using namespace std; int main() { int len = 0; string x; while(cin >> x) { len = x.size(); } cout << len << endl; return 0; }
中等题:明明的随机数
用一个离散化板子就行了。
不清楚“离散化”的朋友可以跳转 OI Wiki - 离散化 补充一下知识点。
其中,有两个不太常用的STL函数:
unique(a.begin(), a.end());
:将向量a
中的重复元素移动到向量的末尾,并返回指向第一个重复元素的迭代器。a.erase(..., a.end());
:删除从第一个重复元素到向量末尾的所有元素,从而实现去重。
#include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> a(n); for(int &x: a) cin >> x; sort(a.begin(), a.end()); a.erase(unique(a.begin(), a.end()), a.end()); for(int x: a) cout << x << endl; return 0; }
困难题:坐标移动
先按 ";" 分割字符串,然后遍历每个字符串,不合法的跳过即可。
由于一个合法的指令由三至四个符号组成,所以只可能是“A1;” 或 "A10"; 这样的形式,所以去掉分号之后,字符串的长度不为2或3的都跳过。
此外,第一位不是 WASD,或后面的位数不是数字的都可以跳过。
满足条件的指令直接模拟就可。
#include <iostream> #include <map> #include <vector> using namespace std; int main() { string s, t = ""; cin >> s; vector<string> a; // 以;分割字符串 for(auto c: s) { if(c == ';') { a.emplace_back(t); t = ""; } else { t.push_back(c); } } map<char, pair<int, int>> mp; mp['A'] = {-1, 0}; mp['D'] = {1, 0}; mp['W'] = {0, 1}; mp['S'] = {0, -1}; int x = 0, y = 0; for(string t: a) { if(t.size() < 2 || t.size() > 3) continue; if(!mp.count(t[0])) continue; if(t.size() == 2) { auto [dx, dy] = mp[t[0]]; if(t[1] >= '0' && t[1] <= '9') { x += dx * (t[1] - '0'); y += dy * (t[1] - '0'); } else continue; } if(t.size() == 3) { auto [dx, dy] = mp[t[0]]; if(t[1] >= '0' && t[1] <= '9') { if(t[2] >= '0' && t[2] <= '9') { x += dx * (t[2] - '0'); y += dy * (t[2] - '0'); } else { continue; } x += dx * (t[1] - '0') * 10; y += dy * (t[1] - '0') * 10; } else continue; } } cout << x << "," << y << endl; }#牛客春招刷题训练营#