A Walk Through Brooklyn
Time limit2sMemory limit1024 MB
Pick a walk from the north edge to the south edge along house boundaries that splits the grid area into two parts with the smallest difference.
- Level
Hard9 of 10
- Topics
- Graph, Dynamic programming, Implementation
- Solved
- No attempts yet
Problem
Miles Morales walks through Brooklyn. Seen from a bird's eye view, Brooklyn looks like a grid field of cells, whose vertical sides are parallel to the north-south direction. Each cell belongs to a house. Houses are regions of cells connected by sides. Every unit segment on the boundary of the field or between two different houses is a road. Miles starts his walk on the northern boundary of Brooklyn. He moves along the roads to the west, east, or south. He never walks along the same road twice, even in opposite directions. He keeps walking until he reaches the southern boundary of Brooklyn. Miles's route divides Brooklyn into two parts: the part east of the route and the part west of it. Miles wants to know the minimum possible difference between the areas of these two parts. Help him answer this question.
Input
The first line contains two integers and , the size of the field ().
The next lines each contain uppercase Latin letters that describe Brooklyn. Side-connected cells with the same letter form one house.
Output
Print one integer, the minimum possible difference between the areas of the two parts that Miles's route divides Brooklyn into.
Hint
The picture for the first test. Houses are shapes of different colors, and roads are the black segments. A possible route of Miles is drawn as a red dashed line.

The picture for the second test.
