HDU5862(树状数组好题)

来源:互联网 发布:树莓派 gpio 编程 编辑:程序博客网 时间:2024/06/08 06:52

题意:给一些平行坐标轴的线段,。统计相交数

题解:可以这样考虑,把所有与x轴平行的线段存起来,用来枚举。把与y轴平行的线段的左右端点存起来。这样在枚举x线段时。就需要看x线段的左端点左边有多少,右端点有多少,相减就是中间重合的。如何维护这些数据呢?当然就得用树状数组了。,简单粗暴

#include<stdio.h>#include<stdlib.h>#include<string.h>#include<math.h>#include<iostream>#include<algorithm>#include<stack>#include<queue>#include<vector>#include<set>#include<map>#include<string>using namespace std;typedef long long ll;typedef pair<int,int>P;const int INF=0x3f3f3f3f;const ll INFF=0x3f3f3f3f3f3f3f3f;const double pi=acos(-1.0);const double eps=1e-9;ll bit[200010];struct node1{    int x1,x2,y;    int id;}node[200010];int ax[200010];bool cmp(node1 p1,node1 p2){    if(p1.y!=p2.y)        return p1.y<p2.y;    return p1.id>p2.id;}ll sum(int i){    ll ans=0;    while(i)    {        ans+=bit[i];        i-=(i&-i);    }    return ans;}void add(int i,int x,int len){    while(i<=len)    {        bit[i]+=x;        i+=i&(-i);    }}int main(){    int t;scanf("%d",&t);    while(t--)    {        int n;scanf("%d",&n);        int cnt=0,tmp=0;        for(int i=1;i<=n;i++)        {            int x1,x2,y1,y2;scanf("%d%d%d%d",&x1,&y1,&x2,&y2);            if (x1 > x2) swap(x1, x2);            if (y1 > y2) swap(y1, y2);            if(x1==x2)            {                ax[cnt++]=x1;                node[tmp].x1=x1;node[tmp].y=y1;node[tmp++].id=1;                node[tmp].x1=x2;node[tmp].y=y2;node[tmp++].id=-1;            }            else            {                ax[cnt++]=x1;ax[cnt++]=x2;                node[tmp].x1=x1;                node[tmp].x2=x2;                node[tmp].y=y2;                node[tmp++].id=0;            }        }        sort(ax,ax+cnt);        int len=unique(ax,ax+cnt)-ax;        sort(node,node+tmp,cmp);        memset(bit,0,sizeof(bit));        ll ans=0;        for(int i=0;i<tmp;i++)        {            if(node[i].id==0)            {                int l=lower_bound(ax,ax+len,node[i].x1)-ax+1;                int r=lower_bound(ax,ax+len,node[i].x2)-ax+1;                ans+=sum(r)-sum(l-1);            }            else            {                int l=lower_bound(ax,ax+len,node[i].x1)-ax+1;                add(l,node[i].id,len+1);            }        }        printf("%lld\n",ans);    }    return 0;}


原创粉丝点击