首页 > 代码库 > LightOJ 1088 - Points in Segments 二分

LightOJ 1088 - Points in Segments 二分

http://www.lightoj.com/volume_showproblem.php?problem=1088

 

题意:给出N个点,Q个查询,问在区间内的点数有多少个。

思路:直接在线二分,注意边界问题

 

 

/** @Date    : 2016-12-17-19.03  * @Author  : Lweleth (SoungEarlf@gmail.com)  * @Link    : https://github.com/  * @Version :  */#include<bits/stdc++.h>#define LL long long#define PII pair#define MP(x, y) make_pair((x),(y))#define fi first#define se second#define PB(x) push_back((x))#define MMG(x) memset((x), -1,sizeof(x))#define MMF(x) memset((x),0,sizeof(x))#define MMI(x) memset((x), INF, sizeof(x))using namespace std;const int INF = 0x3f3f3f3f;const int N = 1e5+20;const double eps = 1e-8;int a[N];int query(int x, int y, int n)//二分细节阿阿阿 边界问题{    int p1 = -1, p2 = -1;    int l = 0, r = n - 1;    while(l <= r)    {        int mid = (l + r) >> 1;        //cout << "l1:" < a[mid])            l = mid + 1;    }    l = 0, r = n - 1;    while(l <= r)    {        int mid = (l + r) >> 1;        //cout << "l2:" <= a[mid])            l = mid + 1, p2 = mid;    }    if(!(~p1) || !(~p2))//        return 0;    else        return p2 - p1 + 1;}int main(){    int T;    int cnt = 0;    cin >> T;    while(T--)    {        int n, q;        scanf("%d%d", &n, &q);        for(int i = 0; i < n; i++)            scanf("%d", a + i);        printf("Case %d:\n", ++cnt);        while(q--)        {            int x, y;            scanf("%d%d", &x, &y);            int ans = query(x, y, n);            printf("%d\n", ans);        }    }    return 0;}

LightOJ 1088 - Points in Segments 二分