Points in Segments(二分)Crawling in process...
Crawling failed Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu
Description
Given n points (1 dimensional) and q segments, you have to find the number of points that lie in each of the segments. A point pi will lie in a segment A B if A ≤ pi ≤ B.
For example if the points are 1, 4, 6, 8, 10. And the segment is 0 to 5. Then there are 2 points that lie in the segment.
Input
Input starts with an integer T (≤ 5), denoting the number of test cases.
Each case starts with a line containing two integers n (1 ≤ n ≤ 105) and q (1 ≤ q ≤ 50000). The next line contains n space separated integers denoting the points in ascending order. All the integers are distinct and each of them range in [0, 108].
Each of the next q lines contains two integers Ak Bk (0 ≤ Ak ≤ Bk ≤ 108) denoting a segment.
Output
For each case, print the case number in a single line. Then for each segment, print the number of points that lie in that segment.
Sample Input
1
5 3
1 4 6 8 10
0 5
6 10
7 100000
Sample Output
Case 1:
2
3
2
这是一个二分题,给你一组数字,然后在一段区间上寻找有几个数字在这个区间上。
才开始学习二分,这个题套模板就可以,但是必须要找准区间,才开始做这道题目的时候,理解提议了,但是不会找区间,WA了好几次,最后问了学长才AC的。
代码:
#include<stdio.h>
int a[100005];
int a1, a2, n;
int upper(int a2)
{
int low = 0, high = n - 1, mid;
while(low <= high)
{
mid = (low + high) / 2;
if(a[mid] <= a2)
low = mid + 1;
else
high = mid - 1;
}
return low;//代数试试。
}
int lower(int a1)
{
int low = 0, high = n - 1, mid;
while(low <= high)
{
mid = (low + high) / 2;
if(a[mid] >= a1)
high = mid - 1;
else
low = mid + 1;
}
return low;//代数试试。。
}
int main()
{
int i, j, k, m, t, s, o;
scanf("%d",&t);
for(i = 1; i <= t; i ++)
{
scanf("%d%d",&n,&m);
for(int j = 0; j < n; j ++)
{
scanf("%d",&a[j]);
}
printf("Case %d:\n",i);
for(k = 1; k <= m; k ++)
{
scanf("%d%d",&a1,&a2);
s = upper(a2);
o = lower(a1);
printf("%d\n",s - o);
}
}
return 0;
}