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

51nod 1107 斜率小于0的连线数量_第1张图片

按x坐标排序,求y坐标的逆序对 归并排序求逆序对:

#include
#include
using namespace std;

const int maxn = 1e5 + 5;
struct p{
    int x, y;
} a[maxn];
int b[maxn];
long long ans = 0;

int cmp(p a, p b){
    return a.x < b.x || a.x == b.x && a.y < b.y;
}

void msort(int l, int r){
    if(l == r) return;
    int mid = (l + r) >> 1;
    msort(l, mid);
    msort(mid + 1, r);
    int i = l, j = mid + 1, tot = l;
    while(i <= mid && j <= r){
        if(a[i].y <= a[j].y){
            b[tot++] = a[i++].y;
        }else{
            ans += (long long)mid - i + 1;
            b[tot++] = a[j++].y;
        }
    }
    while(i <= mid){
        b[tot++] = a[i++].y;
    }
    while(j <= r){
        b[tot++] = a[j++].y;
    }
    for(int i = l; i <= r; i++){
        a[i].y = b[i];
    }
}

int main(){
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++){
        scanf("%d%d", &a[i].x, &a[i].y);
    }
    sort(a + 1, a + n + 1, cmp);
    msort(1, n);
    printf("%lld\n", ans);
}

你可能感兴趣的:(51nod)