【SSL_P2647】线段树练习四

线段树练习四


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

解题思路

这道题实际上比上一道题线段树练习三还要简单,只需要加入和统计就可以了,不需要进行特判,代码如下:

#include<iostream>
#include<cstdio>
using namespace std;

int n,m;

struct abc{
	int x,y,sum;
}tree[400010];

void build(int u)
{
	if(tree[u].x+1<tree[u].y)
	{
		int mid=(tree[u].x+tree[u].y)/2;
		tree[u*2].x=tree[u].x;
		tree[u*2].y=mid;
		tree[u*2+1].x=mid;
		tree[u*2+1].y=tree[u].y;
		build(u*2);
		build(u*2+1);
	}
}

void in(int a,int b,int u)
{
	int mid=(tree[u].x+tree[u].y)/2;
	if(tree[u].x==a&&tree[u].y==b)
		tree[u].sum++;
	else if(b<=mid)
		in(a,b,u*2);
	else if(a>=mid)
		in(a,b,u*2+1);
	else
	{
		in(a,mid,u*2);
		in(mid,b,u*2+1);
	}
}

int find(int a,int b,int u)
{
	int s=tree[1].sum;
	while(tree[u].x+1<tree[u].y)
	{
		int mid=(tree[u].x+tree[u].y)/2;
		if(tree[u].x==a&&tree[u].y==b)
			break;
		else if(b<=mid)
			s+=tree[u*2].sum,u*=2;
		else if(a>=mid)
			s+=tree[u*2+1].sum,u=u*2+1;
	}
	return s;
}
int main()
{
	cin>>n>>m; 
	tree[1].x=1;
	tree[1].y=n;
	build(1);
	for(int i=1;i<=m;i++)
	{
		int xx,yy;
		scanf("%d%d",&xx,&yy);
		in(xx,yy,1);
	}
	int xx,yy;
	cin>>xx>>yy;
	cout<<find(xx,yy,1)<<endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值