Cities and States
InterviewTime limit2sMemory limit512 MB
Given up to 200,000 cities with names and two-letter state codes, count unordered pairs whose first two name letters match the other city's state code and vice versa, with different states.
- Level
Medium5 of 10
- Topics
- Hash map, String, Combinatorics, Implementation
- Solved
- No attempts yet
Problem
To keep his cows entertained, Farmer John hung a large map of the USA on the wall of his barn. The cows spend hours staring at it, and they have started to notice curious patterns. For example, FLINT in Michigan and MIAMI in Florida have a special relationship. The first two letters of "FLINT" spell FL, the state code of MIAMI, and the first two letters of "MIAMI" spell MI, the state code of FLINT.
Two cities form a special pair when they have this property and belong to different states. City and city form a special pair when the first two letters of city 's name equal city 's state code, the first two letters of city 's name equal city 's state code, and the two state codes differ.
Count the special pairs. A pair has no order, so each pair of cities counts once.
Input
The first line contains (), the number of cities on the map.
Each of the next lines contains a city name and its state code, separated by a space. A city name is a string of 2 to 10 uppercase letters, and a state code is a string of 2 uppercase letters. A state code may be something like ZQ, which is not a real USA state. Several cities may share a name, but such cities belong to different states.
Output
Print the number of special pairs on one line.