H. Hard Demon Problem
H. Hard Demon Problem
Swing is opening a pancake factory! A good pancake factory must be good at flattening things, so Swing is going to test his new equipment on 2D matrices.
Swing is given an matrix containing positive integers. He has queries to ask you.
For each query, he gives you four integers , , , and asks you to flatten the submatrix bounded by and into an array . Formally, .
The following image depicts the flattening of a submatrix bounded by the red dotted lines. The orange arrows denote the direction that the elements of the submatrix are appended to the back of , and is shown at the bottom of the image.
Afterwards, he asks you for the value of (sum of over all ).
Input
The first line contains an integer () — the number of test cases.
The first line of each test contains two integers and () — the length of and the number of queries.
The following lines contain integers each, the 'th of which contains ().
The following lines contain four integers , , , and () — the bounds of the query.
It is guaranteed that the sum of over all test cases does not exceed and the sum of over all test cases does not exceed .
Output
For each test case, output the results of the queries on a new line.
Example
Input
2
4 3
1 5 2 4
4 9 5 3
4 5 2 3
1 5 5 2
1 1 4 4
2 2 3 3
1 2 4 3
3 3
1 2 3
4 5 6
7 8 9
1 1 1 3
1 3 3 3
2 2 2 2
Output
500 42 168
14 42 5
Note
In the second query of the first test case, . Therefore, the sum is .
解题思路
纯粹就是把累加转换成前缀和的表示形式然后推式子,关键是需要维护前缀和很多,且式子很复杂易推错。
先从简单的情况考虑,假设询问的是某一行,即 ,此时的结果为
记 ,,则有
现在考虑询问多行的情况,对于每一行,其实只需在上述结果的基础上再加上 ,以保证该行每个元素乘以的系数是正确的。
记 ,,,则有
记 ,则有
AC 代码如下,时间复杂度为 :
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2005;
LL r1[N][N], r2[N][N], c1[N][N], c2[N][N], c3[N][N];
void solve() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
int x;
cin >> x;
r1[i][j] = r1[i][j - 1] + x;
r2[i][j] = r2[i][j - 1] + j * x;
}
}
for (int j = 1; j <= n; j++) {
for (int i = 1; i <= n; i++) {
c1[i][j] = c1[i - 1][j] + r1[i][j];
c2[i][j] = c2[i - 1][j] + r2[i][j];
c3[i][j] = c3[i - 1][j] + i * r1[i][j];
}
}
while (m--) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
auto f = [&](LL c[][N]) {
return c[x2][y2] - c[x1 - 1][y2] - c[x2][y1 - 1] + c[x1 - 1][y1 - 1];
};
cout << (y2 - y1 + 1) * f(c3) + (1 - y1 - x1 * (y2 - y1 + 1)) * f(c1) + f(c2) << ' ';
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
参考资料
Codeforces Round 993 (Div. 4) Editorial:https://codeforces.com/blog/entry/137306
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/18616401
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
2023-12-19 D. Array Collapse