HDU 2689 Sort it(逆序对-BIT)

Description
给出一个长度为n的序列,输出其逆序对数
Input
多组输入,每组用例第一行为一整数n表示序列长度,第二行n个整数表示该序列,以文件尾结束输入
Output
对于每组用例,输出其逆序对数
Sample Input
3
1 2 3
4
4 3 2 1
Sample Output
0
6
Solution
树状数组求逆序对
Code

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<string>
using namespace std;
#define maxn 1111
int num[maxn];
int bit[maxn];
struct node
{
    int val,pos;
}a[maxn];
int cmp(node x,node y)
{
    if(x.val!=y.val)return x.val<y.val;
    return x.pos<y.pos;
}
void init()//初始化 
{
    memset(bit,0,sizeof(bit));
} 
int lowbit(int x)//求lowbit 
{
    return x&(-x);
}
void update(int x,int v)//单点更新 
{
    while(x<=maxn)
    {
        bit[x]+=v;
        x+=lowbit(x);
    }
}
int getsum(int x) 
{
    int ans=0;
    while(x>0)
    {
        ans+=bit[x];
        x-=lowbit(x);
    }
    return ans; 
}
int solve(int num[],int n)//num表示要求逆序对的序列(从0开始),n表示序列长度 
{
    init();
    for(int i=1;i<=n;i++)
    {
        a[i].val=num[i-1];
        a[i].pos=i;
    }
    sort(a+1,a+n+1,cmp);
    int ans=0; 
    for(int i=n;i>0;i--)
    {
        ans+=getsum(a[i].pos);
        update(a[i].pos,1);
    }
    return ans;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=0;i<n;i++)    
            scanf("%d",&num[i]);
        int ans=solve(num,n);
        printf("%d\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值