HDU 1394 Minimum Inversion Number (求逆序对数)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1394


题意:一个由0..n-1组成的序列,每次可以把队首的元素移到队尾,求形成的n个序列中最小逆序对数目。


求逆序对数。

方法就是按序列顺序逐个读取元素,每次读取都要查询当前已读取元素中大于当前元素的个数,加到sum里,最后得到的sum即为原始数列的逆序数。

这样就是每读一个就插入到线段树或者树状数组里,查询当前元素+1到n-1中有多少数就行了。


求出了原始序列的逆序对数,从第一个元素开始往后枚举递推。 每次sum减去比它小的元素的个数,加上比它大的元素的个数。保留sum的最小值。


线段树求逆序对数:

#include <bits/stdc++.h>
using namespace std;
struct node{
	int l, r, m;
	int val;
};
const int maxn = 5010;
node T[maxn << 2];
int a[maxn];
void pushup(int rt)  {
	T[rt].val = T[rt << 1].val + T[rt << 1 | 1].val;
}
void build(int begin, int end, int rt) {
	T[rt].l = begin;
	T[rt].r = end;
	T[rt].m = (T[rt].l + T[rt].r) >> 1;
	if(begin == end) {
		T[rt].val = 0;
		return ;
	}
	build(T[rt].l, T[rt].m, rt << 1);
	build(T[rt].m + 1, T[rt].r, rt << 1 | 1);
	pushup(rt);
}
void update(int id, int add, int rt) {
	if(T[rt].l == T[rt].r) {
		T[rt].val += add;
		return ;
	}
	if(id <= T[rt].m) update(id, add, rt << 1);
	else update(id, add, rt << 1 | 1);
	pushup(rt);
}
int query(int L, int R, int rt) {
	if(L <= T[rt].l && T[rt].r <= R) {
		return T[rt].val;
	}
	if(R <= T[rt].m) return query(L, R, rt << 1);
	else if(L > T[rt].m) return query(L, R, rt << 1 | 1);
	else return query(L, T[rt].m, rt << 1) + query(T[rt].m + 1, R, rt << 1 | 1);
}

int main() {
	int n;
	while(~scanf("%d", &n)) {
		int sum = 0;
		build(0, n - 1, 1);
		for(int i = 0; i < n; i++) {
			scanf("%d", a + i);
			sum += query(a[i], n - 1, 1); //此处写a[i] + 1也可,不过要进行特判不是最大值 
			update(a[i], 1, 1);
		}
		int ans = sum;
		for(int i = 0; i < n - 1; i++) {
			sum -= a[i];
			sum += (n - a[i] - 1);
			if(sum < ans) ans = sum;
		}
		printf("%d\n", ans);
	}
	return 0;
}


### 使用分治算法计算数组中逆序对数量 #### 归并排序框架下的逆序对统计 在处理逆序对问题时,可以利用归并排序这一经典分治算法来高效解决。具体来说,在每次合并两个已排序序列的过程中,如果遇到左边的元素大于右边对应的元素,则意味着存在若干个逆序对,因为此时左边剩余未比较的所有元素都构成了新的逆序关系[^1]。 #### Python 实现代码示例 下面给出了一种基于上述思路的具体实现方式: ```python def merge_and_count_split_inv(B, C): i = j = inversions = 0 sorted_list = [] while i < len(B) and j < len(C): if B[i] <= C[j]: sorted_list.append(B[i]) i += 1 else: sorted_list.append(C[j]) j += 1 inversions += len(B) - i sorted_list.extend(B[i:]) sorted_list.extend(C[j:]) return sorted_list, inversions def sort_and_count(A): n = len(A) if n <= 1: return A, 0 mid = n // 2 (B, X) = sort_and_count(A[:mid]) (C, Y) = sort_and_count(A[mid:]) (D, Z) = merge_and_count_split_inv(B, C) return D, X + Y + Z def count_inversions(array): _, num_of_inversions = sort_and_count(array) return num_of_inversions ``` 此段程序通过`sort_and_count()`函数递归地分割输入列表直到单个元素;随后借助辅助函数`merge_and_count_split_inv()`完成两部分之间的合并操作的同时统计跨越不同分区边界的那些特殊形式的逆序对数目。最终由顶层调用返回整个过程累计得到的结果即为所逆序对数[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值