HDOJ 1166 敌兵布阵

题意:给出每个位置的初始值,有三种操作,add,sub,query;add表示在第i个位置增加k,sub表示在第i个位置减少k,query表示求出第i到k个位置的所有数的和。

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

思路:裸的树状数组,单点更新,区间查询。线段树也可以做,不过无论是时间复杂度,空间复杂度,编码复杂度,都是树状数组更方便。

注意点:无。


以下为AC代码:

Run IDSubmit TimeJudge StatusPro.IDExe.TimeExe.MemoryCode Len.LanguageAuthor
125643962014-12-22 20:49:22Accepted1166748MS1344K1346 BC++luminous11

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

int n;
int num[50005];

void add( int x, int k )
{
    for ( ; x <= n; x += ( x & -x ) )
        num[x] += k;
}

int query ( int x )
{
    int ans = 0;
    for ( ; x > 0; x -= ( x & -x ) )
        ans += num[x];
    return ans;
}

int main()
{
    ios::sync_with_stdio ( false );
    int ncase;
    cin >> ncase;
    for ( int t = 1; t <= ncase; t ++ )
    {
        int l, r;
        memset ( num, 0, sizeof ( num ) );
        getchar();
        cin >> n;
        int tmp;
        for ( int i = 1; i <= n; i ++ )
        {
            cin >> tmp;
            add ( i, tmp );
        }
        cout << "Case " << t << ":" << endl;
        char ch[100];
        while ( cin >> ch )
        {
            if ( ch[0] == 'E' )break;
            cin >> l >> r;
            if ( ch[0] == 'Q' )
                cout << query( r ) - query ( l - 1 ) << endl;
            else if ( ch[0] == 'A' )
                add ( l, r );
            else if ( ch[0] == 'S' )
                add ( l, -r );
            getchar();
        }
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值