[Codewars] Formula 1 Race

Formula 1 Race

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <string>
using namespace std;
pair<int, char> parse(const string& s, int& p) {
int id = 0;
while(p < s.length() and isdigit(s[p])) {
id = id * 10 + s[p] - '0';
p += 1;
}
p += 1;
char op = s[p];
p += 2;
return {id, op};
}
int at(map<int, int>& mp, int who) {
for(auto [k,v] : mp) if(v == who) return k;
return -1;
}
int ChampionRank(int champion,const std::string &events ) {
map<int, int> ord;
for(int i = 1; i <= 20; i++) ord[i] = i;
int p = 0;
while(p < events.length()) {
auto [who, op] = parse(events, p);
auto pos = at(ord, who);
if(op == 'I') ord.erase(pos);
else {
auto lb = ord.lower_bound(pos);
auto prv = prev(lb);
swap(prv->second, lb->second);
}
}
int res = 1;
for(auto [k,v] : ord) {
if(v == champion) return res;
res += 1;
}
return -1;
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/30/PS/Codewars/formula-1-race/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.