Flipping Coins 3
InterviewTime limit5sMemory limit512 MB
Flip whole rows or columns of an N by M grid of coins to leave as few tails as possible, with N at most 20.
- Level
Medium6 of 10
- Topics
- Bit manipulation, Brute force, Greedy
- Solved
- No attempts yet
Problem
coins lie on a table in rows and columns. Each coin shows either heads (H) or tails (T).
One operation flips all coins of a single row, or all coins of a single column. You may repeat the operation as many times as you want.
For example, suppose the coins start like this.
HHT
THH
THT
Flipping every coin in the first column gives this.
THT
HHH
HHT
Flipping every coin in the first row after that gives this.
HTH
HHH
HHT
Two coins show tails in the last state. Starting from the first state, no sequence of operations leaves fewer than two coins showing tails.
Given the starting state of the coins, you want to repeat the operation until as few coins as possible show tails. Write a program that finds that minimum count.
Input
The first line contains and , separated by a space. (, )
Each of the next lines contains the starting state of one row. Each line is a string of length that lists the coins of that row from left to right, where H means heads and T means tails. There are no spaces between the characters.
Output
Print the minimum number of coins that can show tails.