HDU1166敌兵布阵 分块解法,分块练习

来源:互联网 发布:西南政法大学王洪 知乎 编辑:程序博客网 时间:2024/06/02 03:32

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1166

线段树,树状数组的模板题。用来入门分块。


#include<bits/stdc++.h>using namespace std;const int N = 5e4+10;int block;int n;int arr[N], sum[N];void update(int pos, int val){    arr[pos] += val;    sum[pos/block] += val;}int query(int s, int e){    int ans = 0;    for (int i = 0, l = 1, r = block-1; i <= n/block; i++, l = i*block, r += block){        int L = max(l, s);        int R = min(r, e);        if (L > R) continue;        if (L == l && R == r) ans += sum[i];        else for (int j = L; j <= R; j++)            ans += arr[j];    }    return ans;}int main(){    int T;    scanf("%d", &T);    for (int kase = 1; kase <= T; kase++){        memset(sum, 0, sizeof(sum));        scanf("%d", &n);        block = (int)sqrt(n);        for (int i = 1; i <= n; i++){            scanf("%d", &arr[i]);            sum[i/block] += arr[i];        }        printf("Case %d:\n", kase);        char opt[10];        while(scanf("%s", opt) == 1){            if (opt[0] == 'E') break;            if (opt[0] == 'Q'){                int s, e;                scanf("%d%d", &s, &e);                printf("%d\n", query(s, e));            }            else{                int pos, val;                scanf("%d %d", &pos, &val);                if (opt[0] == 'A') update(pos, val);                else update(pos, -val);            }        }    }    return 0;}


原创粉丝点击