Codeforces 838 A Binary Blocks(前缀和)

本文介绍了一种处理二进制矩阵的算法,通过使用前缀和思想来计算缩小后的矩阵中1的数量,适用于需要对大型二进制数据进行快速处理的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址
题意:给你个二进制矩阵,然后你按一定比例缩小,(一个范围内的相同的数字可以变为一个)比如:

001100
001100

可以转变为

010

如果不够倍数就在最右边和最下面补0

思路:就是前缀和的思想来,用前缀和来维护一个区域中1的个数(看下代码就懂了)

#include <iostream>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <cstdio>
#include <algorithm>
#define N 2510
#define LL __int64
#define lson l,mid,ans<<1
#define rson mid+1,r,ans<<1|1
#define getMid (l+r)>>1
#define movel ans<<1
#define mover ans<<1|1
using namespace std;
const LL mod = 1e9 + 7;
const double eps = 1e-9;
const int inf = 1 << 28;
char mapp[N][N];
int num[N][N];
int main() {
    cin.sync_with_stdio(false);
    int n, m;
    LL ans, cnt;
    while (cin >> n >> m) {
        memset(num, 0, sizeof(num));
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                cin >> mapp[i][j];
                num[i][j] = num[i][j - 1] + mapp[i][j] - '0';
            }
        }
        cnt = N*N;
        int len = max(n, m);
        for (int k = 2; k <= len; k++) {
            ans = 0;
            for (int i = 1; i <= n; i += k) {
                for (int j = 1; j <= m; j += k) {
                    LL sum = 0;
                    for (int l = i; l <= min(n, i + k - 1); l++) {
                        sum += num[l][min(m, j + k - 1)] - num[l][j - 1];
                    }
                    ans += min(k*k - sum, sum);
                }
            }
            cnt = min(ans, cnt);
        }
        cout << cnt << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值