hdu 1566 Color the ball---线段树

不知值不值得开心,这题我是没有百度,google的说,自己的方法过的感觉就是不一样

前天做了pku的346觉得思路用在这题也行,结果还真的,嘻嘻~~

#include<stdio.h> #define N 100005 struct node{ int l; int r; int sum; int add; node *after; }; node tree[3*N]; node *(p1[N]);//指针数组,指向,各个叶子结点 void buid_tree(int k,int left,int right) { int mid; int L,R; tree[k].l = left; tree[k].r = right; tree[k].sum = 0; tree[k].add = 0; if(tree[k].r-tree[k].l == 1){ //if(tree[k].l == 1){ // p = &tree[k]; //} //p->after = &tree[k]; //p = &tree[k]; p1[tree[k].l] = &tree[k]; return ; } mid = (tree[k].l+tree[k].r)/2; L = k<<1; R = L+1; if(left < mid) buid_tree(L,left,mid); if(right > mid) buid_tree(R,mid,right); return ; } //插入就和之前做的pku3468一样,用一个add进行传递 void tree_insert(int k,int left,int right) { int mid; int L,R; if(left <= tree[k].l && right >= tree[k].r){ tree[k].add += 1; tree[k].sum += (tree[k].r-tree[k].l); return ; } mid = (tree[k].l+tree[k].r)/2; L = k<<1; R = L+1; if(tree[k].add){ tree[L].add += tree[k].add; tree[R].add += tree[k].add; tree[L].sum += (tree[L].r-tree[L].l)*tree[k].add; tree[R].sum += (tree[R].r-tree[R].l)*tree[k].add; tree[k].add = 0; } if(left < mid) tree_insert(L,left,right); if(right > mid) tree_insert(R,left,right); tree[k].sum = tree[L].sum+tree[R].sum; return ; } //这个很重要,把add中传递下去的,都传下去直到叶子结点,计算出叶子结点最终sum //最后直接用指针数组输出就行了 void tree_comp(int k) { int L,R; L = k<<1; R = L+1; if(tree[k].r-tree[k].l == 1) return ; if(tree[k].add){ tree[L].add += tree[k].add; tree[R].add += tree[k].add; tree[L].sum += (tree[L].r-tree[L].l)*tree[k].add; tree[R].sum += (tree[R].r-tree[R].l)*tree[k].add; tree[k].add = 0; } tree_comp(L); tree_comp(R); return ; } int main() { int n; int a,b; int i; while(scanf("%d",&n) == 1 && n){ buid_tree(1,1,n+1); for(i = 1;i <= n;i++){ scanf("%d %d",&a,&b); tree_insert(1,a,b+1); } tree_comp(1); //指针数组输出 printf("%d",p1[1]->sum); for(i = 2;i <= n;i++){ printf(" %d",p1[i]->sum); } printf("/n"); } return 0; }

你可能感兴趣的:(hdu 1566 Color the ball---线段树)