您的位置:首页 > 其它

树状数组

2012-11-21 21:39 120 查看
树状数组主要理解三个函数Lowbit(),pluse(),sum();lowbit()是他们三个当中最难理解的,一切都靠网络,呵呵,另外有意外收获了输入开挂

先说下Lowbit()人如其名,指的就是,这个数用二进制表示,最后一个1所代表的数

Pluse()也就是从底向上跟新了,他与他的父亲节点下表差为Lowbit();

sum()也就是求和,很easy,sum(pos)=C[Lowbit(pos)]+sum(pos-Lowbit(pos));

表示的是从1到pos数组C的和

这是南阳理工的士兵杀敌二

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define K 1000050
long long c[K];
long long Lowbit(long long t)
{
	return t&(t^(t-1));
}
long long Sum(long long end)
{
	long long sum=0;
	while(end>0)
	{
		sum+=c[end];
		end-=Lowbit(end);
	
	}
	return sum;

}
void Plus(long long pos,long long num,long long n)
{
	while(pos<=n)
	{
		c[pos]+=num;
		pos+=Lowbit(pos);
	
	}

}
/*             输入外挂
使用方法:
int a;
a = Scan(); 
*/
int Scan()
{
    long long res = 0 , ch ;
    while( !( ( ch = getchar() ) >= '0' && ch <= '9' ) )
    {
        if( ch == EOF )  return 1 << 30 ;
    }
    res = ch - '0' ;
    while( ( ch = getchar() ) >= '0' && ch <= '9' )
        res = res * 10 + ( ch - '0' ) ;
    return res ;
}

int main()
{
	long long N,M,i,tem,s,t;
	char str1[]="QUERY",str2[]="ADD",str[20];
	scanf("%lld%lld",&N,&M);
	for(i=1;i<=N;i++)
		{
			tem = Scan(); 
		   Plus(i,tem,N);
	    }
	/*for(i=1;i<=N;i++)
		cout<<"c["<<i<<"]="<<c[i]<<endl;*/
	for(i=0;i<M;i++)
	{

		scanf("%s%lld%lld",str,&s,&t);
		//cout<<"str[]="<<str<<endl;
		int ma;
		ma=strlen(str);
		if(ma==5)
		  cout<<Sum(t)-Sum(s-1)<<endl;
		if(ma==3)
			Plus(s,t,N);
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: