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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值