树状数组(来自DK的神奇模版)

适合于快速的区间求和查询 较高的编程效率 优秀的算法....神一样的算法

 

 

以下是sample

 

 

#include <iostream>
using namespace std;

long c[2000];
long m;
//m就是数列有几个数,x是修改的数的下标,T是修改值
void update(int x,int t)
{
    
while(x<=m)
    {
        c[x]
+=t;
        x
+=x^(x&(x-1));
    }
}

int query(int x)
{
    
if (x==0)
    {
        
return 0;
    }
    
int sum=0;
    
while(x)
    {
        sum
+=c[x];
        x
&=x-1;
    }
return sum;
}

int main()
{
    
while(scanf("%ld",&m)!=EOF)
    {
        
long i;
        
for (i=1;i<=m;++i)
        {
            
long t;
            scanf(
"%ld",&t);
            update(i,t);
        }

        
long from,to;

        
if (from>to)
        {
            swap(from,to);
        }
        scanf(
"%ld %ld",&from,&to);
        printf(
"%ld\n",query(to)-query(from-1));
    }
    
return 0;
}
posted @ 2008-08-18 14:21  Hdu-Lost  阅读(342)  评论(0编辑  收藏  举报