import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines xyz = map(int,readline().split()) ST = read().decode().split() length = {a : x for a, x in zip('ABC', xyz)} def f(S0, T0, S1, T1): T0 = int(T0) T1 = int(T1) if S0 == S1: yield abs(T0 - T1) # 2つの交差点 L, R。計算の都合、交差点にも駅があるとしておく。 L0, R0 = T0, length[S0] + 1 - T0 L1, R1 = T1, length[S1] + 1 - T1 D = min(length.values()) + 1 # 両方を通る場合 yield L0 + R1 + D - 2 yield L1 + R0 + D - 2 # L のみを通る場合 yield L0 + L1 - 1 # R のみを通る場合 yield R0 + R1 - 1 answer = min(f(*ST)) print(answer)