P1908 逆序对(树状数组)

P1908

题目描述
猫猫 TOM 和小老鼠 JERRY 最近又较量上了,但是毕竟都是成年人,他们已经不喜欢再玩那种你追我赶的游戏,现在他们喜欢玩统计。

最近,TOM 老猫查阅到一个人类称之为“逆序对”的东西,这东西是这样定义的:对于给定的一段正整数序列,逆序对就是序列中 ai>aj且 i<j的有序对。知道这概念后,他们就比赛谁先算出给定的一段正整数序列中逆序对的数目。注意序列中可能有重复数字。

Update:数据已加强。

输入格式
第一行,一个数 nn,表示序列中有 nn个数。

第二行 nn 个数,表示给定的序列。序列中每个数字不超过 10^910
9

输出格式
输出序列中逆序对的数目。

#include <iostream>
#include <queue>
#include <stack>
#include <cstring>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 5 * 1e5 + 5;
ll a[maxn], n;
ll ch[maxn];
struct node
{
  int val, num;
} t[maxn];
int lowbit(int x)
{
  return x & (-x);
}
bool cmp(node t1, node t2)
{
  if (t1.val != t2.val)
    return t1.val < t2.val;
  return t1.num < t2.num;
}
void change(int pos, int x)
{
  while (pos <= n)
  {
    a[pos] += x;
    pos += lowbit(pos);
  }
}
int sum(int n)
{
  int res = 0;
  while (n)
  {
    res += a[n];
    n -= lowbit(n);
  }
  return res;
}
int main()
{
  cin >> n;
  ll ans = 0;
  for (int i = 1; i <= n; i++)
  {
    cin >> t[i].val;
    t[i].num = i;
  }
  stable_sort(t + 1, t + n + 1, cmp);
  for (int i = 1; i <= n; i++)
  {
    ch[t[i].num] = i;
  }
  for (int i = 1; i <= n; i++)
  {
    change(ch[i], 1);
    ans += i - sum(ch[i]);
  }
  cout << ans;
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值