Reiks的技术博客

C/C++/STL/Algorithm/D3D
posts - 17, comments - 2, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

树状数组

Posted on 2009-08-28 10:35 reiks 阅读(306) 评论(0)  编辑 收藏 引用 所属分类: 算法与数据结构
#include <stdio.h>
#include 
<memory.h>
#define N 1000

class treearray
{
       
public:
       
int c[N],n;
       
void clear()
       
{
             memset(
this,0,sizeof(*this));
       }

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

       
void change(int i,int d)
       
{
             
for (;i<=n;i+=lowbit(i))       c[i]+=d;
       }

       
int getsum(int i)
       
{
             
int t;
             
for (t=0;i>0;i-=lowbit(i))       t+=c[i];
             
return t;
       }

}
t;

main()
//附一个测试程序
{
       
int i,x;
       t.clear();
       scanf(
"%d",&t.n);
       
for (i=1;i<=t.n;i++)
       
{
             scanf(
"%d",&x);
             t.change(i,x);
       }

       
for (;scanf("%d",&x),x;)       printf("%d\n",t.getsum(x));
       
return 0;
}



只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理