E. Count The Rectangles [思维+优先队列+树状数组]

传送门
题意:给出n(n<=5000)条水平和垂直的线段,计算共形成多少个矩形

题解:枚举矩形的上下边即枚举水平线段,显然如果有x个垂直线段与这两条边同时相交那么就形成了x*(x-1)/2个矩形,如果直接暴力枚举垂直线段,那么复杂度为O(n^3),复杂度爆表是因为垂直线段这样被重复计算贡献,思考能不能快速地计算贡献,对于纵坐标为(y1,y2)的垂直线段,其能产生贡献的区间就是下边界为>=y1上边界<=y2,那么可以在枚举上下边界时利用优先队列维护一个满足条件的序列,通过树状数组快速更改新加入的垂直线段的贡献或者删除不满足条件的垂直线段的贡献,复杂度变成了O( n^2 *logn)

#include

using namespace std;
typedef long long ll;
#define debug(x) cout<<#x<<" is "<

const int maxn=1e5+5;

struct edge{
    int x;
    int y;
    int z;
    int t;
    int id;
    bool operator<(const struct edge &aa)const{
        return y>aa.y;
    }
}h[maxn],v[maxn];

bool cmp(struct edge aa,struct edge bb){
    return aa.x<bb.x;
}

int maxx,tim,wq[maxn];
ll sum[maxn];

void update(int x,int y){
    while(x<=maxx){
        if(wq[x]!=tim){
            wq[x]=tim;
            sum[x]=0;
        }
        sum[x]+=y;
        x+=(x&(-x));
    }
}

ll query(int x,int y){
    ll ac=0;
    while(x){
        if(wq[x]!=tim){
            wq[x]=tim;
            sum[x]=0;
        }
        ac-=sum[x];
        x-=(x&(-x));
    }
    while(y){
        if(wq[y]!=tim){
            wq[y]=tim;
            sum[y]=0;
        }
        ac+=sum[y];
        y-=(y&(-y));
    }
    return ac;
}

int main(){
    int n;
    scanf("%d",&n);
    int t1,t2;
    t1=t2=0;
    for(int i=1;i<=n;i++){
        int a,b,c,d;
        scanf("%d%d%d%d",&a,&b,&c,&d);
        a+=5001;
        b+=5001;
        c+=5001;
        d+=5001;
        if(b==d){
            h[++t1].x=b;
            h[t1].y=b;
            h[t1].z=min(a,c);
            h[t1].t=max(a,c);
            h[t1].id=i;
        }
        else{
            v[++t2].x=min(b,d);
            v[t2].y=max(b,d);
            v[t2].z=a;
            v[t2].t=a;
            v[t2].id=i;
        }
        maxx=max(max(a,c),maxx);
    }
    sort(h+1,h+1+t1,cmp);
    sort(v+1,v+1+t2,cmp);
    ll ans=0;
    for(int i=1;i<=t1;i++){
        int w=1;
        tim++;
        priority_queue<struct edge>pq;
        while(w<=t2&&v[w].x<=h[i].x){
            pq.push(v[w]);
            update(v[w].z,1);
            w++;
        }
        for(int j=i+1;j<=t1;j++){
            while(!pq.empty()&&(pq.top()).y<h[j].y){
                update(pq.top().z,-1);
                pq.pop();
            }
            ll ww=query(max(h[i].z,h[j].z)-1,min(h[i].t,h[j].t));
            ww=max(ww,0ll);
            ans+=ww*(ww-1)/2;
        }
    }
    printf("%lld\n",ans);
    return 0;
}

你可能感兴趣的:(优先队列,树状数组)