P3941 入阵曲

入阵曲


Description

链接
给出 NMN*M的矩阵, 矩阵中的每个数都是不超过 KK 的正整数, 求有多少矩阵的和满足 mod K=0mod\ K = 0


Solution

O(N4)O(N^4)枚举矩阵人尽皆知, 就不说了

  1. 枚举行的上界和下界 O(N2)O(N^2)
  2. 将上界到下界的所有元素压成一行,
    从左向右扫, 假如当前前缀和为S1S_1, 则如果前面的前缀和有S2%K==S1%KS_2 \% K == S_1\%K的, 则两个前缀之间的数一定满足 mod K=0K=0
    复杂度 O(N3)O(N^3)

Attention

注意计数数组的清0方法, 使用队列实现 O(N)O(N)


Code

#include<bits/stdc++.h>
#define reg register

int read(){
        char c;
        int s = 0, flag = 1;
        while((c=getchar()) && !isdigit(c))
                if(c == '-'){ flag = -1, c = getchar(); break ; }
        while(isdigit(c)) s = s*10 + c-'0', c = getchar();
        return s * flag;
}

const int maxn = 405;

int N, M, K;
int A[maxn][maxn];
int sum[maxn][maxn];
bool Used[1000005];
int cnt[1000005];

int main(){
        freopen("rally.in", "r", stdin);
        freopen("rally.out", "w", stdout);
        N = read(), M = read(), K = read();
        for(reg int i = 1; i <= N; i ++)
                for(reg int j = 1; j <= M; j ++) A[i][j] = read()%K;
        for(reg int i = 1; i <= N; i ++)
                for(reg int j = 1; j <= M; j ++){
                        sum[i][j] = sum[i-1][j] + sum[i][j-1], sum[i][j] %= K;
                        sum[i][j] += A[i][j] - sum[i-1][j-1], sum[i][j] %= K;
                        sum[i][j] += K, sum[i][j] %= K;
                }
        long long Ans = 0;
        std::queue <int> Q;
        for(reg int top = 1; top <= N; top ++){
                for(reg int bot = top; bot <= N; bot ++){
                        for(reg int i = 1; i <= M; i ++){
                                int temp = sum[bot][i] - sum[top-1][i] + K;
                                temp %= K;
                                if(!temp) Ans ++;
                                Ans += cnt[temp];
                                cnt[temp] ++;
                                if(!Used[temp]) Q.push(temp);
                                Used[temp] = 1;
                        }
                        while(!Q.empty()) Used[Q.front()] = 0, cnt[Q.front()] = 0, Q.pop();
                }
        }
        printf("%lld\n", Ans);
        return 0;
}
posted @ 2019-04-28 15:47  XXX_Zbr  阅读(98)  评论(0编辑  收藏  举报