题目描述
猫猫 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;
}