灯塔(LightHouse)
Description
As shown in the following figure, If another lighthouse is in gray area, they can beacon each other.
For example, in following figure, (B, R) is a pair of lighthouse which can beacon each other, while (B, G), (R, G) are NOT.
Input
1st line: N
2nd ~ (N + 1)th line: each line is X Y, means a lighthouse is on the point (X, Y).
Output
How many pairs of lighthourses can beacon each other
( For every lighthouses, X coordinates won’t be the same , Y coordinates won’t be the same )
Example
Input
3
2 2
4 3
5 1
Output
1
Restrictions
For 90% test cases: 1 <= n <= 3 * 105
For 95% test cases: 1 <= n <= 106
For all test cases: 1 <= n <= 4 * 106
For every lighthouses, X coordinates won’t be the same , Y coordinates won’t be the same.
1 <= x, y <= 10^8
Time: 2 sec
Memory: 256 MB
题意:在一堆坐标里找x和y同时小于另一个坐标的一对坐标的对数。
思路:先按x排序后数数有多少y是按照顺序出现的。一开始不知道怎么整,后来学会归并排序可以nlogn求顺序对。1200ms过
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=4e6+50;
struct point{
int x,y;
}q[maxn];
int n=5;
long long ans=0;
int y[maxn];
int b[maxn];
point bb[maxn];
void mergeesort(int a[],int l,int m,int r){
int pb=0;
int p1=l;
int p2=m+1;
while(p1<=m&&p2<=r){
// printf("p1=%d p2=%d l=%d m=%d r=%d ans+=%d ans=%d\n",p1,p2,l,m,r,a[p1]<a[p2]?(r-m-(p2-m-1)):0,ans);
if(a[p1]<a[p2]){
b[pb++]=a[p1++];
ans+=r-m-(p2-m-1);
}
else
b[pb++]=a[p2++];
}
while(p1<=m){
b[pb++]=a[p1++];
}
while(p2<=r) b[pb++]=a[p2++];
for(int i=0;i<r-l+1;i++)
a[i+l]=b[i];
}
void mergee(int p[],int l,int r){
if(l==r)
return ;
int m=(l+r)>>1;
mergee(p,l,m);
mergee(p,m+1,r);
mergeesort(p,l,m,r);
}
void mmergeesort(point a[],int l,int m,int r){
int pb=0;
int p1=l;
int p2=m+1;
while(p1<=m&&p2<=r){
// printf("p1=%d p2=%d l=%d m=%d r=%d ans+=%d ans=%d\n",p1,p2,l,m,r,a[p1]<a[p2]?(r-m-(p2-m-1)):0,ans);
if(a[p1].x<a[p2].x||(a[p1].x==a[p2].x&&a[p1].y<a[p2].y)){
bb[pb++]=a[p1++];
}
else
bb[pb++]=a[p2++];
}
while(p1<=m){
bb[pb++]=a[p1++];
}
while(p2<=r) bb[pb++]=a[p2++];
for(int i=0;i<r-l+1;i++)
a[i+l]=bb[i];
}
void mmerge(point p[],int l,int r){
if(l==r)
return ;
int m=(l+r)>>1;
mmerge(p,l,m);
mmerge(p,m+1,r);
mmergeesort(p,l,m,r);
}
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d%d",&q[i].x,&q[i].y);
}
mmerge(q,0,n-1);
for(int i=0;i<n;i++){
y[i]=q[i].y;
}
mergee(y,0,n-1);
printf("%lld",ans);
return 0;
}