hdu 1556 Color the ball (线段树做法)

Problem Description

N个气球排成一排,从左到右依次编号为1,2,3....N.每次给定2个整数a b(a <= b),lele便为骑上他的“小飞鸽"牌电动车从气球a开始到气球b依次给每个气球涂一次颜色。但是N次以后lele已经忘记了第I个气球已经涂过几次颜色了,你能帮他算出每个气球被涂过几次颜色吗?

Input

每个测试实例第一行为一个整数N,(N <= 100000).接下来的N行,每行包括2个整数a b(1 <= a <= b <= N)。
当N = 0,输入结束。

Output

每个测试实例输出一行,包括N个整数,第I个数代表第I个气球总共被涂色的次数。


#include<stdio.h> #pragma comment(linker,"/STACk:1024000000,1024000000") struct CNode { int L,R; //int nSum; int Inc; CNode *pLeft,*pRight; }; CNode Tree[1000050]; int nCount; int Mid(CNode *pRoot) { return (pRoot->L+pRoot->R)/2; } void BuildTree(CNode *pRoot,int L,int R) { pRoot->L=L; pRoot->R=R; //pRoot->nSum=0; pRoot->Inc=0; if(L==R) return ; nCount++; pRoot->pLeft=Tree+nCount; nCount++; pRoot->pRight=Tree+nCount; BuildTree(pRoot->pLeft,L,(L+R)/2); BuildTree(pRoot->pRight,(L+R)/2+1,R); } /*void Insert(CNode *pRoot,int i,int v) { if(pRoot->L==i&&pRoot->R==i) { pRoot->nSum=v; return ; } pRoot->nSum+=v; if(i<=Mid(pRoot)) Insert(pRoot->L,i,v); else Insert(pRoot->R,i,v); }*/ void Add(CNode *pRoot,int a,int b) { if(pRoot->L==a&&pRoot->R==b) { pRoot->Inc++; return ; } //pRoot->nSum+=c*(b-a+1); if(b<=Mid(pRoot)) Add(pRoot->pLeft,a,b); else if(a>=Mid(pRoot)+1) Add(pRoot->pRight,a,b); else { Add(pRoot->pLeft,a,Mid(pRoot)); Add(pRoot->pRight,Mid(pRoot)+1,b); } } int ans; int QuerySum(CNode *pRoot,int a,int b,int i) { ans+=pRoot->Inc; if(pRoot->L==i&&pRoot->R==i) return ans;//pRoot->nSum+(pRoot->R-pRoot->L+1)*pRoot-> //pRoot->nSum+=(pRoot->R-pRoot->L)*pRoot->Inc; //Add(pRoot->pLeft,pRoot->L,Mid(pRoot),pRoot->Inc); //Add(pRoot->pRight,Mid(pRoot)+1,pRoot->R,pRoot->Inc); //pRoot->Inc=0; if(i<=Mid(pRoot)) return QuerySum(pRoot->pLeft,a,b,i); else //(i>=Mid(pRoot)+1) return QuerySum(pRoot->pRight,a,b,i); /*else { return QuerySum(pRoot->pLeft,a,Mid(pRoot),i) +QuerySum(pRoot->pRight,Mid(pRoot)+1,b,i); }*/ } int main() { int n,a,b,i; while(scanf("%d",&n)!=EOF&&n) { nCount=0; BuildTree(Tree,1,n); for(i=0;i<n;i++) { scanf("%d%d",&a,&b); Add(Tree,a,b); } for(i=1;i<n;i++) { ans=0; printf("%d ",QuerySum(Tree,1,n,i)); } ans=0; printf("%d ",QuerySum(Tree,1,n,n)); } return 0; }
原文地址:https://www.cnblogs.com/XDJjy/p/3283287.html