题目链接;
http://www.lightoj.com/volume_showproblem.php?problem=1088
题目描述:
给出一个n位数升序排列的数列,然后q个查询,每个查询问指定的区间覆盖了数列中几个数?
解题思路:
二分枚举区间的起始点和终点在数列中的位置。
upper_bound() 返回数列中第一个大于所查询数的位置,或者没有大于所查询的数返回数列长度(越界)
lower_bound() 返回数列中第一个等于或者大于所查询数的位置,或者没有等于,大于所查询数返回数列长度(越界)
哦,对对对!还有噢,不能用cin, cout输入,会TLE的,亲试~
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<algorithm> 5 #include<cmath> 6 using namespace std; 7 8 #define LL long long 9 #define maxn 100010 10 #define esp 1e-12 11 #define PI acos(-1.0) 12 13 int a[maxn]; 14 15 int main () 16 { 17 int T, L = 1; 18 cin >> T; 19 while (T --) 20 { 21 int n, q; 22 23 scanf ("%d %d", &n, &q); 24 25 for (int i=0; i<n; i++) 26 scanf ("%d", &a[i]); 27 //sort (a, a+n); 28 29 int x, y; 30 printf ("Case %d: ", L++); 31 while (q --) 32 { 33 scanf ("%d %d", &x, &y); 34 int ans = upper_bound (a, a+n, y) - a; 35 ans -= lower_bound (a, a+n, x) - a; 36 37 printf ("%d ", ans); 38 } 39 } 40 return 0; 41 } 42 /* 43 4 44 30 40 10 45 12.619429 8.163332 3 46 10 10 3 47 10 10 1 48 */