题目
好久没练题了,一直忙许多乱七八糟的事情。最近要考甲级,所以重新刷甲级真题。这道题目不难,就是简单的查找与排序(说来说去,还是字符串的处理)。但是有个以前不知道,现在知道的点,关于C++中的endl与"\n"之间的区别。
在没有必要刷新输出流的时候应尽量使用cout<<"\n",过多的endl是影响程序执行效率底下的原因。
endl除了写’\n’进外,还调用flush函数,刷新缓冲区,把缓冲区里的数据写入文件或屏幕,考虑效率就用’\n’
因为大量使用endl,导致后面两个测试点一直运行超时。
#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
struct student{
string id;
int score;
}stu[N];
struct node{
string site;
int peo;
}place[N];
bool cmp1(const student &a, const student &b){
if(a.score!=b.score){
return a.score > b.score;
} else {
return a.id < b.id;
}
}
bool cmp2(const node &a, const node &b){
if(a.peo!=b.peo){
return a.peo > b.peo;
} else {
return a.site < b.site;
}
}
int main()
{
int n, m;
scanf("%d%d", &n, &m);
for(int i=0; i<n; i++){
cin>>stu[i].id>>stu[i].score;
}
string t, info;
for(int i=1; i<=m; i++){
cin>>t>>info;
cout<<"Case "<<i<<": "<<t<<" "<<info<<"\n";
if(t=="1"){
vector<student> v;
for(int j=0; j<n; j++){
if(stu[j].id.substr(0, 1)==info){
v.push_back(stu[j]);
}
}
if(v.size()){
sort(v.begin(), v.end(), cmp1);
for(int j=0; j<(int)v.size(); j++){
cout<<v[j].id<<" "<<v[j].score<<"\n";
}
} else {
printf("NA\n");
}
} else if(t=="2"){
int res=0, sum=0;
for(int j=0; j<n; j++){
if(stu[j].id.substr(1, 3)==info){
res+=1;
sum+=stu[j].score;
}
}
if(res){
printf("%d %d\n", res, sum);
} else {
printf("NA\n");
}
} else if(t=="3"){
unordered_map<string, int> mp;
for(int j=0; j<n; j++){
if(stu[j].id.substr(4, 6)==info){
mp[stu[j].id.substr(1, 3)]+=1;
}
}
if(mp.size()){
unordered_map<string, int>::iterator it;
int cnt=0;
for(it=mp.begin(); it!=mp.end(); it++){
place[cnt].site=it->first;
place[cnt].peo=it->second;
cnt+=1;
}
sort(place, place+cnt, cmp2);
for(int j=0; j<cnt; j++){
cout<<place[j].site<<" "<<place[j].peo<<"\n";
}
} else {
printf("NA\n");
}
} else {
printf("NA\n");
}
}
return 0;
}