51Nod 1107 斜率小于0的连线数量

来源:互联网 发布:windows 执行snmpwalk 编辑:程序博客网 时间:2024/06/01 10:50

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

#include<algorithm>#include<cstdio>#include<cstring>using namespace std;#define LL long long#define INF 1000000007#define lowbit(x) (x&(-x))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 += lowbit(k);    }    LL sum(int k){//a[1]+..+a[k]        LL Ans = 0;        while(k) Ans += c[k],k -= lowbit(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() {    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;}

如果两个点构成的直线斜率小于零,那么一个点肯定在另外一个点的右下方,那么对横坐标排个序,求一下纵坐标的逆序对。。

原创粉丝点击