Explanation
Since can go all the way up to , it would take much too long to iterate through all possible values of .
Instead, let's iterate through all possible values of and determine how many values of can be paired with it. To do this, we need to determine the number of elements in that are equal to for all . This can be done with a map and some pre-calculation.
Official Solution
The official solution goes through all values of instead, but it's pretty much the same idea.
Implementation
Time Complexity:
C++
#include <iostream>#include <map>#include <vector>using std::cout;using std::endl;using std::vector;int main() {int n;
Java
import java.io.*;import java.util.*;public class Main {public static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new InputStreamReader(System.in));read.readLine(); // n not neededint[] a = Arrays.stream(read.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Python
input() # n not neededa = [int(i) for i in input().split()]b = [int(i) for i in input().split()]c = [int(i) for i in input().split()]# Stores for each number in A how many times it appears in totalocc_a_num = {}for i in a:if i not in occ_a_num:occ_a_num[i] = 0
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!