公式

B - ABCDEFG 解説 by en_translator


The key to this problem is coming up with a simple implementation. If you had trouble with this problem, learn how to code fast.

There are several solutions. For example, it is not recommended to embed all answers to your code. There are \(7 \times 6 = 42\) possible pairs of \((p, q)\) given as the input. Do arithmetics by hand and embed the answers, and your code will be accepted.

# (Discouraged) sample code in Python
p, q = input().split()
if p == 'A' and q == 'B':
  print(3)
elif p == 'A' and q == 'C':
  print(4)
# and so on (enumerate 40 cases, and it will be AC (accepted))

But this is too cumbersome, let’s try to take the easy way out.

For simplicity, we label the vertices the integers starting from \(0\), instead of the alphabet. That is, points \(A, B, C, D, E, F\), and \(G\) are called points \(0, 1, 2, 3, 4, 5\), and \(6\) instead. (This can be easily implemented as a conversion from a character to the ASCII code. For example, in C++, it can be written as p - 'A' (where p is of char type), and in Python, ord(p[0]) - ord('A') (where p is of str type).) Then, for each \(n=0,1,2,3,4,5\), let us call the edge between point \(n\) and point \((n+1)\) “edge \(n\).” (For example, edge \(0\) is an edge of length \(3\) connecting point \(0\) and point \(1\).)

We explain the solution using these names. First, if \(p \gt q\), then “the distance between point \(p\) and point \(q\)” equals “the distance between point \(q\) and point \(p\),” so we can safely swap \(p\) and \(q\). By doing so, we can always assume that \(p \lt q\). If \(p \lt q\), the edges between point \(p\) and point \(q\) are “the edges numbered between \(p\) (inclusive) and \(q\) (exclusive)” by definition of the edge numbers. Thus, by summing up the length of the edges with a for loop, you can obtain the answer.

  • Sample code (C++)
#include <iostream>
using namespace std;

int main() {
  char p, q;
  cin >> p >> q;
  p -= 'A', q -= 'A';
  if(p > q) swap(p, q);
  int e[] = {3, 1, 4, 1, 5, 9}, ans = 0;
  for (int i = p; i < q; i++) ans += e[i];
  cout << ans << "\n";
}

Alternatively, you can correspond points \(A\) through \(G\) to some coordinates.
We briefly explain the approach. Consider point \(A\) a point with coordinate \(x=0\) on a number line; then the points \(B\) through \(G\) turn out to have coordinates \(x=3, 4, 8, 9, 14, 23\) by a simple calculation. Then, the distance between two points equals the absolute difference of their coordinates, so the answer can be found using abs function.

  • Sample code (C++)
#include <iostream>
using namespace std;

int main() {
  char p, q;
  cin >> p >> q;
  int e[] = {0, 3, 4, 8, 9, 14, 23};
  cout << abs(e[p - 'A'] - e[q - 'A']) << endl;
}

投稿日時:
最終更新: