题目
猫猫 TOM 和小老鼠 JERRY 最近又较量上了,但是毕竟都是成年人,他们已经不喜欢再玩那种你追我赶的游戏,现在他们喜欢玩统计。
最近,TOM 老猫查阅到一个人类称之为“逆序对”的东西,这东西是这样定义的:对于给定的一段正整数序列,逆序对就是序列中 ai>aj 且 i<j 的有序对。知道这概念后,他们就比赛谁先算出给定的一段正整数序列中逆序对的数目。注意序列中可能有重复数字。
Update:数据已加强。
Input
第一行,一个数 n,表示序列中有 n个数。
第二行 n 个数,表示给定的序列。序列中每个数字不超过 。
Output
输出序列中逆序对的数目。
思路
正序扫描原序列,每扫到一个元素x,就在树状数组tree[x]上加一,同时ans加上在x后面的元素个数(两个前缀和相减就好),因为我们是正序扫描,在x后面的元素比x大,又比x早出现,属于逆序对。由于题目数据较大,因此用了离散化。
代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<bitset>
#include<set>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS 1
#define ll long long
#define pub push_back
#define pob pop_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define inf 2e9
#define llf 1e18
#define endl "\n"
const ll mod = 1e6 + 7;
ll qpow(ll base, ll power)
{
ll res = 1;
while (power > 0)
{
if (power & 1) res = base * res % mod;
power >>= 1;
base = base * base % mod;
}
return res;
}
ll gcd(ll a, ll b)
{
return b == 0 ? a : gcd(b, a % b);
}
ll lcm(ll a, ll b)
{
return a / gcd(a, b) * b;
}
double dis1(double x, double y, double x1, double y1)
{
return sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
}
double dis2(double x, double y, double z, double x1, double y1, double z1)
{
return sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1) + (z - z1) * (z - z1));
}
double chaji(double x1, double x2, double y1, double y2)
{
return x1 * y2 - x2 * y1;
}
ll n;
vector<ll> tree(500010);
ll lowbit(ll x)
{
return x & (-x);
}
void add(ll i, ll a)
{
while (i <= n)
{
tree[i] += a;
i += lowbit(i);
}
}
ll search(ll i)
{
ll ans = 0;
while (i != 0)
{
ans += tree[i];
i -= lowbit(i);
}
return ans;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n;
vector<pll> ve(n + 1);
vector<ll> t(n + 1);
ll ans = 0;
for (ll i = 1; i <= n; i++)
{
cin >> ve[i].first;
ve[i].second = i;
}
sort(ve.begin() + 1, ve.end());
for (ll i = 1; i <= n; i++)
{
t[ve[i].second] = i;
}
for (ll i = 1; i <= n; i++)
{
ans += search(n) - search(t[i]);
add(t[i], 1);
}
cout << ans;
}