xjoi数组-好学生

题目描述:
告诉你每个学生在每门功课上的成绩,现在定义好学生为:至少在某一门功课上是所有学生中最优秀的。

问,有多少个好学生

输入格式:
第一行输入两个整数n,m,表示学生的数量与功课的数量
接下来n行输入一个数字矩阵,每行m个数字字符。

输出格式:
输出一个整数

样例输入:
3 5
91728
11828
11111
样例输出:
3

约定:
1<=n,m<=100


#include <iostream>
#include <vector>

using namespace std;

int countGoodStudents(vector<vector<int>>& scores) {
    int n = scores.size();
    int m = scores[0].size();

    int count = 0;
    for (int i = 0; i < n; i++) {
        bool goodStudent = true;
        for (int j = 0; j < m; j++) {
            int score = scores[i][j];
            bool isBest = true;
            for (int k = 0; k < n; k++) {
                if (scores[k][j] > score) {
                    isBest = false;
                    break;
                }
            }
            if (isBest) {
                goodStudent = true;
                break;
            }
        }
        if (goodStudent) {
            count++;
        }
    }
    return count;
}

int main() {
    int n, m;
    cin >> n >> m;

    vector<vector<int>> scores(n, vector<int>(m));
    for (int i = 0; i < n; i++) {
        string scoreLine;
        cin >> scoreLine;
        for (int j = 0; j < m; j++) {
            scores[i][j] = scoreLine[j] - '0';  // 将字符转换为整数
        }
    }

    int goodStudents = countGoodStudents(scores);
    cout << goodStudents << endl;

    return 0;
}

可以参考一下,看看有没有帮助

【以下回答由 GPT 生成】

问题可以转化为找到每一列的最大值,并统计有多少列上的最大值是唯一的。

解决方案如下:

  1. 首先,读取输入的n和m,并定义一个二维数组score用来存放学生的成绩。
n, m = map(int, input().split())
score = []
  1. 接下来,使用一个循环,读取n行输入的数字矩阵,并将每一行转换成一个列表后添加到score中。
for _ in range(n):
    row = list(map(int, input().strip()))
    score.append(row)
  1. 然后,定义变量count用来统计好学生的数量,初始值为0。
count = 0
  1. 接下来,使用两个循环,遍历每一列和每一行,找到每一列的最大值,并判断该最大值是否唯一。
for j in range(m):
    max_value = score[0][j]
    max_count = 1
    for i in range(1, n):
        if score[i][j] > max_value:
            max_value = score[i][j]
            max_count = 1
        elif score[i][j] == max_value:
            max_count += 1
    if max_count == 1:
        count += 1
  1. 最后,输出统计好学生的数量。
print(count)

完整代码如下:

n, m = map(int, input().split())
score = []
for _ in range(n):
    row = list(map(int, input().strip()))
    score.append(row)

count = 0
for j in range(m):
    max_value = score[0][j]
    max_count = 1
    for i in range(1, n):
        if score[i][j] > max_value:
            max_value = score[i][j]
            max_count = 1
        elif score[i][j] == max_value:
            max_count += 1
    if max_count == 1:
        count += 1

print(count)

该解决方案的时间复杂度为O(nm),空间复杂度为O(nm)。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^