Analysis:
Just used lower_bound and upper_bound functions which we all know uses built in binary search function. so for any aray of points like
a[10] = {1, 2, 4, 5, 5, 5, 6, 7, 8, 8}
lower_bound(1) = 0 upper_bound(1) = 1
lower_bound(2) = 1 upper_bound(2) = 2
lower_bound(4) = 2 upper_bound(4) = 3
lower_bound(8) = 8 upper_bound(8) = 10
lower_bound(-500) = 0 upper_bound(10000) = 10
using those you can see lower and upper bound works. than just we find lower bound for left of the segment and upper bound for the right limit of the segment and the difference is our answer.
Here goes the code:
- #include <bits/stdc++.h>
- using namespace std;
- int main(){
- int ts;
- scanf("%d", &ts);
- for(int p = 1; p <= ts; p++){
- printf("Case %d:\n", p);
- vector<int>v;
- int n, q;
- scanf("%d%d", &n, &q);
- for(int i = 0; i <n; i++){
- int a;
- scanf("%d", &a);
- v.push_back(a);
- }
- sort(v.begin(), v.end());
- for(int i = 0; i <q; i++){
- int l, r;
- scanf("%d%d", &l , &r);
- printf("%d\n", upper_bound(v.begin(), v.end(),r)-lower_bound(v.begin(), v.end(),l));
- }
- }
- return 0;
- }
No comments:
Post a Comment