Cod sursa(job #1620553)

Utilizator Alexa2001Alexa Tudose Alexa2001 Data 29 februarie 2016 10:45:17
Problema Gropi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.26 kb
#include <cstdio>
#include <algorithm>

using namespace std;

int s[100004],n,i,m,q,v1,v2,X1,X2,Y1,Y2;
struct Stiee{int x,y;};
Stiee a[100004];

inline bool comp(Stiee a,Stiee b) {return a.y<b.y;}

inline int bs(int x,bool K)
{
    int st=1,dr=m,mj;

    while(st<=dr)
    {
        mj=(st+dr)/2;
        if(a[mj].y==x) return mj;
        if(a[mj].y<x) st=mj+1;
        else dr=mj-1;
    }
    if(K) return st;
    return dr;
}

int main()
{
    freopen("gropi.in","r",stdin);
    freopen("gropi.out","w",stdout);

    scanf("%d%d",&n,&m);
    for(i=1;i<=m;++i) scanf("%d%d",&a[i].x,&a[i].y);
    sort(a+1,a+m+1,comp);

    for(i=2;i<=m;++i)
    s[i]=s[i-1]+(a[i-1].x!=a[i].x);

    scanf("%d",&q);

    while(q--)
    {
        scanf("%d%d%d%d",&X1,&Y1,&X2,&Y2);
        if(Y1>Y2)
        {
            swap(Y1,Y2);
            swap(X1,X2);
        }

        v1=bs(Y1,1);
        if(v1>m)
        {
            printf("%d\n",(Y2-Y1+1)+(X1!=X2));
            continue;
        }

        if(Y1==Y2)
        {
            printf("%d\n",1+(X1!=X2));
            continue;
        }

        if(a[v1].y==Y1) ++v1;
        v2=bs(Y2,0);

        if(v1>v2) printf("%d\n",(Y2-Y1+1)+(X1!=X2));
        else printf("%d\n",s[v2]-s[v1]+(a[v1].x==X1)+(a[v2].x==X2)+(Y2-Y1+1));
    }

    return 0;
}