C - Piano 3 Editorial by en_translator
Mange the positions of left and right hands while inspecting the key to press for \(1,2,\dots,N\)-th press, and add the fatigue level of each move required.
In the sample code below, we prepare an array \(\text{pos}\) of length two, so that \(pos[0]\) and \(pos[1]\) manage the current position of left and right hands, respectively. Also, we set the initial positions of the hands to \(-1\), and do not add the fatigue level to the answer when moving a hand from \(-1\) to another key, so as to realize the action of “placing a hand at an appropriate position (the position of the first key to be pressed by the hand)” at the beginning of the performance.”
Sample code (C++):
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> pos = {-1, -1}; // 0: left, 1: right
int ans = 0;
for (int i = 0; i < n; i++) {
int a;
char s;
cin >> a >> s;
int hand = (s == 'R');
if (pos[hand] != -1) ans += abs(pos[hand] - a);
pos[hand] = a;
}
cout << ans << endl;
}
Sample code (Python) :
n = int(input())
pos = [-1, -1] # 0: left, 1: right
ans = 0
for i in range(n):
a, s = input().split()
a = int(a)
hand = (0 if s == 'L' else 1)
if pos[hand] != -1:
ans += abs(pos[hand] - a)
pos[hand] = a
print(ans)
posted:
last update: