Description
给出若干水平竖直的线段,求交点个数
Input
第一行一整数T表示用例组数,每组用例首先输入一整数n表示线段个数,之后四个整数x1,y1,x2,y2表示线段两端点的坐标,保证任意一条线段不会被其他线段所包含(1<=n<=10^5,所有点坐标的绝对值不超过1e9)
Output
对于每组用例,输出水平线与竖直线的交点个数
Sample Input
2
4
1 0 1 3
2 0 2 3
0 1 3 1
0 2 3 2
4
0 0 2 0
3 0 3 2
3 3 1 3
0 3 0 2
Sample Output
4
0
Solution
扫描线,首先给所有坐标离散化,扫描线从下到上扫,对于每个纵坐标y,如果对于某些横坐标x,(x,y)是某些竖直线段的下端点,则在树状数组x位置插入1表示之后一段时间这个位置新加了一条竖直线段;如果(x,y-1)是某些竖直线段的上端点,那么在x位置插入-1表示消除这条竖直线段的影响;对于这个纵坐标上的所有线段(x1,y)->(x2,y),从树状数组中查询Sum(x2)-Sum(x1-1)即得到这条水平线段与其他竖直线段的交点个数,累加这个值即为答案
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define maxn 444444
int x[maxn],y[maxn];
int T,n,cntx,cnty;
struct node
{
int y0,y1,x0,x1,id;
node(){};
node(int _x0,int _y0,int _x1,int _y1)
{
x0=_x0,y0=_y0,x1=_x1,y1=_y1;
if(x0>x1)swap(x0,x1);
if(y0>y1)swap(y0,y1);
}
bool operator <(const node &b)const
{
if(id!=b.id)return id<b.id;
return y0<b.y0;
}
void out()
{
printf("%d %d %d %d\n",x0,y0,x1,y1);
}
}p[maxn];
struct BIT
{
#define lowbit(x) (x&(-x))
int b[maxn];
void init()
{
memset(b,0,sizeof(b));
}
void update(int x,int v)
{
while(x<maxn)
{
b[x]+=v;
x+=lowbit(x);
}
}
int sum(int x)
{
int ans=0;
while(x)
{
ans+=b[x];
x-=lowbit(x);
}
return ans;
}
}bit;
struct Node
{
int x,y,v;
bool operator<(const Node &b)const
{
if(y!=b.y)return y<b.y;
return x<b.x;
}
}a[maxn];
ll query(int l,int r)
{
return bit.sum(r)-bit.sum(l-1);
}
int main()
{
//freopen("in.txt","r",stdin);
scanf("%d",&T);
while(T--)
{
bit.init();
scanf("%d",&n);
int resx=0,resy=0;
for(int i=1;i<=n;i++)
{
int x0,y0,x1,y1;
scanf("%d%d%d%d",&x0,&y0,&x1,&y1);
x[resx++]=x0,x[resx++]=x1;
y[resy++]=y0,y[resy++]=y1;
p[i]=node(x0,y0,x1,y1);
if(x0==x1)p[i].id=0;//横线
else p[i].id=1;//竖线
}
sort(x,x+2*n),sort(y,y+2*n);
cntx=unique(x,x+2*n)-x;
cnty=unique(y,y+2*n)-y;
// printf("cntx=%d cnty=%d\n",cntx,cnty);
for(int i=1;i<=n;i++)
{
p[i].x0=lower_bound(x,x+cntx,p[i].x0)-x+1;
p[i].y0=lower_bound(y,y+cnty,p[i].y0)-y+1;
p[i].x1=lower_bound(x,x+cntx,p[i].x1)-x+1;
p[i].y1=lower_bound(y,y+cnty,p[i].y1)-y+1;
}
sort(p+1,p+n+1);
int pos=1,res=0;
while(p[pos].id==0&&pos<=n)
{
a[res].v=1,a[res].x=p[pos].x0,a[res].y=p[pos].y0,res++;
a[res].v=-1,a[res].x=p[pos].x0,a[res].y=p[pos].y1+1,res++;
pos++;
}
sort(a,a+res);
ll ans=0;
for(int i=1,j=pos,k=0;i<=cnty+1;i++)
{
while(a[k].y==i&&k<res)
{
bit.update(a[k].x,a[k].v);
k++;
}
while(p[j].y0==i&&j<=n)
{
ans+=query(p[j].x0,p[j].x1);
j++;
}
}
printf("%I64d\n",ans);
}
return 0;
}