Problem 661
Minimum Domino Rotations For Equal Row
Medium · 20 pts · Array, Greedy
Problem
A row of N dominoes has a top half TOPS[i] and a bottom half BOTTOMS[i], each a number from 1 to 6. Rotating domino i swaps its two halves. Find the minimum number of rotations that makes all the top values equal, or all the bottom values equal, or print -1 if neither is possible. The common value must appear on the first domino, so only TOPS[0] and BOTTOMS[0] need to be tried as targets, each for the top row and for the bottom row.
Input
The first line contains N. The second line contains TOPS. The third line contains BOTTOMS.
Output
Print the minimum number of rotations, or -1.
Constraints
2 <= N <= 20000; 1 <= TOPS[i], BOTTOMS[i] <= 6
Example input
6 2 1 2 4 2 2 5 2 6 2 3 2
Example output
2
Explanation
With TOPS = 2 1 2 4 2 2 and BOTTOMS = 5 2 6 2 3 2, rotating the second and fourth dominoes puts a 2 on every top. That takes 2 rotations, and no target needs fewer.