Tsinghua OJ:范围查询(Range)
来源:互联网 发布:mac快捷键缩小窗口 编辑:程序博客网 时间:2024/05/21 19:49
范围查询(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.
Example
Input
5 21 3 7 9 114 67 12
Output
03
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
解题思路:
1、用points数组标识,将有坐标位置置1(points数组初始化0)。
2、更新数组:points[i] += points[i-1] (i>1)。这时points[i],即表示[0,i]之间的坐标数。
3、用points[b] - points[a] 即得结果。
注意:由于第2步中,可能出现的下标为小于0的情况。因此,第1步置1的时候,可以将其往后移一位。
具体代码如下:
#include <cstdio> #include <cstdlib>const int SZ = 1 << 20; //提升IO buff struct fastio{char inbuf[SZ];char outbuf[SZ];fastio(){setvbuf(stdin, inbuf, _IOFBF, SZ);setvbuf(stdout, outbuf, _IOFBF, SZ);}}io;#define N 10000001int points[N];int main(){int n, m, i, x;int a, b;scanf("%d %d", &n, &m);for (i = 0; i < N; i++)points[i] = 0;while (n--){scanf("%d", &x);points[x + 1] = 1;}for (i = 2; i <= N; ++i)points[i] += points[i - 1];while (m--){scanf("%d %d", &a, &b);printf("%d\n", points[b + 1] - points[a]);}return 0;}
- Tsinghua OJ:范围查询(Range)
- Tsinghua MOOC 范围查询(Range)
- 范围查询(Range)
- 范围查询(Range)
- Tsinghua OJ:祖玛(Zuma)
- Tsinghua OJ:灯塔(LightHouse)
- Tsinghua OJ:隧道(Tunel)
- Lucene2.9 范围查询Range Query
- 1-1 范围查询(Range)
- 范围查询(Range)-----学堂在线编程题
- 范围最小值查询 RMQ (Range Minimum Query)
- Tsinghua OJ:列车调度(Train)
- Tsinghua OJ 多米诺骨牌(domino)
- Tsinghua OJ:真二叉树重构(Proper Rebuild)
- Geeks - Range Minimum Query RMQ范围最小值查询
- THU数据结构编程作业一:查询范围(Range)
- 学堂在线-数据结构-PA1-范围查询(Range)-解题报告
- LeetCode OJ 之 Search for a Range (查找一个范围)
- JS基础
- require头域
- python保存文件UnicodeEncodeError以及reload(sys)后print失效问题
- 数据挖掘导论总结之分类技术
- leetcode-292-Nim Game
- Tsinghua OJ:范围查询(Range)
- Android开发规范
- HP Unified Functional Testing的使用
- java IO流
- 2.2 规划物理内存格局,设置缓冲区、虚拟盘、主内存
- 2.3 设置虚拟盘空间并初始化
- nginx配置文件详解
- 2.4 内存管理结构mem_map初始化
- Java 反射简介