AcWing 796. 子矩阵的和
原题链接
简单
作者:
一个不正经的程序员
,
2024-11-21 21:39:57
,
所有人可见
,
阅读 1
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const input = [];
readline.on('line', (line) => {
input.push(line);
});
readline.on('close', () => {
// 解析矩阵的尺寸和查询数
const [n, m, q] = input[0].split(' ').map(Number);
// 读取矩阵
const matrix = [];
for (let i = 1; i <= n; i++) {
matrix.push(input[i].split(' ').map(Number));
}
// 构建二维前缀和数组
const prefixSum = Array(n + 1).fill(0).map(() => Array(m + 1).fill(0));
// 计算前缀和
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
prefixSum[i][j] = matrix[i - 1][j - 1]
+ prefixSum[i - 1][j]
+ prefixSum[i][j - 1]
- prefixSum[i - 1][j - 1];
}
}
// 处理查询
for (let i = n + 1; i < n + 1 + q; i++) {
const [x1, y1, x2, y2] = input[i].split(' ').map(Number);
// 计算子矩阵的和
const result = prefixSum[x2][y2]
- prefixSum[x1 - 1][y2]
- prefixSum[x2][y1 - 1]
+ prefixSum[x1 - 1][y1 - 1];
console.log(result);
}
});