【PAT乙级】1047 编程团体赛 (20 分) C语言实现
编程团体赛的规则为:每个参赛队由若干队员组成;所有队员独立比赛;参赛队的成绩为所有队员的成绩和;成绩最高的队获胜。
现给定所有队员的比赛成绩,请你编写程序找出冠军队。
输入格式:
输入第一行给出一个正整数 N(≤10^4),即所有参赛队员总数。随后 N 行,每行给出一位队员的成绩,格式为:队伍编号-队员编号 成绩,其中队伍编号为 1 到 1000 的正整数,队员编号为 1 到 10 的正整数,成绩为 0 到 100 的整数。
输出格式:
在一行中输出冠军队的编号和总成绩,其间以一个空格分隔。注意:题目保证冠军队是唯一的。
输入样例:
6
3-10 99
11-5 87
102-1 0
102-3 100
11-9 89
3-2 61
输出样例:
11 176
代码实现:
- 解法一:
#include <stdio.h>
#include <string.h> // 使用初始化函数 memset
#include <stdlib.h> // 使用 atoi 函数,把字符串转换成整型数的一个函数
// 获取队伍名
int getTeamName(char *arr);
// 获取分数
int getScore(char *arr);
int main() {
int n;
if (scanf("%d", &n) == 1) {
int team[1001];
// 给数组附初始值
memset(team, -1, sizeof(team));
char arr[20] = {'\0'};
for (int i = 0; i < n; i++) {
getchar();
scanf("%[^\n]", arr);
int team_name = getTeamName(arr);
int score = getScore(arr);
if (team[team_name] == -1) {
team[team_name] = score;
} else {
team[team_name] += score;
}
}
// 打印输出
int champion = 0;
int champion_score = team[0];
for (int i = 1; i < 1001; i++) {
if (champion_score < team[i]) {
champion = i;
champion_score = team[i];
}
}
printf("%d %d\n", champion, champion_score);
}
return 0;
}
int getTeamName(char *arr) {
char team_name[10] = {'\0'};
int i = 0;
while (arr[i] != '-') {
team_name[i] = arr[i];
i++;
}
return atoi(team_name);
}
int getScore(char *arr) {
char score[10] = {'\0'};
// 忽略队员编号
int i = 0;
while (arr[i] != ' ') {
i++;
}
int j = 0;
while (arr[i] != '\0') {
score[j++] = arr[i++];
}
return atoi(score);
}
- 解法二:
#include <stdio.h>
#include <string.h> // 使用初始化函数 memset
int main() {
int n;
if (scanf("%d", &n) == 1) {
int team[1001];
// 给数组附初始值
memset(team, -1, sizeof(team));
int teamname, teammate, score;
for (int i = 0; i < n; i++) {
if (scanf("%d-%d %d", &teamname, &teammate, &score) == 3) {
if (team[teamname] == -1) {
team[teamname] = score;
} else {
team[teamname] += score;
}
}
}
// 打印输出
int champion = 0;
int champion_score = team[0];
for (int i = 1; i < 1001; i++) {
if (champion_score < team[i]) {
champion = i;
champion_score = team[i];
}
}
printf("%d %d\n", champion, champion_score);
}
return 0;
}