51NOD 1107 斜率小于0的连线数量 坐标离散化+树状数组

7 篇文章 0 订阅
3 篇文章 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的连线数量为2Input1行:1个数NN为点的数量(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

不难发现 当x1 < x2 且 y1 > y2(x1,y1)与(x2,y2)的斜率 < 0
对所有点排序
按x从大到小 , x相同按 y从大到小顺序遍历 ( 排除(1,2)与(1,3)这样的情况 )
BIT记录y值 <= 某个值的点有多少个
对点i y坐标<=y-1的点的数量就是与点i斜率小于0的数量
y的最大值太大 所以处理前要进行一次坐标离散化


#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<vector>
#include<deque>
#include<queue>
#include<algorithm>
#include<set>
#include<map>
#include<stack>
#include<time.h>
#include<math.h>
#include<list>
#include<cstring>
#include<fstream>
//#include<memory.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair<int,int>
#define INF 1000000007
#define pll pair<ll,ll>
#define pid pair<int,double>

const int N = 50000 + 5;
const int MAX = N;

struct BIT{
    int n;
    ll c[MAX];
    BIT(int n){//a[1]....a[n]
        this->n = n;
        for(int i=1;i<=n;++i){
            c[i]=0;
        }
    }
    void add(int k, int num){//a[k] + num
        while(k<=n){
            c[k]+=num;
            k+=k&(-k);
        }
    }
    ll sum(int k){//a[1]+..+a[k]
        ll ans=0;
        while(k){
            ans+=c[k];
            k-=k&(-k);
        }
        return ans;
    }
};

struct P{
    int x,y;
}p[N];

bool compX(const P&a,const P&b){
    return a.x<b.x;
}

bool compY(const P&a,const P&b){
    return a.y<b.y;
}

void initXY(int n){//坐标离散化 此处只需要处理y坐标即可
    sort(p,p+n,compY);
    int last=p[0].y;
    p[0].y=1;
    for(int i=1;i<n;++i){
        int tmp=p[i].y;
        p[i].y=p[i].y==last?p[i-1].y:p[i-1].y+1;
        last=tmp;
    }
    stable_sort(p,p+n,compX);
}

ll slove(int n){
    ll ans=0;
    BIT bit(MAX-3);
    for(int i=n-1;i>=0;--i){
        ans+=bit.sum(p[i].y-1);
        bit.add(p[i].y,1);
    }
    return ans;
}

int main()
{
    //freopen("/home/lu/文档/r.txt","r",stdin);
    //freopen("/home/lu/文档/w.txt","w",stdout);
    int n;
    while(~scanf("%d",&n)){
        for(int i=0;i<n;++i){
            scanf("%d%d",&p[i].x,&p[i].y);
        }
        initXY(n);
        printf("%lld\n",slove(n));
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值