题目:
一个学生成绩录入和查询系统,接受以下两种输入:
Add name id score
Query score
name是个不超过16字符的字符串,中间没有空格,代表学生姓名。id 是个整数,代表学号。score是个整数,表示分数。学号不会重复,分数 和姓名都可能重复。
两种输入交替出现。第一种输入表示要添加一个学生的信息,碰到这 种输入,就记下学生的姓名、id和分数。第二种输入表示要查询,碰到这 种输入,就输出已有记录中分数比score低的最高分获得者的姓名、学号 和分数。如果有多个学生都满足条件,就输出学号最大的那个学生的信 息。如果找不到满足条件的学生,则输出“Nobody”。
输入样例:
Add Jack 12 78
Query 78 Query 81
Add Percy 9 81
Add Marry 8 81
Query 82
Add Tom 11 79
Query 80
Query 81
输出样例:
Nobody
Jack 12 78
Percy 9 81
Tom 11 79
Tom 11 79
代码:
#include<iostream>
#include<cstdio>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
struct StudentInfo
{
int id;
char name[20];
};
struct Student
{
int score;
StudentInfo info;
};
int main()
{
ios::sync_with_stdio(false);
multimap<int,StudentInfo> st;
multimap<int,StudentInfo>::iterator p;//迭代器
Student student;
int Result;
char cmd[10];
while(cin>>cmd)
{
switch(cmd[0])
{
case 'A':
cin>>student.info.name>>student.info.id>>student.score;
st.insert(pair<int,StudentInfo>(student.score,student.info));
break;
case 'Q':
cin>>Result;//要查询的成绩
p=st.lower_bound(Result);
if(p!=st.begin())//说明容器中有比Result大的值
{
p--;
int MaxScore=p->first;
multimap<int,StudentInfo>::iterator maxnp;
maxnp=p;
int MaxId=p->second.id;
for(;p->first==MaxScore&&p!=st.begin();p--)
{
if(p->second.id>MaxId)
{
MaxId=p->second.id;
maxnp=p;
}
}
if(p->first==MaxScore)//当p==st.begin()时
{
if(p->second.id>MaxId)
{
MaxId=p->second.id;
maxnp=p;
}
}
cout<<maxnp->second.name<<" "<<MaxId<<" "<<MaxScore<<endl;
}
else
cout<<"Nobody"<<endl;
break;
}
}
return 0;
}