【線段樹】SSLOJ 2647 線段樹練習四

LinkLink

SSLOJSSLOJ 26472647

DescriptionDescription

在平面內有一條長度爲n的線段(也算一條線段),可以對進行以下2種操作:
1 x y 把從x到y的再加一條線段
2 x 查詢從x到x+1有多少條線段

InputInput

第一行輸入n,m
第2~m+1行,每行3個數

OutputOutput

對於每個查詢操作,輸出線段數目

SampleSample InputInput

7 2
2 5
3 6
4 5

SampleSample OutputOutput

2

HintHint

【數據規模】 
100%滿足1≤n≤100000,1≤x≤y≤n

TrainTrain ofof ThoughtThought

就統計每一個區間有多少線段覆蓋就好了吧

CodeCode

#include<iostream>
#include<cstdio>

using namespace std;

int ans, n, m;

struct Tree
{
	int l, r, num;
}tree[400005];

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 Ins(int x, int L, int R)
{
	if (tree[x].l == L && tree[x].r == R) {
		tree[x].num ++;
		return ;
	}//記錄當前區間被多少條線段剛好覆蓋	
	int mid = (tree[x].l + tree[x].r) >> 1;
	if (R <= mid) Ins(x * 2, L, R);
	 else if (L >= mid) Ins(x * 2 + 1, L, R);
	  else {
	  	Ins(x * 2, L, mid);
	  	Ins(x * 2 + 1, mid, R);
	  } 
} 

int Print(int x)
{
	while (x > 0)
	{
		ans += tree[x].num;
		x >>= 1;
	}
	return ans;
}//統計答案

int Count(int x, int L, int R)
{
	int mid = (tree[x].l + tree[x].r) >> 1;
	if (tree[x].l == L && tree[x].r == R) return Print(x);//找出所求區間的位置 
	if (R <= mid) Count(x * 2, L, R);
	 else if (L >= mid) Count(x * 2 + 1, L, R);
	  else {
	  	Count(x * 2, L, mid);
	  	Count(x * 2 + 1, mid, R);
	  } 
}

int main()
{
	int x, y;
	scanf("%d%d", &n, &m);
	Build(1, 1, n);
	for (int i = 1; i <= m; ++i)
	{
		scanf("%d%d", &x, &y);
		Ins(1, x, y);
	}
	scanf("%d%d", &x, &y);
	printf("%d", Count(1, x, y));
	return 0;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章