错误点1:再cmpNt中用sscanf函数将string化为int,导致测试点4超时
错误点2:将string用scanf输入后,如果不substr后比较||赋值,就会发生错误。可能和resize有关
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <unordered_map>
using namespace std;
const int SIZE = 10005;
struct Lpeo {
string number;
int score;
Lpeo() {number.resize(20);}
} peo[SIZE];
bool cmp(const Lpeo& a, const Lpeo& b) {
if (a.score != b.score) return a.score > b.score;
else return a.number < b.number;
}
bool cmpNt(const pair<string, int>& a, const pair<string, int>& b) {
if (a.second != b.second) return a.second > b.second;
else {
int num1, num2;
sscanf(a.first.c_str(), "%d", &num1);
sscanf(b.first.c_str(), "%d", &num2);
return num1 < num2;
}
}
int main() {
int N, M;
scanf("%d %d", &N, &M);
for (int i = 0; i < N; i ++) {
scanf("%s %d", &peo[i].number[0], &peo[i].score);
}
int type;
string s, s1, s2, st;
s.resize(20);
vector<Lpeo> res;
vector<pair<string, int>> vt;
unordered_map<string, int> mp;
for (int i = 1; i <= M; i ++) {
scanf("%d %s", &type, &s[0]);
res.clear();
mp.clear();
vt.clear();
printf("Case %d: %d %s\n", i, type, s.c_str());
int totalSum = 0, totalScore = 0;
if (type == 1) {
for (int i = 0; i < N; i ++) {
if (peo[i].number[0] == s[0]) {
res.push_back(peo[i]);
}
}
sort(res.begin(), res.end(), cmp);
for (int i = 0; i < res.size(); i ++) {
printf("%s %d\n", res[i].number.c_str(), res[i].score);
}
if (res.size() == 0) printf("NA\n");
} else if (type == 2) {
for (int i = 0; i < N; i ++) {
s1 = peo[i].number.substr(1, 3); /*substr出错*/
s2 = s.substr(0, 3); /*当s2 == s时出错*/
// printf("%s %s\n", peo[i].number.substr(1, 3).c_str(), s.c_str());
// if (peo[i].number.substr(1, 3) == s) /*不对,找一下原因*/
if (s1 == s2) {
totalSum ++;
totalScore += peo[i].score;
}
}
if (totalSum == 0 && totalScore == 0) printf("NA\n");
else printf("%d %d\n", totalSum, totalScore);
} else {
for (int i = 0; i < N; i ++) {
s1 = peo[i].number.substr(4, 6);
s2 = s.substr(0, 6);
if (s1 == s2) {
st = peo[i].number.substr(1, 3);
mp[st] ++;
}
}
for (auto p : mp) vt.push_back(p);
sort(vt.begin(), vt.end(), cmpNt);
for (int i = 0; i < vt.size(); i ++) printf("%s %d\n", vt[i].first.c_str(), vt[i].second);
if (vt.size() == 0) printf("NA\n");
}
}
cin >> s;
return 0;
}