数轴上有n个点,对于任一闭区间 [a, b],试计算落在其内的点数。
输入
第一行包括两个整数:点的总数n,查询的次数m。
第二行包含n个数,为各个点的坐标。
以下m行,各包含两个整数:查询区间的左、右边界a和b。
输出
对每次查询,输出落在闭区间[a, b]内点的个数。
输入样例
5 2
1 3 7 9 11
4 6
7 12
输出样例
0
3
限制
0 ≤ n, m ≤ 5×105
对于次查询的区间[a, b],都有a ≤ b
各点的坐标互异
各点的坐标、查询区间的边界a、b,均为不超过10^7的非负整数
时间:2s,内存:256MB
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <vector>
#define MAXLEN 500000
#define ERROR -1
using namespace std;
int a[MAXLEN];
int b[MAXLEN][2];
int findBoundryLeft(int left, int right, int queiesLeft);
int findBoundryRight(int left, int right, int queiesRight);
void swapNumbe(int &a,int &b);
void sortQuick(int* a, int low, int high);
int findBoundryLeft(int left, int right, int queiesLeft)
{
if(left==right) return left;
int mid = (left+right)/2;
if (a[mid] < queiesLeft)
{
return findBoundryLeft(mid+1,right,queiesLeft);
}
else
{
return findBoundryLeft(left,mid,queiesLeft);
}
}
int findBoundryRight(int left, int right, int queiesRight)
{
if(left==right) return right;
int mid = (left+right+1)/2;
if (a[mid] > queiesRight)
{
return findBoundryRight(left,mid-1,queiesRight);
}
else
{
return findBoundryRight(mid,right,queiesRight);
}
}
int main()
{
int arrayLength,queies; //数组长度和查询次数
cin >> arrayLength >> queies;
//输入数组元素
for (int i = 0; i < arrayLength; ++i)
{
cin>>a[i];
}
//排序
sort(a,a+arrayLength);
//输入左右区间
int l,r;
int leftBoundry = 0;
int rightBoundry = 0;
vector<int> v;
for(int i=0; i<queies; i++ )
{
cin >> b[i][0] >> b[i][1];
if(b[i][0]>b[i][1]) swap(l,r);
if (b[i][0] > a[arrayLength-1] || b[i][1] < a[0])
{
cout<<"error"<<endl;
}
//找到左边界
leftBoundry = findBoundryLeft(0,arrayLength-1,b[i][0]);
//找到右边界
rightBoundry = findBoundryRight(0,arrayLength-1,b[i][1]);
//存储结果
v.push_back(rightBoundry-leftBoundry);
}
//输出结果
for(int i=0; i<v.size(); i++)
{
cout<<v[i]<<endl;
}
return 0;
}