HDU-4267-A Simple Problem with Integers-(树状数组)

树状数组区间更新查询
本文介绍了一种使用树状数组解决区间加法更新与单点查询问题的有效方法。通过示例输入输出展示了算法的工作流程,并提供了一段C++代码实现,该方法适用于处理大量更新与查询操作。

Problem Description
Let A1, A2, ... , AN be N elements. You need to deal with two kinds of operations. One type of operation is to add a given number to a few numbers in a given interval. The other is to query the value of some element.
 

Input
There are a lot of test cases. The first line contains an integer N. (1 <= N <= 50000) The second line contains N numbers which are the initial values of A1, A2, ... , AN. (-10,000,000 <= the initial value of Ai <= 10,000,000) The third line contains an integer Q. (1 <= Q <= 50000) Each of the following Q lines represents an operation. "1 a b k c" means adding c to each of Ai which satisfies a <= i <= b and (i - a) % k == 0. (1 <= a <= b <= N, 1 <= k <= 10, -1,000 <= c <= 1,000) "2 a" means querying the value of Aa. (1 <= a <= N)
 

Output
For each test case, output several lines to answer all query operations.
 

Sample Input
4 1 1 1 1 14 2 1 2 2 2 3 2 4 1 2 3 1 2 2 1 2 2 2 3 2 4 1 1 4 2 1 2 1 2 2 2 3 2 4
 

Sample Output
1 1 1 1 1 3 3 1 2 3 4 1

树状数组很有趣的一种做法

代码:

#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
typedef long long ll;
#define M 50005
int tree[M][11][11];
int p[M];
int n;
inline int lowbit(int i)
{
    return i&(-i);
}
void update(int x,int k,int mod,int v)
{
    while(x<=n)
    {
        tree[x][k][mod]+=v;
        x+=lowbit(x);
    }
}
int query(int x,int y)
{
    int ret=0,i;
    while(x>0)
    {
        for(i=1;i<=10;i++)
        {
            ret+=tree[x][i][y%i];
        }
        x-=lowbit(x);
    }
    return ret;
}
int main()
{
    int q,i,op,a,b,k,c;
    while(scanf("%d",&n)!=EOF)
    {
        for(i=1;i<=n;i++)
            scanf("%d",&p[i]);
        memset(tree,0,sizeof(tree));
        scanf("%d",&q);
        while(q--)
        {

            scanf("%d",&op);
            if(op==2)
            {
                scanf("%d",&a);
                int ans=query(a,a);
                printf("%d\n",p[a]+ans);
            }
            else
            {
                scanf("%d%d%d%d",&a,&b,&k,&c);
                update(a,k,a%k,c);
                update(b+1,k,a%k,-c);
            }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值