zoj 1610 Count the Colors【线段树】

//纠结了好久,因为中间的一个逻辑错误
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define L(x) ((x) << 1)
#define R(x) ((x) << 1 | 1)
#define Mid(x, y) (((x)+(y)) >> 1)
#define MAX 8005
#define P(x) printf(x)
#define STOP system("pause") 
typedef struct
{
	int l, r, c;
}Node;
Node s[MAX * 3];
int col[MAX], pre;
void build(int idx, int l, int r, int c)
{
	s[idx].l = l;
	s[idx].r = r;
	s[idx].c = c;
	if(l + 1 == r)	return;//构造出的结果是最底层是长度为1的线段
	int mid = Mid(l, r);
	build(L(idx), l, mid, c);
	build(R(idx), mid, r, c);
}

void update(int idx, int l, int r, int c)
{
	if(s[idx].c == c)	return;
	if(s[idx].l >= r || s[idx].r <= l)	return;
	if(s[idx].l >= l && s[idx].r <= r)
	{
		s[idx].c = c; 
		return;
	}
	if(s[idx].c != -1)//就是这里,刚开始没有这个if
	{
		s[L(idx)].c = s[idx].c;
		s[R(idx)].c = s[idx].c;
		s[idx].c = -1;
	}
	update(L(idx), l, r, c);
	update(R(idx), l, r, c);
}

void compute(int idx)
{
	if(s[idx].c == -1 && s[idx].r - s[idx].l > 1)//注意结束条件
	{
		compute(L(idx));
		compute(R(idx));
		return;
	}
	if(s[idx].c == -1)
	{
		pre = -1;
		return;
	}
	if(s[idx].c != pre)
	{
		col[ s[idx].c ]++;
		pre = s[idx].c;
		return;
	}
}
int main()
{
	int n, i, c, x, y, j;
	while( ~scanf("%d", &n) )
	{
		build(1, 0, 8000, -1);
		memset(col, 0, sizeof(col));
		for(i=0; i<n; i++)
		{
			scanf("%d%d%d", &x, &y, &c);
			update(1, x, y, c);
		}
		pre = -1;
		compute(1);
		for(i=0; i<MAX; i++)
			if(col[i])
				printf("%d %d\n", i, col[i]);
		printf("\n");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值