HDU 5862 Counting Intersections

扫描线,树状数组求和。

横着的线的两个端点作为插入和删除,竖着的线作为询问。

遇到横着的线的左端点,那么那个位置+1,

遇到竖着的线,询问竖着那一段区间和是多少,区间和就是这条线对答案做出的贡献,

遇到横着的线的右端点,那么那个位置-1。

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
typedef long long LL;
const double pi=acos(-1.0),eps=1e-8;
void File()
{
    freopen("D:\in.txt","r",stdin);
    freopen("D:\out.txt","w",stdout);
}
template <class T>
inline void read(T &x)
{
    char c = getchar(); x = 0;while(!isdigit(c)) c = getchar();
    while(isdigit(c)) { x = x * 10 + c - '0'; c = getchar();  }
}

const int maxn=100010;
int T,n,sz,a[5*maxn],c[5*maxn],cnt;
struct X { int t,x,f,L,R; }s[5*maxn];

bool cmp(X a,X b)
{
    if(a.x==b.x)
    {
        if(a.t==0&&b.t==0) return 1;
        if(a.t==1&&b.t==0)
        {
            if(a.f==1) return 1;
            else return 0;
        }

        if(a.t==0&&b.t==1)
        {
            if(b.f==1) return 0;
            else return 1;
        }

        if(a.t==1&&b.t==1) return a.f>b.f;
    }
    return a.x<b.x;
}

int get(int x)
{
    int res,L=0,R=cnt-1;
    while(L<=R)
    {
        int mid=(L+R)/2;
        if(a[mid]>x) R=mid-1;
        else if(a[mid]==x) res=mid, R=mid-1;
        else L=mid+1;
    }
    res++;
    return res;
}

int lowbit(int x) {return x&(-x);}

void add(int p,int x)
{
    for(int i=p;i<=300000;i=i+lowbit(i)) c[i]=c[i]+x;
}

int sum(int p)
{
    int res=0;
    for(int i=p;i>0;i=i-lowbit(i)) res=res+c[i];
    return res;
}

int main()
{
   // File();
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n); cnt=sz=0;
        for(int i=1;i<=n;i++)
        {
            int x1,y1,x2,y2; scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
            if(x1==x2)
            {
                if(y1>y2) swap(y1,y2);
                s[sz].t=0; s[sz].x=x1; s[sz].L=y1; s[sz].R=y2; sz++;
                a[cnt++]=y1; a[cnt++]=y2;
            }
            else if(y1==y2)
            {
                if(x1>x2) swap(x1,x2);
                s[sz].t=1; s[sz].x=x1; s[sz].f=1; s[sz].L=y1; sz++;
                s[sz].t=1; s[sz].x=x2; s[sz].f=-1; s[sz].L=y1; sz++;
                a[cnt++]=y1;
            }
        }

        sort(a,a+cnt);
        for(int i=0;i<sz;i++)
        {
            if(s[i].t==0) s[i].L=get(s[i].L), s[i].R=get(s[i].R);
            else if(s[i].t==1) s[i].L=get(s[i].L);
        }

        sort(s,s+sz,cmp); memset(c,0,sizeof c);

        LL ans=0;
        for(int i=0;i<sz;i++)
        {
            if(s[i].t==0) ans=ans+(LL)(sum(s[i].R)-sum(s[i].L-1));
            else add(s[i].L,s[i].f);
        }
        printf("%lld
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/5788692.html