数据结构(上)(自主模式) 灯塔(LightHouse)

灯塔(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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值