首页 > 技术文章 > NYOJ 116 士兵杀敌(二)(二叉索引树)

zyb993963526 2017-03-10 13:02 原文

http://acm.nyist.net/JudgeOnline/problem.php?pid=116

题意:

南将军手下有N个士兵,分别编号1到N,这些士兵的杀敌数都是已知的。

小工是南将军手下的军师,南将军经常想知道第m号到第n号士兵的总杀敌数,请你帮助小工来回答南将军吧。

南将军的某次询问之后士兵i可能又杀敌q人,之后南将军再询问的时候,需要考虑到新增的杀敌数。

 

思路:
典型的二叉索引树题目。

超时了许多次...因为用的是cin/cout输入输出流,换成scanf/printf之后就行了。

#include<iostream> 
#include<algorithm>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;

const int maxn = 1000000 + 5;

int n, m;
char str[6];
int c[maxn];

int lowbit(int x)
{
    return x&(-x);
}

int sum(int x)
{
    int num = 0;
    while (x>0)
    {
        num += c[x];
        x -= lowbit(x);
    }
    return num;
}

void add(int x, int d)
{
    while (x <= n)
    {
        c[x] += d;
        x += lowbit(x);
    }
}

int main()
{
    //freopen("D:\\txt.txt","r",stdin);
    scanf("%d%d", &n, &m);
    int x, y;
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &x);
        add(i, x);
    }
    for (int i = 0; i<m; i++)
    {
        scanf("%s%d%d", &str, &x, &y);
        if (str[0] == 'Q')
        {
            printf("%d\n", sum(y) - sum(x - 1));
        }
        else
        {
            add(x, y);
        }
    }
}

 

推荐阅读