HDU 1394 Minimum Inversion Number

The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy i < j and ai > aj.

For a given sequence of numbers a1, a2, ..., an, if we move the first m >= 0 numbers to the end of the seqence, we will obtain another sequence. There are totally n such sequences as the following:

a1, a2, ..., an-1, an (where m = 0 - the initial seqence)
a2, a3, ..., an, a1 (where m = 1)
a3, a4, ..., an, a1, a2 (where m = 2)
...
an, a1, a2, ..., an-1 (where m = n-1)

You are asked to write a program to find the minimum inversion number out of the above sequences.

 

这题数据规模好小,感觉写个n^2的也能过?首先第一步就是求逆序对,方法太多了,树状数组几行的事情,线段树稍微有点麻烦。然后题目要求通过将第一个换到最后一个位置,得到新的逆序对个数,然后算出最小的逆序对个数。将i这个数字放在最后,会增加n-i个逆序对,并且减少i-1个逆序对。所以是水题无疑了。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 5e3;
int arr[4 * maxn + 5], a[maxn + 5], n, sum, res;
inline void Push_Up(int index) {
	arr[index] = arr[2 * index + 1] + arr[2 * index];
}
void Update(int index, int L, int R, int pos) {
	if (L == R) {
		arr[index]++;
		return;
	}
	int mid = L + R >> 1;
	if (mid >= pos)Update(2 * index, L, mid, pos);
	else Update(2 * index + 1, mid + 1, R, pos);
	Push_Up(index);
}
int Query(int index, int L, int R, int QL, int QR) {
	if (L >= QL&&R <= QR)return arr[index];
	int mid = L + R >> 1, res = 0;
	if (mid >= QL)res += Query(2 * index, L, mid, QL, QR);
	if (QR > mid)res += Query(2 * index + 1, mid + 1, R, QL, QR);
	return res;
}
int main(void)
{
	while (~scanf("%d", &n)) {
		memset(arr, 0, sizeof(arr));
		sum = 0;
		for (int i = 1; i <= n; ++i)scanf("%d", &a[i]), a[i]++;
		sum = 0;
		for (int i = 1; i <= n; ++i) {
			Update(1, 1, n, a[i]);
			sum += Query(1, 1, n, a[i] + 1, n);
		}
		res = sum;
		for (int i = 1; i <= n; ++i) {
			sum += n - a[i];
			sum -= a[i] - 1;
			res = min(res, sum);
		}
		printf("%d\n", res);
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值