P3941 入阵曲
Description
链接
给出 的矩阵, 矩阵中的每个数都是不超过 的正整数, 求有多少矩阵的和满足
Solution
枚举矩阵人尽皆知, 就不说了
- 枚举行的上界和下界
- 将上界到下界的所有元素压成一行,
从左向右扫, 假如当前前缀和为, 则如果前面的前缀和有的, 则两个前缀之间的数一定满足 mod
复杂度
Attention
注意计数数组的清0方法, 使用队列实现
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;
}