线段树计算线段填色

转自: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值