树状数组

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#define N 20000
using namespace std;

int n;
double c[N];
double a[N];
int lowbit(int x)/**************求2的k次方**************/
{
    return (x&(-x));
}

void update(int pos,double num)/************更新a[],c[]*************/
{
    //int c[N];
    while(pos<=N)
    {
        c[pos]+=num;
        pos+=lowbit(pos);
    }
}

void init()//初始化
{
    memset(c,0,sizeof(c));
    for(int i=1; i<=n; i++)
    {
        cin>>a[i];
        update(i,a[i]);
    }
}

double sum(int x)/************求原数组a[]前x项的和****************/
{
    double summer=0;
    while(x>0)
    {
        summer+=c[x];
        x-=lowbit(x);
    }
    return summer;
}

char ch[111];
char ch1[111];
int main()
{
    freopen("C:\\Users\\Administrator\\Desktop\\in.txt" , "r" , stdin);
    int m;
    double y;
    int x;
    while(scanf("%d%d",&n,&m)==2)
    {
        init();
        getchar();
        while(m--)
        {
            gets(ch);
            sscanf(ch+4,"%d %lf",&x,&y);
            if(ch[1]=='e')
            {
                update(x,-(sum(x)-sum(x-1)));
                update(x,y);
                printf("%.0lf\n",sum(x));
            }
            else
            {
                printf("%.0lf\n",(sum((int)y)-sum(x-1)));
            }
        }
    }
    return 0;
}

自己学校 oj上的一个题,被坑了几次,开始没注意set:或者sum:后面没得空格是直接读得一个字符串,没有分离,后来分离了又被坑了2次,最后才发现是更新出了问题,多加了

题目连接 :http://211.67.33.161/JudgeOnline/showproblem?problem_id=1040

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值