solution
- 测试点3超时:命令为3时,用unordered_map而非map,否则会超时
#include<iostream>
#include<string>
#include<algorithm>
#include<unordered_map>
using namespace std;
const int maxn = 1e4 + 10;
struct stu{
string id;
int score;
friend bool operator < (stu &s1, stu &s2){
if(s1.score == s2.score) return s1.id < s2.id;
return s1.score > s2.score;
}
}stus[maxn], temp[maxn];
int main(){
int n, m, com, cnt, sum;
string coms;
cin >> n >> m;
for(int i = 0; i < n; i++){
cin >> stus[i].id >> stus[i].score;
}
for(int j = 1; j <= m; j++){
cnt = sum = 0;
cin >> com >> coms;
cout << "Case " << j << ": " << com << " " << coms << endl;
if(com == 1){
for(int i = 0; i < n; i++){
if(stus[i].id.substr(0, 1) == coms){
temp[cnt].id = stus[i].id;
temp[cnt++].score = stus[i].score;
}
}
}
else if(com == 2){
for(int i = 0; i < n; i++){
if(stus[i].id.substr(1, 3) == coms){
cnt++;
sum += stus[i].score;
}
}
if(cnt) cout << cnt << " " << sum << endl;
}
else{
unordered_map<string, int> mp;
for(int i = 0; i < n; i++){
if(stus[i].id.substr(4, 6) == coms) mp[stus[i].id.substr(1, 3)]++;
}
for(unordered_map<string, int>::iterator it = mp.begin(); it != mp.end(); it++){
temp[cnt].id = it -> first;
temp[cnt++].score = it -> second;
}
}
if(com != 2){
sort(temp, temp + cnt);
for(int i = 0; i < cnt; i++){
cout << temp[i].id << " " << temp[i].score << endl;
}
}
if(!cnt) cout << "NA" << endl;
}
return 0;
}
或者
#include<iostream>
#include<string>
#include<algorithm>
#include<unordered_map>
#include<vector>
using namespace std;
const int maxn = 1e4 + 10;
struct stu{
string id;
int score;
friend bool operator < (stu &s1, stu &s2){
if(s1.score == s2.score) return s1.id < s2.id;
return s1.score > s2.score;
}
}stus[maxn];
int main(){
int n, m, com, cnt, sum;
string coms;
cin >> n >> m;
for(int i = 0; i < n; i++){
cin >> stus[i].id >> stus[i].score;
}
for(int j = 1; j <= m; j++){
cnt = sum = 0;
vector<stu> vs;
cin >> com >> coms;
cout << "Case " << j << ": " << com << " " << coms << endl;
if(com == 1){
for(int i = 0; i < n; i++){
if(stus[i].id.substr(0, 1) == coms) vs.push_back(stus[i]);
}
}
else if(com == 2){
for(int i = 0; i < n; i++){
if(stus[i].id.substr(1, 3) == coms){
cnt++;
sum += stus[i].score;
}
}
if(cnt) cout << cnt << " " << sum << endl;
}
else{
unordered_map<string, int> mp;
for(int i = 0; i < n; i++){
if(stus[i].id.substr(4, 6) == coms) mp[stus[i].id.substr(1, 3)]++;
}
for(unordered_map<string, int>::iterator it = mp.begin(); it != mp.end(); it++){
vs.push_back({it -> first, it -> second});
}
}
if(com != 2){
sort(vs.begin(), vs.end());
for(int i = 0; i < vs.size(); i++){
cout << vs[i].id << " " << vs[i].score << endl;
}
}
if(!cnt && !vs.size()) cout << "NA" << endl;
}
return 0;
}