Partitioning the Farm
Time limit1sMemory limit128 MB
Place at most K full-width horizontal or vertical fences on an N x N grid to minimize the largest connected group of cows.
- Level
Hard8 of 10
- Topics
- Brute force, Binary search, Prefix sum, Bit manipulation
- Solved
- No attempts yet
Problem
Farmer John's farm is divided into an square grid of pastures (). Right now there is a fence only around the outside of the farm, so cows can move freely from pasture to pasture.
Farmer John has decided to build fences to separate the cows from one another. Because of zoning laws, each fence must be a horizontal or vertical line that runs all the way across the farm, and a fence cannot cut through a pasture (so every fence lies between two adjacent rows or between two adjacent columns). Farmer John can afford to build at most fences ().
The size of a group is the total number of cows in it, and two cows belong to the same group if one can reach the other without crossing any fence. Farmer John wants to place the fences so as to minimize the size of the largest resulting group. Given the current number of cows in each pasture, compute the size of the largest group of cows when the fences are built optimally.
Input
- Line 1: Two integers, and .
- Lines 2 to : Each line contains integers describing the number of cows in each pasture of one row of the farm (each pasture holds between and cows).
Output
- Line 1: The minimum possible size of the largest group of cows.
Hint
Explanation of the sample
Farmer John should build one fence between columns 2 and 3 and one fence between rows 2 and 3. This creates 4 groups of 4 cows each, so the largest group has size .