Time Limit:10000MS Memory Limit:65536K
Total Submit:126 Accepted:47
Case Time Limit:1000MS
Description
在平面内有一条长度为
n
n
n的线段(不计入答案),可以对进行以下
2
2
2种操作:
1、把从
x
x
x到
y
y
y的再加一条线段
2、查询从
x
x
x到
x
+
1
x+1
x+1有多少条线段
Input
第一行输入
n
,
m
n,m
n,m
第
2
m
+
1
2~m+1
2 m+1行,每行
2
2
2个数
x
,
y
x,y
x,y,表示从
x
x
x到
y
y
y再加一条线段
最后一行输入
2
2
2个数,为
x
x
x和
x
+
1
x+1
x+1,查询
x
x
x到
x
+
1
x+1
x+1的线段数目
Output
输出
x
x
x到
x
+
1
x+1
x+1的线段数目
Sample Input
7 2
2 5
3 6
4 5
Sample Output
2
Hint
【数据规模】
100
100
100%满足
1
≤
n
≤
100000
,
1
≤
x
≤
y
≤
n
1≤n≤100000,1≤x≤y≤n
1≤n≤100000,1≤x≤y≤n
解题思路
为线段树每个节点增加一个
C
o
u
n
t
Count
Count域。表示所对应区间上重叠的线段数。
思考线段树的构造方法:当某线段能够完整覆盖某个结点所对应的区间时,则不再二分。因此要统计某个单位区间上重叠的线段总数,必须把从叶结点到根结点路径上所有结点的
c
o
u
n
t
count
count域累加。
a
[
i
]
.
z
a[i].z
a[i].z表示当前节点表示的区间里线段的数量。。。
当前节点表示的区间里线段的数量+这个节点的父节点表示的区间里线段的数量+这个节点的父节点的父节点表示的区间里线段的数量+……+根节点表示的区间里线段的数量=这个节点表示的区间有多少条线段。
代码
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int n,l,ans,x,y,h,t;
struct c{
int x,y,z;
}a[400010];
void insert(int dep,int x,int y)//插入算法
{
int mid=(a[dep].x+a[dep].y)/2;
if(a[dep].x==x&&a[dep].y==y)/如果完全覆盖
{
a[dep].z++;//线段数量+1
return;
}
else if(y<=mid) insert(2*dep,x,y);//全都在左孩子
else if(x>=mid) insert(2*dep+1,x,y);//全都在右孩子
else
{
insert(2*dep,x,mid);
insert(2*dep+1,mid,y);//左右孩子各有一部分
}
}
void b(int i){//建树
if(a[i].y-a[i].x>1)
{
int mid=(a[i].y+a[i].x)/2;
a[i*2].x=a[i].x;
a[i*2].y=mid;
a[i*2+1].x=mid;
a[i*2+1].y=a[i].y;
b(i*2);
b(i*2+1);
}
}
int countt(int dep,int l,int r){//统计
ans=a[1].z;
while(a[dep].y-a[dep].x>1)
{
int mid=(a[dep].y+a[dep].x)/2;
if(l==a[dep].x&&r==a[dep].y)
break;//如果已经统计到当前区间,则退出
if(r<=mid) //全都在左孩子
{
dep=dep*2;
ans+=a[dep].z;
}
if(l>=mid)//全都在右孩子
{
dep=dep*2+1;
ans+=a[dep].z;
}
}
return ans;
}
int main(){
scanf("%d%d",&l,&n);
a[1].x=1,a[1].y=l;
b(1);
for(int i=1;i<=n;i++)
{
scanf("%d%d",&x,&y);
insert(1,x,y);//每次插入线段
}
scanf("%d%d",&h,&t);
printf("%d",countt(1,h,t));
}