zoj 1610 线段树

本文深入探讨了线段树的数据结构及其在颜色计算、区间更新和区间查询中的应用,详细介绍了初始化、构建树、更新节点和计算颜色的过程。

线段树

参考:http://wenku.baidu.com/view/aa601208763231126edb11ab.html

计算颜色时维护两个参数cl,cr,返回区间两端点的颜色

1,如果区间为单色则对应颜色+1

2.如果node。col为-1,则递归调用左右子区间,若返回的颜色相同

则对应颜色-1

详见代码

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <climits>
#define L(x) (x << 1)
#define R(x) (x << 1 | 1)

using namespace std;

const int MAX = 8010;
struct Tnode{ int col; int l,r;};
Tnode node[MAX*3];
int col[MAX],len[MAX];;
void init()
{
	memset(node,0,sizeof(node));
	memset(col,-1,sizeof(col));
}
void Build(int t,int l,int r)
{
	node[t].l = l;
	node[t].r = r;
	node[t].col = -1;
	if( l == r - 1 ) return ;
	int mid = ( l + r ) >> 1;
	Build(L(t), l, mid);
	Build(R(t), mid, r);
}

void Updata(int t,int l,int r,int col)
{
	if( node[t].l >= l && node[t].r <= r )
	{
		node[t].col = col;
		return ;
	}
	if( node[t].col == col ) return ;
	if( node[t].col >= 0 )
	{
		node[R(t)].col = node[t].col;
		node[L(t)].col = node[t].col;
		node[t].col = -1;
	}
	int mid = (node[t].l + node[t].r) >> 1; 
	if( l >= mid )
		Updata(R(t),l,r,col);
	else
		if( r <= mid )
			Updata(L(t),l,r,col);
		else
		{
			Updata(L(t),l,mid,col);
			Updata(R(t),mid,r,col);
		}
}
void Compute(int t,int l,int r,int &cl,int &cr)
{
	if( node[t].col >= 0 )
	{
		len[node[t].col]++;
		cr=node[t].col;
		cl=node[t].col;\\区间为单一颜色直接计数返回颜色
		return ;
	}
	if( node[t].l == node[t].r - 1 ) 
	{
		cr=-1;
		cl=-1;
		return ; 
	}
	int mid = (node[t].l + node[t].r) >> 1; 
	int tr1,tr2,tl1,tl2;
	if( l >= mid )
	{
		Compute(R(t),l,r,cl,cr);
	}
	else
		if( r <= mid )
		{
			Compute(L(t),l,r,cl,cr);
		}
		else
		{
			Compute(L(t),l,mid,tl1,tr1);\\统计左区间两端颜色
			Compute(R(t),mid,r,tl2,tr2);\\统计右边区间两端颜色
			if(tr1>=0&&tl2>=0&&tr1==tl2)\\若颜色相同,合并区间颜色减一
				len[tr1]--;
			cl=tl1;\\返回本区间两端颜色
			cr=tr2;
		}
}

int main()
{
	int n,x,y,color;
	
	while( ~scanf("%d",&n) )
	{
		init();
		Build(1,0,8000);
		while( n-- )
		{
			scanf("%d%d%d",&x,&y,&color);
			Updata(1,x,y,color);
		}
		memset(len,0,sizeof(len));
		Compute(1,0,8000,x,y);
	  
		 for(int i=0; i<MAX; i++)  
            if( len[i] )  
                printf("%d %d\n",i,len[i]);  
        printf("\n");  
	}
	
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值