PAT乙级1032

题目链接

https://pintia.cn/problem-sets/994805260223102976/problems/994805289432236032

题解

用数组的下标表示学校,数组元素表示分数。统计各校分数后,遍历求最大就好了。

做这道题遇到一个memset初始化数组元素的问题,具体见https://www.cnblogs.com/chouxianyu/p/11322984.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// PAT BasicLevel 1032
// https://pintia.cn/problem-sets/994805260223102976/problems/994805289432236032

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
// n个参赛者
int n;
cin >> n;

// 最多n个学校
int* scores=new int[n+1];

// 各学校(下标为0的学校是无效的学校)分数初始化为-1,因为是百分制,有可能所以参赛者都是零分且是同一个学校
memset(scores, -1, sizeof(int) * (n + 1));

// 统计n个学校分数
int index,score;
for(int i=0;i<n;i++){
cin >> index >> score;
scores[index] += score;
}

// 有效的学校最低分数是0,所以遍历后结果肯定不会是下标为0的那个学校
int maxIndex=0,maxScore=scores[maxIndex];
for(int i=1;i<n+1;++i){
// 处理-1
scores[i]++;

// 更新最大值
if (scores[i] > maxScore){
maxScore = scores[i];
maxIndex = i;
}
}

// 输出结果
cout << maxIndex << ' ' << maxScore;

// 释放内存
delete[] scores;

//system("pause");
return 0;
}

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!