數據結構(Tsinghua--範圍查詢(Range))

描述

數軸上有n個點,對於任一閉區間 [a, b],試計算落在其內的點數。

輸入

第一行包括兩個整數:點的總數n,查詢的次數m。

第二行包含n個數,爲各個點的座標。

以下m行,各包含兩個整數:查詢區間的左、右邊界a和b。

輸出

對每次查詢,輸出落在閉區間[a, b]內點的個數。

樣例

Input

5 2
1 3 7 9 11
4 6
7 12

Output

0
3

限制

0 ≤ n, m ≤ 5×105

對於每次查詢的區間[a, b],都有a ≤ b

各點的座標互異

各點的座標、查詢區間的邊界a、b,均爲不超過10^7的非負整數

時間:2 sec

內存:256 MB

解題思路:

很容易想到對所有點進行排序,然後通過二分查找,找到對應範圍的下標,進而相減即爲範圍內點數。


#include <cstdio>  
#include <cstdlib>

int room[500010];

//不存在則返回小於該值的最後一個元素的pos(包含哨兵[lo-1])
int mybinsearch(int v[], int const& e, int lo, int hi) {
	while (lo < hi) {
		int mi = (lo + hi) >> 1;
		(e < v[mi]) ? hi = mi : lo = mi + 1;
	}
	return --lo;//返回所搜索值的前一個pos
}

int cmp(const void *a, const void *b)
{
	return *(int*)a - *(int*)b;
}
int mymax(int a, int b)
{
	return (a > b ? a : b);
}
int main()
{
	int N, M;
	scanf("%d %d", &N, &M);

	for (int i = 0; i < N; ++i)
	{
		scanf("%d", &room[i]);
	}
	qsort(room,N, sizeof(int), cmp);

	int start, end;

	for (auto i = 0; i < M; ++i)
	{
		scanf("%d %d", &start, &end);
		int s = mybinsearch(room, start, 0, N);
		int e = mybinsearch(room, end, mymax(s,0), N);
		if (s >= 0 && room[s] == start)
			s--;
		printf("%d\n", e - s);
	}

	return 0;
}

代碼對應結果如下:

Case No. Result Time(ms) Memory(KB)
1 Accepted 0 6456
2 Accepted 0 6456
3 Accepted 0 6456
4 Accepted 0 6456
5 Accepted 0 6456
6 Accepted 0 6456
7 Accepted 0 6456
8 Accepted 0 6456
9 Accepted 0 6456
10 Accepted 0 6456
11 Accepted 0 6456
12 Accepted 36 6692
13 Accepted 48 6772
14 Accepted 20 6772
15 Accepted 60 6848
16 Accepted 72 7044
17 Accepted 116 7160
18 Accepted 132 7240
19 Accepted 208 8412
20 Accepted 360 8412

這裏列出當前Top10的結果

Email Score Worst Case Time(ms) Memory(KB)
suzq** 100.0 20

68 

22580 

zhong3** 100.0 20

72 

44484 

hhyl** 100.0 20

108 

66428 

[Anonymous] 100.0 20

116 

53076 

hongyuan_de** 100.0 20

124 

30984 

wunschunre** 100.0 20

132 

53332 

3830670** 100.0 20

136 

53048 

li-ch** 100.0 20

140 

84308 

4505632** 100.0 20

144 

66608 

gwy** 100.0 20

148 

52524 

可以看到相差較大,那麼進行優化。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章