HDU4267(樹狀數組)

題目大意:給一數列,有兩種操作,一種是在[a, b]內,對(i - a) % k == 0 的所有值加上c,另一種是查詢某個位置的值。

思路:由於本題k<=10,所以一共有1+2+3+...+10 = 55種餘數,所以可以開55個樹狀數組,用sum[k][mod][i]表示i % k == mod,便於在詢問的時候減少循環次數。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
const int maxn = 55555;
int aa[maxn];
int sum[11][11][maxn];
int n, q;
int lowbit(int x)
{
    return x & (-x);
}
void modify(int pos, int k, int mod, int val)
{
    for(int i=pos; i>0; i-=lowbit(i))
    {
        sum[k][mod][i] += val;
    }
}
int query(int pos, int k)
{
    int res = 0;
    for(int i=pos; i<=n; i+=lowbit(i))
    {
        for(int j=1; j<=10; j++)
            res += sum[j][k%j][i];
    }
    return res;
}
int main()
{
    while(scanf("%d", &n) != EOF)
    {
        for(int i=1; i<=n; i++)
        {
            scanf("%d", &aa[i]);
        }
        memset(sum, 0, sizeof sum);
        scanf("%d", &q);
        while(q--)
        {
            int op;
            int a, b, k, c;
            scanf("%d", &op);
            if(op == 1)
            {
                scanf("%d%d%d%d", &a, &b, &k, &c);
                modify(b, k, a%k, c);
                modify(a-1, k, a%k, c*(-1));
            }
            else
            {
                scanf("%d", &a);
                int ans = query(a, a);
                printf("%d\n", ans + aa[a]);
            }
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章