树状数组test

这是按照自己理解写的一个测试代码。。。

简单易懂

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

const int maxn = 10005;

int a[ maxn ],c[ maxn ];

int lowbit( int i ){

	return i&(-i);

}

int sum( int i ){

	int s=0;

	while( i>0 ){

		s+=c[ i ];

		i-=lowbit( i );

	}

	return s;

}

void update( int i,int new_val,int pre_val ){

	while( i<maxn ){

		c[ i ]-=pre_val;

		c[ i ]+=new_val;

		i+=lowbit( i );

	}

}

void test( int n ){

	printf("\n\n");

	for( int i=1;i<=n;i++ )

		printf("%d ",a[ i ]);

	printf("\n\n");

}

int main(){

	int n;

	while( scanf("%d",&n)==1 ){

		memset( a,0,sizeof( a ) );

		memset( c,0,sizeof( c ) );

		for( int i=1;i<=n;i++ ){

			scanf("%d",&a[ i ]);

			update( i,a[ i ],0 );

		}

		int m;

		scanf("%d",&m);

		while( m-- ){

			int op;

			scanf("%d",&op);

			if( op==1 ){

				int pos,new_val;

				scanf("%d%d",&pos,&new_val);

				test( n );

				update( pos,new_val,a[ pos ] );

				a[ pos ]=new_val;

				test( n );//输出1 到 n 

			}//change a[ pos ] to new_val

			else if( op==2 ){

				int from,to;

				scanf("%d%d",&from,&to);

				if( from>1 )

					printf("from %d to %d:%d\n",from,to,sum( to )-sum( from-1 ) );

				else

					printf("from %d to %d:%d\n",from,to,sum( to ) );

			}//询问从from到to的总和

		}

	}

	return 0;

}

		

 

你可能感兴趣的:(test)