Explanation
Let's represent each given pair as a 4-letter string (city prefix + state code) and use a map to track frequencies. For each string we check if its mirror exists and increase our count accordingly.
Implementation
Time Complexity:
from collections import defaultdictpairs = []with open("citystate.in") as read:for _ in range(int(read.readline())):city, state = read.readline().strip().split()city = city[:2] # We only care about the first two letters of the citypairs.append((city, state))
However, note that we can optimize this by converting each string into an integer and using an array instead of a map.
Time Complexity:
def index(s: str) -> int:ind = 0for c in s:ind = 26 * ind + (ord(c) - ord("A"))return indpairs = []with open("citystate.in") as read:for _ in range(int(read.readline())):
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!