【线段树】线段树练习题三

线段树练习题三

题目

给定一条长度为m的线段,有n个操作,每个操作有3个数字x,y,z表示把区间[x,y]染成颜色z,询问染完色之后,这条长度为m的线段一共有几种颜色。规定:线段的颜色可以相同。连续的相同颜色被视作一段。问x轴被分成多少段。

输入样例

4 20   //四条,总长度为20
10 19 1
2 9 2
5 13 3
15 17 4

输出样例

7

数据范围

N <= 10000
M <= 1000000

解题思路

其实这道题就是一道线段树,和线段树练习二差不多,只要把颜色不是自定义而是根据输入来插入即可.

程序如下

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,m,x,y,z,ans,s,ss;

struct tree_node
{
	int l,r,colorx;
}tree[400001];

void build(int x,int L,int R)//建树
{
	tree[x].l=L; tree[x].r=R;
	if(L + 1 == R) return;
	int mid=(L+R)>>1;
	build(x * 2,L,mid);
	build(x * 2 + 1,mid,R);
}

void insert(int x,int L,int R,int color)//插入
{
	if (tree[x].l == L && tree[x].r == R) 
	{
		tree[x].colorx = color;
		return ;
	}
	else
	{
		if (tree[x].colorx >= 0)
		{
			tree[x * 2].colorx = tree[x].colorx;
			tree[x * 2 + 1].colorx = tree[x].colorx;
			tree[x].colorx = -1;
		}
		int mid = (tree[x].l + tree[x].r) >> 1;
		if (R <= mid) insert(x * 2,L,R,color);
		else if (L >= mid) insert(x * 2 + 1,L,R,color);
		else {
			insert(x * 2,L,mid,color);
			insert(x * 2 + 1,mid ,R,color);
		}
	}
}

void ask(int x,int &L,int &R)//统计,要用滚动,因为要把它给下传
{
	int ll = 0,rr = 0;
	if(tree[x].colorx >= 0)
	{
		ans++;
		L = tree[x].colorx;
		R = tree[x].colorx;
		return ;
	}
	if(tree[x].l+1 == tree[x].r) return;
	ask(x*2,L,ll);
	ask(x*2+1,rr,R);
	if(ll == rr && ll!=0) ans--;
	return ;
}

int main()
{
	scanf("%d%d",&n,&m);
	build(1,1,m);
	for(int i = 1;i <= n; ++i)
	{
		scanf("%d%d%d",&x,&y,&z);
		insert(1,x,y,z);
	}
	ans = 0;
	ask(1,s,ss);
	printf("%d",ans);
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值