思路:
1.暴力破解,直接进行遍历排序即可;
2.第三个type使用unordered_map比较方便;
注意点:
1.个别数据转换成int输出时要注意形式;
2.避免超时问题;
代码:
#include<iostream>
#include<algorithm>
#include<map>
#include<unordered_map>
#include<vector>
using namespace std;
bool cmp(const pair<string, int> &p1, const pair<string, int> &p2)
{
return p1.second == p2.second ? p1.first<p2.first : p1.second>p2.second;
}
int main()
{
int n, m;
cin >> n >> m;
multimap<char, pair<string, int>> t1;
multimap<string, int> t2;
multimap<string, string> t3;
for (int i = 0; i < n; i++)
{
string id;
int score;
cin >> id >> score;
t1.insert(make_pair(id[0], make_pair(id, score)));
t2.insert(make_pair(id.substr(1, 3), score));
t3.insert(make_pair(id.substr(4, 6), id.substr(1, 3)));
}
for (int i = 0; i < m; i++)
{
int type;
string term;
cin >> type >> term;
printf("Case %d: %d %s
", i + 1, type, term.c_str());
vector<pair<string, int>> v;
if (type == 1)
{
multimap<char, pair<string, int>>::iterator it;
for (it = t1.find(term[0]); it != t1.end() && it->first == term[0]; it++)
v.push_back(make_pair((it->second).first, (it->second).second));
}
else if (type == 2)
{
multimap<string, int>::iterator it;
int totalscore = 0;
it = t2.find(term);
if (it != t2.end())
{
for (; it->first == term; it++)
totalscore += it->second;
printf("%d %d
", t2.count(term), totalscore);
}
else
printf("%s
", "NA");
}
else if (type == 3)
{
multimap<string, string>::iterator it;
unordered_map<string, int> mp;
it = t3.find(term);
while (it != t3.end() && it->first == term)
mp[(it++)->second]++;
for (auto it : mp)
v.push_back(make_pair(it.first, it.second));
}
sort(v.begin(), v.end(), cmp);
for (auto vi : v)
printf("%s %d
", vi.first.c_str(), vi.second);
if (type != 2 && v.size() == 0)
printf("%s
", "NA");
}
return 0;
}