题目
样例
输入
4 4 3 2 1
输出
6
思路
利用性质:数列中所有元素的逆序数之和等于交换相邻两数把数列变为有序的最小步数。
“相邻的两节车厢交换”让人想到了冒泡排序,而且实际上每次交换都会使得逆序对数减1,也就是说排序的过程就是减少逆序对的过程。因此可以用冒泡排序来做,但题目只要我们统计输出最小旋转次数,即逆序对数,因此统计逆序对数即可。
代码
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
//source:
const int N = 10010;
int a[N], res = 0;
int n;
int main()
{
// IOS;
cin >> n;
for (int i = 1; i <= n; i ++)
{
cin >> a[i];
}
//统计每个元素a[i] 能和多少个元素组成逆序对
for (int i = 1; i < n; i ++)
{
for (int j = i + 1;j <= n; j ++)
{
if (a[i] > a[j])res ++;
}
}
cout << res;
return 0;
}