USACO Silver 2016 December - Cities & States

Author: Benjamin Qi

Official Editorial (Java)

Java

C++

As the editorial mentions, we can store the number of times a given four-letter string appears in a map.

Time Complexity: O(NlogN)\mathcal{O}(N\log N) with map, O(N)\mathcal{O}(N) with unordered_map.

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using db = double;
using str = string; // yay python!
using pi = pair<int,int>;
using pl = pair<ll,ll>;

A faster solution is to convert each string into an integer in the range [0,264)[0,26^4) and use an array instead of a map.

Time Complexity: O(N)\mathcal{O}(N)

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using db = double;
using str = string; // yay python!
using pi = pair<int,int>;
using pl = pair<ll,ll>;

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!