使用分数表查找学生排名的 C++ 代码
假设我们有一个大小为 n x 4 的二维数组。考虑有 n 个学生,他们的 id 从 0 到 n-1 开始。他们每个人都有四门成绩:英语、地理、数学和历史。在该表格中,学生将按分数总和降序排列。如果两个或更多学生的分数总和相同,则这些学生按 id 升序排列。我们必须找到 id 为 0 的学生的 id。
因此,如果输入类似
100 | 98 | 100 | 100 |
100 | 100 | 100 | 100 |
90 | 99 | 90 | 100 |
100 | 98 | 60 | 99 |
则输出将为 2
步骤
为此,我们将按照以下步骤操作 -
n := size of table r := 1 p := table[0, 0] + table[0, 1] + table[0, 2] + table[0, 3] for initialize i := 1, when i < n, update (increase i by 1), do: if table[i, 0] + table[i, 1] + table[i, 2] + table[i, 3] > p, then: (increase r by 1) return r
示例
让我们查看以下实现,以加深理解 -
#include <bits/stdc++.h> using namespace std; int solve(vector<vector<int>> table){ int n = table.size(); int r = 1; int p = table[0][0] + table[0][1] + table[0][2] + table[0][3]; for (int i = 1; i < n; i++){ if (table[i][0] + table[i][1] + table[i][2] + table[i][3] > p) r++; } return r; } int main(){ vector<vector<int>> table = { { 100, 98, 100, 100 }, { 100, 100, 100, 100 }, { 90, 99, 90, 100 }, { 100, 98, 60, 99 } }; cout << solve(table) << endl; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输入
{ { 100, 98, 100, 100 }, { 100, 100, 100, 100 }, { 90, 99, 90, 100 }, { 100, 98, 60, 99 } }
输出
2
广告