简体   繁体   English

如何计算半随机整数数组中的“预期”反转次数?

[英]How to calculate “expected” number of inversions in a semi-random array of integers?

Consider an array a of integers. 考虑一个整数数组a。 A pair (i,j) is called an inversion in A if i < j and A[i] > A[j]. 如果i <j且A [i]> A [j],则对(i,j)在A中称为反转。

For every position 'i' in the array there are two possible candidates: a[i] with probability p[i] and a[i]+x with probability 1-p[i]. 对于阵列中的每个位置“i”,存在两个可能的候选:具有概率p [i]的a [i]和具有概率1-p [i]的a [i] + x。

Now I have to calculate expected number of inversions. 现在我必须计算预期的反转次数。 Given a[i] and p[i] for every index i and an integer x. 给定每个索引i和整数x的[i]和p [i]。

I know the O(n^2) approach (check every legal possible pair). 我知道O(n ^ 2)方法(检查每个合法可能的对)。 Also, I know the O(nlogn) approach to calculate the number of inversions in an array in which all the elements are predetermined with 100% probability. 此外,我知道O(nlogn)方法来计算数组中的反转次数,其中所有元素都以100%的概率预先确定。 It is done by modifying merge sort. 它是通过修改合并排序来完成的。

I want to know an approach better than n squared. 我想知道比n平方更好的方法。 Please let me know. 请告诉我。

This can be done with a simple modification to the standard merge-sort based algorithm for counting inversions, where we assign a weight to each value and compute the sum of W[i]*W[j] for i<j , A[i]>A[j] (when each weight is 1, we get the normal count). 这可以通过对用于计数反演的基于标准合并排序的算法的简单修改来完成,其中我们为每个值分配权重并计算对于i<jA[i]>A[j] W[i]*W[j]W[i]*W[j]A[i]>A[j] (当每个权重为1时,我们得到正常计数)。 Instead of adding to the count the number of elements remaining in the left array, we add the sum of the weights for these elements multiplied by the weight of the element in the right array we are processing. 我们将这些元素的权重之和乘以我们正在处理的右数组中元素的权重,而不是将剩余的元素数添加到计数中。

To use this algorithm to solve the posed problem, simply create an array of twice the size, where each element in the original array is replaced by two elements (in sorted order), with weights given by the probabilities. 要使用此算法来解决提出的问题,只需创建一个大小为两倍的数组,其中原始数组中的每个元素都由两个元素(按排序顺序)替换,权重由概率给出。

I left a comment explaining this, but you can have an O(1) calculation of this if you just use a little bit of math. 我留下了一个解释这个问题的评论,但如果你只是使用一点点数学,你就可以对其进行O(1)计算。 I'll spare you the work, but, by my calculations, the expected number of inversions in an array of n integers is ((n^2) - (n)) / 4. Sorry for the abundance of parentheses, I just wanted to make sure that was totally clear. 我会省去你的工作,但是,根据我的计算,n个整数数组中预期的反转次数是((n ^ 2) - (n))/ 4.对不起,括号中有很多,我只是想要确保完全清楚。 I can post the work if you want it, but I figured I'd leave it out if you just need the answer. 如果你愿意,我可以发布你的工作,但我想如果你只是需要答案,我会把它留下来。

So, despite what my comment says, I remembered incorrectly. 所以,尽管我的评论说,我记得错了。 It's not lg(n). 这不是lg(n)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM