/*Sherlock and Watson and Adler*/
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<cmath>
#include<complex>
#include<string>
#include<algorithm>
#include<iostream>
#define eps 1e-9
#define LL long long
#define bitnum(a) __builtin_popcount(a)
#define PI acos(-1.0)
using namespace std;
const int N = 100005;
const int M = 2001;
const int inf = 1000000007;
const int mod = 1000000007;
struct horizontal
{
int x,y,type;
}s[2*N];
struct node
{
int x1,y1,x2,y2;
}point[N];
int a[4*N],c[4*N],p;
bool cmp(horizontal x,horizontal y)
{
if(x.x!=y.x)
return x.x<y.x;
return x.type<y.type;
}
bool cmpz(node x,node y)
{
return x.x1<y.x1;
}
int lowbit(int t)
{//计算c[t]展开的项数
return t&(-t);
}
void update(int i,int x)
{
while(i<=p)
{
c[i]=c[i]+x;
i+=lowbit(i);
}
}
int Sum(int n) //求前n项的和.
{
int sum=0;
while(n>0)
{
sum+=c[n];
n-=lowbit(n);
}
return sum;
}
int main()
{
int t,n,i,j,q,k;
__int64 ans;
scanf("%d",&t);
while(t--)
{
ans=0;
q=p=k=0;
memset(c,0,sizeof(c));
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d%d%d%d",&point[i].x1,&point[i].y1,&point[i].x2,&point[i].y2);
if(point[i].x1>point[i].x2||point[i].y1>point[i].y2)
{
swap(point[i].x1,point[i].x2);
swap(point[i].y1,point[i].y2);
}
a[p++]=point[i].x1;
a[p++]=point[i].y1;
a[p++]=point[i].x2;
a[p++]=point[i].y2;
}
sort(a,a+p);
p=unique(a,a+p)-a;
for(i=0;i<n;i++)
{
point[i].x1=lower_bound(a,a+p,point[i].x1)-a+1;//坐标离散化
point[i].x2=lower_bound(a,a+p,point[i].x2)-a+1;
point[i].y1=lower_bound(a,a+p,point[i].y1)-a+1;
point[i].y2=lower_bound(a,a+p,point[i].y2)-a+1;
//printf("%d %d %d %d\n",point[i].x1,point[i].y1,point[i].x2,point[i].y2);
if(point[i].y1==point[i].y2)//该线段为横向线段,只保留线段端点
{
s[q].x=point[i].x1;
s[q].y=point[i].y1;
s[q++].type=0;
s[q].x=point[i].x2;
s[q].y=point[i].y2;
s[q++].type=1;
}
else//该线段为竖向线段,保留整条线段
point[k++]=point[i];
}
sort(s,s+q,cmp);//按x从小到大排序
sort(point,point+k,cmpz);
for(j=i=0;i<k;i++)//暴力枚举竖向线段
{
for(;j<q&&(s[j].x<point[i].x1||s[j].x==point[i].x1&&s[j].type!=1);j++)//处理所有横坐标小于当前竖向线段的横向线段端点或横坐标等于当前竖向线段的横向线段左端点
if(s[j].type)//若为右端点,更新树状数组,-1操作
update(s[j].y,-1);
else//若为左端点,更新树状数组,+1操作
update(s[j].y,1);
ans+=Sum(point[i].y2)-Sum(point[i].y1-1);//所有纵坐标<=y2的横向线段数-纵坐标<y1的横向线段数即为当前竖向线段与横向线段的交点数
}
printf("%I64d\n",ans);
}
return 0;
}
hdu 5682 Counting Intersections 离散化+树状数组
最新推荐文章于 2019-08-19 19:53:00 发布