解题代码
#include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include<string>
using namespace std;
typedef pair<string, int> pp;
bool cmp(pp a, pp b) {
return a.second != b.second ? a.second > b.second:a.first < b.first;
}
int main() {
int n, m, num;
string s;
cin >> n >> m;
vector<pp> v(n);
for (int i = 0; i < n; i++)
cin >> v[i].first >> v[i].second;
for (int i = 1; i <= m; i++) {
cin >> num >> s;
printf("Case %d: %d %s\n", i, num, s.c_str());
vector<pp> ans;
int cnt = 0, sum = 0;
if (num == 1) {
for (auto x : v)
if (x.first[0] == s[0])
ans.push_back(x);
}
else if (num == 2) {
for(auto x:v)
if (x.first.substr(1, 3) == s) {
cnt++;
sum += x.second;
}
if(cnt) printf("%d %d\n", cnt, sum);
}
else {
unordered_map<string, int> mm;
for (auto x : v) if (x.first.substr(4, 6) == s) mm[x.first.substr(1, 3)]++;
for (auto x : mm) ans.push_back(x);
}
sort(ans.begin(), ans.end(), cmp);
for (auto x : ans) printf("%s %d\n", x.first.c_str(), x.second);
if (((num==1 || num==3) && ans.size() == 0) || (num==2 && cnt == 0)) printf("NA\n");
}
return 0;
}
测试结果
问题整理
1.一开始我通过比较复杂的方法边输入数据边处理,争取输出时速度快一点,但这题明显输出时在处理要方便。