C++代码:查找编程竞赛后学生的排名


假设我们有一个包含n个元素的数组A。在一个编程竞赛中,共有n名学生参加,在比赛开始之前,每个学生都有一定的正整数评分(整数)。A[i]表示第i个学生的评分。比赛结束后,每个学生都将获得一个正整数名次。我们期望学生根据他们的评分排名。如果学生A的评分严格低于学生B,则A的排名将严格高于B。我们需要找到比赛结束后的排名。

因此,如果输入类似于A = [3, 5, 3, 4, 5],则输出将是[4, 1, 4, 3, 1],因为第2和第5个学生以最高评分共享第一名,第4个学生接下来获得第三名,第1和第3个学生最后共享第四名。

步骤

为了解决这个问题,我们将遵循以下步骤:

n := size of A for initialize i := 0, when i < n, update (increase i by 1), do: d := 1 for initialize j := 0, when j < n, update (increase j by 1), do: if A[j] > A[i], then: (increase d by 1) cout << d << ", "

示例

让我们看看下面的实现,以便更好地理解:

Open Compiler
#include <bits/stdc++.h> using namespace std; void solve(vector<int> A){ int n = A.size(); for (int i = 0; i < n; i++){ int d = 1; for (int j = 0; j < n; j++){ if (A[j] > A[i]) d++; } cout << d << ", "; } } int main(){ vector<int> A = { 3, 5, 3, 4, 5 }; solve(A); }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输入

{ 3, 5, 3, 4, 5 }

输出

4, 1, 4, 3, 1,

更新于:2022年3月15日

浏览量:288

开启你的职业生涯

完成课程获得认证

开始学习
广告