问题![](https://img-blog.csdnimg.cn/202109221655001.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAQXByaWwwMTE5,size_20,color_FFFFFF,t_70,g_se,x_16)
代码(18)
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int n;
cin >> n;
int score[100002]={0};//记录不同学校的分数
int t = 0,grade = 0,tmax = 0;//t表示每次输入的学校编号,grade对应的成绩
for (int i=0; i<n; i++)
{
cin >> t;
cin >> grade;
score[t] += grade;//相同编号的成绩累加
if (t > tmax)//找到学校编号的最大值,便于控制下一个for循环的循环条件
tmax = t;
}
int max = 0;//记录分数最高的学校的编号
int i = 1;
for (i; i<=tmax; i++)
{
if (score[i] > score[max])
max = i;
}
cout << max << " " << score[max];
return 0;
}
上述代码只有18分,没有通过测试点2。问题是,如果输入的成绩为0分,和初始化的成绩相同,无法找出最高成绩的学校。
代码(20)
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int n;
cin >> n;
int score[100002];//记录不同学校的分数
memset(score,-1,sizeof(score));//将所有编号对应的成绩初始化为-1
int t = 0,grade = 0,tmax = 0;//t表示每次输入的学校编号,grade对应的成绩
for (int i=0; i<n; i++)
{
cin >> t;
cin >> grade;
if (score[t] < 0)//小于0表示第一次出现这个学校,将其成绩设置为0
score[t] = 0;
score[t] += grade;//相同编号的成绩累加
if (t > tmax)//找到学校编号的最大值,便于控制下一个for循环的循环条件
tmax = t;
}
int max = 0;//记录分数最高的学校的编号
int i = 1;
for (i; i<=tmax; i++)
{
if (score[i] > score[max])
max = i;
}
cout << max << " " << score[max];
return 0;
}
笔记
- 使用 int score[100002] = {-1}; 只是给数组的第一个元素赋值为-1,其余元素仍然为0
- memset的使用 memset(score,-1,sizeof(score)); 需要头文件 #include<cstring>