【線段樹】SSLOJ 2646 線段樹練習三

LinkLink

SSLOJSSLOJ 26462646

DescriptionDescription

給定一條長度爲m的線段,有n個操作,每個操作有3個數字x,y,z表示把區間[x,y]染成顏色z,詢問染完色之後,這條長度爲m的線段一共有幾種顏色。規定:線段的顏色可以相同。連續的相同顏色被視作一段。問x軸被分成多少段。

InputInput

4 20   	
10 19 1
2 9 2
5 13 3
15 17 4

OutputOutput

7

HintHint

數據規模 
N <= 10000 
M <= 1000000

TrainTrain ofof ThoughtThought


用線段樹做啦
定義一個參數Colorx,其實和線段樹二一樣的。。(除了統計部分),統計部分就兩個子節點合併起來看是否同色,就好了

CodeCode

#include<iostream>
#include<cstdio>

using namespace std;

int n, m, sum;

struct Tree
{
	int l, r, colorx;
}tree[4500125];

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

void Ins(int x, int L, int R, int color)
{
	if (tree[x].l == tree[x].r || L > R) return;//加退出條件,要不然會x刷到很大很大很大很大很大很大很大很大很大很大很大
	if (L == tree[x].l && R == tree[x].r) 
		{tree[x].colorx = color; return;}
	else {
		if (tree[x].colorx >= 0)
		{
			tree[x * 2].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) Ins(x * 2, L, R, color);
		else if (L >= mid) Ins(x * 2 + 1, L, R, color);
		else {
			Ins(x * 2, L, mid, color);
			Ins(x * 2 + 1, mid, R, color);
		}
	}
}//插入基本不變

void Count(int x, int &L, int &R)
{
	int ll = 0,rr = 0;
	if (tree[x].colorx >= 0)
	{
		sum++;
		L = R = tree[x].colorx;//記錄當前區間的左右端點的顏色
		return;
	}
	if (tree[x].r == tree[x].l + 1) return;
	Count(x * 2, L, ll);
	Count(x * 2 + 1, rr, R);
	if (ll == rr && ll) sum--;
	return ;
	
}

int main()
{
	scanf("%d", &m);
	scanf("%d", &n);//很奇妙的換位。。。不換就WA
	Build(1, 1, n);
	for (int i = 1; i <= m; ++i)
	{
		int x, y, z;
		scanf("%d%d%d", &x, &y, &z);
		Ins(1, x, y, z);	
	}
	int c, d;
	Count(1, c, d);
	printf("%d", sum);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章