51nod 1107(树状数组、逆序数)

题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1107

思路:其实就是升级版的逆序数,x坐标当作位置,y坐标当作数值val,只是可能有相等的数,稍作修改即可。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5e4 + 3;
int lowbit(int x)
{
    return x & (-x);
}
struct node
{
    int x,y,order;
}q[N];
int a[N],c[N],n;
bool cmp1(node t1,node t2)
{
    if(t1.x != t2.x)
        return t1.x < t2.x;
    return t1.y < t2.y;
}
bool cmp2(node t1,node t2)
{
    if(t1.y != t2.y)
        return t1.y < t2.y;
    return t1.order < t2.order;
}
void update(int pos,int val)
{
    for(int i = pos; i <= n; i += lowbit(i))
        c[i] += val;
}
int sum(int pos)
{
    int ans = 0;
    for(int i = pos; i > 0; i -= lowbit(i))
        ans += c[i];
    return ans;
}
int main()
{
    scanf("%d",&n);
    for(int i = 1; i <= n; i++)
        scanf("%d %d",&q[i].x,&q[i].y);
    sort(q+1,q+n+1,cmp1);
    for(int i = 1; i <= n; i++)
        q[i].order = i;
    sort(q+1,q+n+1,cmp2);
    for(int i = 1; i <= n; i++)
        a[q[i].order] = i;
    int ans = 0;
    for(int i = 1; i <= n; i++)
    {
        update(a[i],1);
        ans += i - sum(a[i]);
    }
    printf("%d\n",ans);
    return 0;
}

 

posted on 2017-01-27 01:06  polarday  阅读(151)  评论(0编辑  收藏  举报

导航