hdu2642 Stars 二维树状数组

Problem:
给了一个矩阵,每次可以更新一个点的值,多次查询一个子矩阵的和。
Solution:
二维树状数组。

#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<vector>
#include<fstream>
#include<list>
#include <iomanip>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
#define ms(s) memset(s,0,sizeof(s))

const double PI = 3.141592653589;
const int INF = 0x3fffffff;

bool b[1010][1010];

long long BI_tree[1010][1010];
int nx, ny;

inline int lowbit(int x) {
    return x & -x;
}

void update(int x, int y, int v) {
    for(int i = x; i <= nx; i += lowbit(i))
        for(int j = y; j <= ny; j += lowbit(j))
            BI_tree[i][j] += v;
}

long long query(int x, int y) {
    long long ans = 0;
    for(int i = x; i > 0; i -= lowbit(i))
        for(int j = y; j > 0; j -= lowbit(j))
            ans += BI_tree[i][j];

    return ans;
}

int main() {
//        freopen("/Users/really/Documents/code/input","r",stdin);
    //    freopen("/Users/really/Documents/code/output","w",stdout);
    ios::sync_with_stdio(false);

    int m;
    cin >> m;
    nx = ny = 1001;
    while(m--) {
        char c;
        int x, y, x1, y1;

        cin >> c;
        if(c == 'B') {
            cin >> x >> y;
            x++;  y++;
            if(b[x][y] == false) {
                update(x, y, 1);
                b[x][y] = true;
            }
        }
        else if(c == 'D') {
            cin >> x >> y;
            x++;  y++;
            if(b[x][y] == true) {
                update(x, y, -1);
                b[x][y] = false;
            }
        }
        else if(c == 'Q') {
            cin >> x >> x1 >> y >> y1;
            x++;  y++;  x1++;  y1++;
            if(x1 < x)
                swap(x, x1);
            if(y1 < y)
                swap(y, y1);
            cout << query(x1, y1) - query(x-1, y1) - query(x1, y-1) + query(x-1, y-1) << endl;
        }

    }





    return 0;
}

猜你喜欢

转载自blog.csdn.net/cfarmerreally/article/details/78283437