题目链接:http://poj.org/problem?id=1195
题意:给出一个矩阵及一些操作,求一些子矩阵的和。
思路:二维树状数组裸题,要注意下标从0开始,所以可以在输入后对每个坐标值都加1。
#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<iostream>
#include<set>
#include<map>
#include<cmath>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<bitset>
#include<algorithm>
#define fin(a) freopen("a.txt","r",stdin)
#define fout(a) freopen("a.txt","w",stdout)
typedef long long ll;
using namespace std;
const int maxn = 1050;
int a[maxn][maxn];
int lowbit(int x) {
return x & -x;
}
void add(int x, int y, int v, int n) {
for(int i = x; i <= n; i += lowbit(i))
for(int j = y; j <= n; j += lowbit(j))
a[i][j] += v;
}
ll sum(int x, int y) {
ll ans = 0;
for(int i = x; i >= 1; i -= lowbit(i))
for(int j = y; j >= 1; j -= lowbit(j))
ans += (ll)a[i][j];
return ans;
}
int main() {
int op, n;
scanf("%d%d", &op, &n);
while(scanf("%d", &op) && op != 3) {
if(op == 1) {
int x, y, z;
scanf("%d%d%d", &x, &y, &z); x++, y++;
add(x, y, z, n);
}
else {
int x1, y1, x2, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
x1++, y1++, x2++, y2++;
ll ans = sum(x2, y2) - sum(x1-1, y2) - sum(x2, y1-1) + sum(x1-1, y1-1);
printf("%lld\n", ans);
}
}
return 0;
}
本文解析了 POJ 1195 的算法问题,介绍了如何使用二维树状数组解决矩阵中子矩阵和的计算问题。通过具体的 C++ 实现代码,展示了关键的数据结构和算法流程。
244

被折叠的 条评论
为什么被折叠?



