B - Ranking with Ties Editorial by en_translator
We will explain two solutions.
Solution 1: implement just as instructed in the problem statement
We may implement the process of determining the ranks just as described in the problem statement. The following implementation is needed:
- Repeat a specific operation until a certain condition is met: realized with a loop structure (
for
statement orwhile
statement). - Find the maximum score among those with undetermined scores: one can manage whether each person’s rank is determined or not in an array, so that the sought maximum score can be found using a loop.
Solution 2: rephrase the procedure
At a glance, the rank decision algorithm described in the problem statement seems complex and puzzling, but it can be in fact simply put as follows:
- Person \(i\)’s rank is the number of people with strictly higher scores, plus one.
Using this alternative form facilitates the implementation than directly coding the process described in the problem statement.
In general, when you encounter a problem with such a complex process, it is good idea to take a close look at how it proceeds using concrete examples, and seek for a simpler way to rephrase it. (Of course, such a substitution is not always possible.)
The following is sample code in C++ and Python for solutions 1 and 2.
Sample code 1 (C++):
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> p(n);
for (int i = 0; i < n; i++) {
cin >> p[i];
}
vector<int> rank(n);
int r = 1;
while (true) {
int x = 0;
for (int i = 0; i < n; i++) {
if (rank[i]) continue;
x = max(x, p[i]);
}
if (!x) break;
int k = 0;
for (int i = 0; i < n; i++) {
if (p[i] == x) {
rank[i] = r;
k++;
}
}
r += k;
}
for (int i = 0; i < n; i++) {
cout << rank[i] << '\n';
}
}
Sample code 1 (Python):
n = int(input())
p = list(map(int, input().split()))
rank = [0 for i in range(n)]
r = 1
while True:
x = 0
for i in range(n):
if rank[i] != 0:
continue
x = max(x, p[i])
if x == 0:
break
k = 0
for i in range(n):
if p[i] == x:
rank[i] = r
k += 1
r += k
for i in range(n):
print(rank[i])
Sample code 2 (C++):
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> p(n);
for (int i = 0; i < n; i++) {
cin >> p[i];
}
for (int i = 0; i < n; i++) {
int rank = 1;
for (int j = 0; j < n; j++) {
if (p[j] > p[i]) rank++;
}
cout << rank << '\n';
}
}
Sample code 2 (Python):
n = int(input())
p = list(map(int, input().split()))
for i in range(n):
rank = 1
for j in range(n):
if p[j] > p[i]:
rank += 1
print(rank)
posted:
last update: