L i n k Link Link
S S L O J SSLOJ SSLOJ 2647 2647 2647
D e s c r i p t i o n Description Description
在平面内有一条长度为n的线段(也算一条线段),可以对进行以下2种操作:
1 x y 把从x到y的再加一条线段
2 x 查询从x到x+1有多少条线段
I n p u t Input Input
第一行输入n,m
第2~m+1行,每行3个数
O u t p u t Output Output
对于每个查询操作,输出线段数目
S a m p l e Sample Sample I n p u t Input Input
7 2
2 5
3 6
4 5
S a m p l e Sample Sample O u t p u t Output Output
2
H i n t Hint Hint
【数据规模】
100%满足1≤n≤100000,1≤x≤y≤n
T r a i n Train Train o f of of T h o u g h t Thought Thought
就统计每一个区间有多少线段覆盖就好了吧
C o d e Code 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;
}