数据结构(上)(自主模式) 范围查询(Range)

范围查询(Range)
Descriptioin
Let S be a set of n integral points on the x-axis. For each given interval [a, b], you are asked to count the points lying inside.

Input
The first line contains two integers: n (size of S) and m (the number of queries).

The second line enumerates all the n points in S.

Each of the following m lines consists of two integers a and b and defines an query interval [a, b].

Output
The number of points in S lying inside each of the m query intervals.

Input

5 2
1 3 7 9 11
4 6
7 12

Output

0
3

Restrictions
0 <= n, m <= 5 * 10^5

For each query interval [a, b], it is guaranteed that a <= b.

Points in S are distinct from each other.

Coordinates of each point as well as the query interval boundaries a and b are non-negative integers not greater than 10^7.

Time: 2 sec

Memory: 256 MB

描述
数轴上有n个点,对于任一闭区间 [a, b],试计算落在其内的点数。

输入
第一行包括两个整数:点的总数n,查询的次数m。

第二行包含n个数,为各个点的坐标。

以下m行,各包含两个整数:查询区间的左、右边界a和b。

输出
对每次查询,输出落在闭区间[a, b]内点的个数。

样例
见英文题面

限制
0 ≤ n, m ≤ 5×105

对于每次查询的区间[a, b],都有a ≤ b

各点的坐标互异

各点的坐标、查询区间的边界a、b,均为不超过10^7的非负整数

时间:2 sec

内存:256 MB

思路:考虑到数据不超过1e7可以直接for 一遍1e7
用前缀和的思路记录此前出现过多少不同的数。

#include<cstdio>
using namespace std;
const int mmax=1e7+5;
int mp[mmax];
int f[mmax];
int main(){
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		int a;
		scanf("%d",&a);
		mp[a]=1;
	}
	for(int i=0;i<=mmax-1;i++){
		if(mp[i])
			f[i]=f[i-1]+1;
		else f[i]=f[i-1];
	}
	while(m--){
		int a,b;
		scanf("%d%d",&a,&b);
		int ans=f[b]-f[a];
		if(mp[a])
			ans++;
		printf("%d\n",ans);
	}
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值