您的位置:首页 > 其它

51Nod - 1107 斜率小于0的连线数量(逆序对)

2017-08-14 13:36 204 查看
1107 斜率小于0的连线数量

基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题

二维平面上N个点之间共有C(n,2)条连线。求这C(n,2)条线中斜率小于0的线的数量。

二维平面上的一个点,根据对应的X Y坐标可以表示为(X,Y)。例如:(2,3) (3,4) (1,5) (4,6),其中(1,5)同(2,3)(3,4)的连线斜率 < 0,因此斜率小于0的连线数量为2。

Input

第1行:1个数N,N为点的数量(0 <= N <= 50000)

第2 - N + 1行:N个点的坐标,坐标为整数。(0 <= X[i], Y[i] <= 10^9)

Output

输出斜率小于0的连线的数量。(2,3) (2,4)以及(2,3) (3,3)这2种情况不统计在内。

Input示例

4

2 3

3 4

1 5

4 6

Output示例

2

李陶冶 (题目提供者)

题意:

给定n个点,求斜率为负数的直线数量,然后去掉斜率为无穷的情况

按照x为第一关键字,y为第二关键字sort,然后把y单独分离开来求逆序对就是所求答案(可以画一下图画理解一下)

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long LL;
const int maxn=5e5+5;

LL ans;
int n,b[maxn],a[maxn];

struct point
{
int x,y;
bool operator <(const point &B)const
{
return x<B.x||(x==B.x&&y<B.y);
}
}c[maxn];

inline void merge(int l,int r)
{
if(l>=r)return;
int mid=(l+r)>>1;
merge(l,mid);
merge(mid+1,r);
int L=l,R=mid+1;
int cnt=l;
while(L<=mid||R<=r)
{
if(L>mid||(a[R]<a[L]&&R<=r))
{
b[cnt++]=a[R++];
ans+=mid-L+1;
}
else b[cnt++]=a[L++];
}
for(int i=l;i<=r;++i)a[i]=b[i];
}

int main()
{
while(~scanf("%d",&n))
{
for(int i=1;i<=n;++i)scanf("%d%d",&c[i].x,&c[i].y);
sort(c+1,c+1+n);
for(int i=1;i<=n;++i)a[i]=c[i].y;
ans=0;
merge(1,n);
printf("%lld\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: