【 IndiaHacks 2nd Elimination 2017】A. Binary Blocks(DP 思维)

A. Binary Blocks
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given an image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into kby k blocks. If n and m are not divisible by k, the image is padded with only zeros on the right and bottom so that they are divisible by k. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some k. More specifically, the steps are to first choose k, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this k. The image must be compressible in that state.

Input

The first line of input will contain two integers n, m (2 ≤ n, m ≤ 2 500), the dimensions of the image.

The next n lines of input will contain a binary string with exactly m characters, representing the image.

Output

Print a single integer, the minimum number of pixels needed to toggle to make the image compressible.

Example
input
3 5
00100
10110
11001
output
5
Note

We first choose k = 2.

The image is padded as follows:

001000
101100
110010
000000

We can toggle the image to look as follows:

001100
001100
000000
000000

We can see that this image is compressible for k = 2.


一开始大家想的都是暴力……后来算了一下发现根本不可行。还剩一个小时突然想起CF835的C题,感觉有点像。最后还是没敲出来,看了大佬的题解觉得自己太蠢了。

#include<bits/stdc++.h>
#define INF 0X3f3f3f3f
using namespace std;
const int MAXN = 2500+10;
char s[MAXN];
int n,m,j,i,k,a[MAXN],sum[MAXN][MAXN],x,y,ans=INF,res,tmp;
int main(void)
{
    scanf("%d%d",&n,&m);
    for(i = 1; i <= n; ++i)
        for(scanf("%s",s+1),j = 1; j <= m; ++j)
            sum[i][j] = sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+(s[j]=='1');
    for(k = 2; k <= max(n,m); ++k)
    {
        res = 0;
        for(i = k; i-k <= n; i+=k)
        {
            for(j = k; j-k <= m; j+=k)
            {
                x = min(n,i);  y = min(m,j);
                tmp = sum[x][y]-sum[i-k][y]-sum[x][j-k]+sum[i-k][j-k];
                res += min(tmp,k*k-tmp);
            }
        }
        ans = min(ans,res);
    }
    printf("%d\n",ans);
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值