#P12349. Maximum Coin Value
Maximum Coin Value
Maximum Coin Value
You are given a grid of coins with n rows and m columns. Each coin is either heads (H) or tails (T). For each coin, its value is defined as the square of the total number of adjacent coins (neighbors in the up, down, left, and right directions) that show the same face as itself. In other words, if a coin has k adjacent coins with the same face, its value is given by
You are allowed to perform any number of operations. In each operation, you may select any row and flip all the coins in that row (i.e. turn H into T and vice versa). Your task is to determine the maximum possible sum of the values of all coins after performing an arbitrary sequence of such operations.
Explanation
The horizontal adjacent relationships are invariant under a row flip since an entire row is flipped, leaving the relative equality of coins in that row unchanged. However, vertical adjacencies may change because the flipped state of one row compared with its neighboring row might yield more matching pairs. Note that each vertical edge contributes to the adjacent count for both coins it touches.
inputFormat
The first line contains two integers n and m — the number of rows and columns, respectively.
Then follow n lines, each containing a string of length m consisting only of the characters H and T, representing the initial state of the coins.
outputFormat
Output a single integer: the maximum possible sum of coin values that can be obtained after performing any number of row-flip operations.
sample
2 2
HT
TH
4