【线段树】线段树练习四

Description

在平面内有一条长度为n的线段(不计入答案),可以对进行以下2种操作:
1、把从x到y的再加一条线段
2、查询从x到x+1有多少条线段

Input

第一行输入n,m
第2~m+1行,每行2个数x,y,表示从x到y再加一条线段
最后一行输入2个数,为x和x+1,查询x到x+1的线段数目

Output

输出x到x+1的线段数目

Sample Input

7 2
2 5
3 6
4 5

Sample Output

2

Hint
【数据规模】

100%满足1≤n≤100000,1≤x≤y≤n


解题思路

线段树


/*
root:当前到线段树的哪个节点
l:当前节点代表范围的左端点
r:当前节点代表范围的右端点
x:查找的节点代表范围的左端点
y:查找的节点代表范围的右端点
*/
#include<iostream>
#include<cstdio>
using namespace std;
struct DT{
	int l,r,cnt;
}a[400100];
int n,m,ans,x,y;
void build(int root,int l,int r){//建树
	if(a[root].l+1<a[root].r){
		int mid=(a[root].l+a[root].r)/2;
		a[root*2].l=a[root].l,a[root*2].r=mid;
		a[root*2+1].l=mid,a[root*2+1].r=a[root].r;
		build(root*2,l,mid);
		build(root*2+1,mid+1,r);
	}
}
void insert(int root,int x,int y){
	int mid=(a[root].l+a[root].r)/2;
	if(a[root].l==x&&a[root].r==y)a[root].cnt++;//绳子+1
	   else if(y<=mid)insert(root*2,x,y);
	     else if(x>=mid)insert(root*2+1,x,y);
		   else{
		   	insert(root*2,x,mid);
		   	insert(root*2+1,mid,y);
		   } 
}
int find(int x,int y){
	int root=1,ans=a[root].cnt;//初始化
	while(a[root].l+1<a[root].r){//注意不是递归(应该也可以改成递归qwq)
		int mid=(a[root].l+a[root].r)/2;
		if(a[root].l==x&&a[root].r==y)break;
		if(y<=mid)root*=2,ans+=a[root].cnt;//不断累积答案
		   else 
		 if(x>=mid)root=root*2+1,ans+=a[root].cnt;
	}
	return ans;
}
int main(){
	scanf("%d%d",&m,&n);
	a[1].l=1,a[1].r=m;
    build(1,1,m);
	for(int i=1;i<=n;i++){
		scanf("%d%d",&x,&y);
		insert(1,x,y);
	}
	scanf("%d%d",&x,&y);
	printf("%d",find(x,y));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值