逆序对定义
在计算机科学和离散数学中,逆序对是指序列中的两个元素,它们的顺序与它们在原始序列中的顺序相反。更具体地说,对于一个包含 n n n 个元素的序列,逆序对是指满足 a i > a j , i < j a_i>a_j,i<j ai>aj,i<j 的索引对 ( i , j ) (i, j) (i,j) 的数量,其中 a i a_i ai 和 a j a_j aj 分别表示序列中的第 i i i 和第 j j j 个元素。
思路
树状数组表征值域,我们只需要对包含第 i i i 个数的数组 + 1 +1 +1,每次统计一下 i + 1 → N i+1 \to N i+1→N 出现的次数即可。但是面对这种问题一般需要对数据进行离散化。
离散化定义
在离散数学和计算机科学中,离散化是指将连续的数据或变量转换为离散的值或类别的过程。这个过程通常涉及将连续的范围划分为若干个间隔或区间,并为每个区间分配一个离散的值或类别标签。离散化的目的通常是简化数据处理或分析,以及减少数据的复杂性。例如,在数据挖掘中,离散化可以用来将连续的数值特征转换为分类特征,以便更好地应用分类算法。
代码
cin >> n;
vector<int> a(n);
for (int &i : a)
cin >> i;
vector<int> b(all(a));
sort(all(b));
b.erase(unique(all(b)), b.end());
int m = b.size();
在我们查询时,只需要查询 a i a_i ai 在离散化数组中的位置。
int pos = lower_bound(all(b), a[i]) - b.begin() + 1;
代码
#include <bits/stdc++.h>
using namespace std;
#define all(x) x.begin(), x.end()
#define bit1(x) __builtin_popcount(x)
#define Pqueue priority_queue
#define lc p << 1
#define rc p << 1 | 1
#define IOS ios::sync_with_stdio(false), cin.tie(0);
#define fi first
#define se second
#define lowbit(x) (x & -x)
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<ll, ll> PII;
const ll mod = 1000000007;
const ll N = 1e6 + 10;
const ld eps = 1e-9;
const ll inf = 1e18;
const ll P = 131;
const ll dir[8][2] = {1, 0, 0, 1, -1, 0, 0, -1, 1, 1, 1, -1, -1, 1, -1, -1};
int n, tr[N];
int t, r;
void change(int x, int k)
{
while (x <= n)
{
tr[x] += k;
x += lowbit(x);
}
}
int query(int x)
{
int ans = 0;
while (x)
{
ans += tr[x];
x -= lowbit(x);
}
return ans;
}
void solve()
{
cin >> n;
vector<int> a(n);
for (int &i : a)
cin >> i;
vector<int> b(all(a));
sort(all(b));
b.erase(unique(all(b)), b.end());
int m = b.size();
// cout << m << "\n";
// for (auto i : b)
// cout << i << "\n";
ll ans = 0;
// cout << a.size();
for (int i = 0; i < n; i++)
{
int pos = lower_bound(all(b), a[i]) - b.begin() + 1;
ans += query(n) - query(pos);
change(pos, 1);
}
cout << ans << "\n";
}
int main()
{
int T = 1;
// cin>>T;
while (T--)
solve();
return 0;
}
/*
oxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxox
x o
o _/_/_/_/ _/ x
x _/ o
o _/_/_/_/ _/ _/_/ _/_/ _/_/_/ _/_/ _/_/_/ _/_/ _/_/_/ _/ _/ _/ x
x _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ o
o _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/ x
x _/ _/ _/_/ _/ _/ _/ _/_/_/ _/_/ _/ _/ _/ _/ _/ o
o _/ _/ _/ x
x _/ _/_/ _/ o
o x
xoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxo
*/```