Official

B - Distance Between Tokens Editorial by en_translator


Suppose that one piece is at the \(a\)-th row and the \(b\)-th column, and the other is at the \(c\)-th row and the \(d\)-th column. Then, the answer is \(|a - c| + |b - d|\). Therefore, all that left is to determine the square containing pieces, which can be implemented with for and if statements.

Sample code (C++):

#include <bits/stdc++.h> using namespace std; int main() { int h, w; cin >> h >> w; vector<pair<int, int>> pieces; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { char c; cin >> c; if (c == 'o') { pieces.emplace_back(i, j); } } } const auto& [a, b] = pieces[0]; const auto& [c, d] = pieces[1]; cout << abs(a - c) + abs(b - d) << '\n'; return 0; } 

Sample code (Python)

h, w = map(int, input().split()) s = [input() for _ in range(h)] pieces = [] for i in range(h): for j in range(w): if s[i][j] == 'o': pieces.append((i, j)) a, b = pieces[0] c, d = pieces[1] print(abs(a - c) + abs(b - d)) 

posted:
last update: