POJ 1195 (Mobile phones) 二维树状数组

本文解析了 POJ 1195 的算法问题,介绍了如何使用二维树状数组解决矩阵中子矩阵和的计算问题。通过具体的 C++ 实现代码,展示了关键的数据结构和算法流程。

题目链接: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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值