1107 斜率小于0的连线数量

二维平面上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
题解:先维护升序的y,进行离散化。以升序x,相同x的情况则升序y排序。然后遍历n个点,每次在bit中查找小于等于该点y值对应离散化的值的数量,因为是由x升序遍历的,所以找到的数量是不符合要求的那部分,用ans减去。将该点y值对应离散化的值维护进bit。ans初始化为c(n,2)。最终的ans便是答案。

代码:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <cmath>
#include <ctime>
using namespace std;
typedef long long ll;
typedef pair<ll, int> P;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-10;
const int maxn = 5e4+7;
const int mod = 1e9+7;

int n;
struct G{
    int x,y,id;
    G(int x,int y,int id):x(x),y(y),id(id){}
    G(){}
}s[maxn];

int d[maxn];
ll b[maxn];
void ins(int v){
    while(v<=n){
        b[v]+=1;
        v = v+(v&-v);
    }
}
ll sum(int v){
    ll res = 0;
    while(v>0){
        res+=b[v];
        v-=(v&-v);
    }
    return res;
}
bool cmp1(G a,G b){
    return a.y==b.y?a.x<b.x:a.y<b.y;
}
bool cmp2(G a,G b){
    return a.x==b.x?a.y<b.y:a.x<b.x;
}


int main()
{
    scanf("%d",&n);
    memset(b,0,sizeof(b));
    for(int i = 1;i <= n;i++){
        int x,y;
        scanf("%d %d",&x,&y);
        s[i] = G(x,y,i);
    }
    sort(s+1,s+n+1,cmp1);
    for(int i = 1;i <= n;i++){
        d[s[i].id] = i;
    }
    sort(s+1,s+n+1,cmp2);
    ll ans = 1ll*n*(n-1)/2;
    for(int i = 1;i <= n;i++){
        ans-=sum(d[s[i].id]);
        ins(d[s[i].id]);
    }
    printf("%lld\n",ans);
    return 0;
}
涉及的知识:

1、离散化。

2、bit。

总结:

一开始想的的二分,后来是线段树+离散化,最后才用了bit。相对来说,在处理求前缀问题上用bit更加简单方便。

好久没打bit,差点记错。

(x&-x):取出x的二进制的最后一个1。

x = x-(x&-x):bit的求和。

x = x+(x&-x):上一步相反,bit插入。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值