poj2352 Stars (第一道树状数组

来源:互联网 发布:rap 说唱教学软件 编辑:程序博客网 时间:2024/06/07 13:33

树状数组详解

  通过这道题,我对树状数组的理解:

  树状数组通过一种类似与二叉树的结构,使得任意连续段的求和操作的时间复杂度为O(log(N)).但是付出的代价是,对某一个元素做修改的时候的时间复杂度不再是O(1),而是O(log(N)).

  一般数组求某一连续段的和的时间复杂度为O(N),而树状数组为O(log(N)). 因此,树状数组适合于,需要大量经常计算某连续段的和的情景。

 
#include<stdio.h>#include<ctype.h>#definelowbit(t) (t&(t^(t-1))) #defineRESULT_MAX 15000/*  */#defineMAX_NUM 32005/*  *///please declare parameters here.int in[MAX_NUM];int result[RESULT_MAX];int N;//please declare functions here.//求前n项和int sum(int end) {int sum = 0; while(end > 0){sum += in[end];end -= lowbit(end);}return sum;}//增加某个元素的大小void plus(int pos, int num){while(pos<=MAX_NUM){in[pos] += num;pos += lowbit(pos);}}int main(){if(freopen("input.txt","r",stdin)==NULL) perror("Can not open the input file!");//input your .scanf("%d\n",&N);        int i,x;for(i=0;i<N;i++){     x=0;char ch;while(isdigit((ch=getchar()))){x=x*10+(ch-'0');}while(isdigit(getchar()));//scanf("%d %d",&x,&y);//printf("%d %d\n",x,y);x++;result[sum(x)]++;plus(x,1);}for(i=0;i<N;i++){printf("%d\n",result[i]);}return 0;}