`
java-mans
  • 浏览: 11340639 次
文章分类
社区版块
存档分类
最新评论

POJ 1195 Mobile phones 二维树状数组

 
阅读更多

二维树状数组是为了矩阵的某个区域快速求和,其原理是一样的,可以对每一维都是用树状数组的原理求和,就相当于把二维数组当做一个一维数组,每个元素又都是一维数组,比如,里面的那个循环是把行的和求出来,外面的循环则是把这些和的和求出来,从而能求解矩阵某个区域的和。

这道题需要注意的就是下标是从0开始的。

/*
ID: sdj22251
PROG: inflate
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define MAXN 1100
#define INF 1000000000
#define eps 1e-7
#define PI 3.1415926535898
using namespace std;
int a[MAXN][MAXN];
int n;
int lowbit(int x)
{
    return x & -x;
}
void modify(int x, int y, int val)
{
    for(int i = x; i <= n; i += lowbit(i))
        for(int j = y; j <= n; j += lowbit(j))
            a[i][j] += val;
}
int getsum(int x, int y)
{
    int sum = 0;
    for(int i = x; i > 0; i -= lowbit(i))
        for(int j = y; j > 0; j -= lowbit(j))
            sum += a[i][j];
    return sum;
}
int main()
{
    int con;
    int x1, x2, y1, y2, v;
    scanf("%d%d", &con, &n);
    n++;
    while(scanf("%d", &con) != EOF)
    {
        if(con == 3) break;
        if(con == 1)
        {
            scanf("%d%d%d", &x1, &y1, &v);
            x1++, y1++;
            modify(x1, y1, v);
        }
        else if(con == 2)
        {
            scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
            x1++, y1++, x2++, y2++;
            printf("%d\n", getsum(x2, y2) + getsum(x1 - 1, y1 - 1) - getsum(x1 - 1, y2) - getsum(x2, y1 - 1));
        }
    }
    return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics