转自:http://blog.csdn.net/cnyali/article/details/43562467
#include<stdio.h>
#include<stdlib.h>
struct node{
int s,t,c;
struct node *l,*r;
};
struct node *h;
int m,n;
int c_sum[100010];
void create_tree(struct node *x){
int mid;
struct node *p,*q;
if(x->t-x->s<=1)return;
mid=(x->s+x->t)/2;
p=new node;
p->s=x->s;p->t=mid;p->c=0;
p->l=NULL;p->r=NULL;
q=new node;
q->s=mid;q->t=x->t;q->c=0;
q->l=NULL;q->r=NULL;
x->l=p;x->r=q;
create_tree(p);
create_tree(q);
return;
}
void color(struct node *x,int u,int v,int z){
if(x==NULL)return ;
if(x->s==u && x->t==v){
x->c=z;
return;
}else{
if(x->c!=-1){
x->l->c=x->c;
x->r->c=x->c;
x->c=-1;
}
if(v<=x->l->t)
color(x->l,u,v,z);
else if(u>=x->r->s)
color(x->r,u,v,z);
else{
color(x->l,u,x->l->t,z);
color(x->r,x->r->s,v,z);
}
}
return;
}
void cal(struct node *x){
if(x==NULL)return ;
if(x->c!=-1){
c_sum[x->c]+=x->t-x->s;
return ;
}else{
cal(x->l);
cal(x->r);
}
}
int main(){
int i,j,k;
int x,y,z;
scanf("%d%d",&m,&n);
h=new node;
h->s=0;h->t=m;h->c=0;
h->l=NULL;h->r=NULL;
create_tree(h);
for(i=1;i<=n;i++){
scanf("%d%d",&x,&y);
color(h,x,y,i);
}
cal(h);
for(i=0;i<=n;i++)
if(c_sum[i]!=0)printf("%d: %d\n",i,c_sum[i]);
system("pause");
return 0;
}