思路:
此题实际上是求逆序对的个数,每交换一次就减少一个逆序对。
使用树状数组求逆序对个数。
步骤:1.离散化:例:5 4 1 2 999 -> 2 3 5 4 1 (按大小进行标号)
2.求顺序对的个数
3.求逆序对的个数
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int a[N], b[N], c[N], n; // b:原数组,a:离散化后的数组,c:树状数组
long long ans;
int lowbit(int x)
{
return x & -x;
}
void add(int i, int x)
{
for (; i <= n; i += lowbit(i))
{
c[i] += x;
}
}
int sum(int i)
{
int res = 0;
for (; i > 0; i -= lowbit(i))
{
res += c[i];
}
return res;
}
bool cmp(int x, int y)
{
if (b[x] == b[y])
{
return x > y;
}
return b[x] > b[y];
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> b[i];
a[i] = i;
}
sort(a + 1, a + n + 1, cmp);
for (int i = 1; i <= n; i++)
{
add(a[i], 1);
ans += sum(a[i] - 1);
}
cout << ans << endl;
return 0;
}