【线段树】SSLOJ 2647 线段树练习四
作者:互联网
Link
Description
在平面内有一条长度为n的线段(也算一条线段),可以对进行以下2种操作:
1 x y 把从x到y的再加一条线段
2 x 查询从x到x+1有多少条线段
Input
第一行输入n,m
第2~m+1行,每行3个数
Output
对于每个查询操作,输出线段数目
Sample Input
7 5
2 3
1 2 5
2 4
1 4 5
2 4
Sample Output
1
2
3
(其实这个样例是假的。。。(暂无正确样例))
Hint
【数据规模】
100%满足1≤n≤100000,1≤x≤y≤n
Train of Thought
就统计每一个区间有多少线段覆盖就好了吧
Code
#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;
}
标签:SSLOJ,int,线段,tree,mid,2647,Build,return 来源: https://blog.csdn.net/LTH060226/article/details/99947064