簡體   English   中英

反轉距離

[英]Inversion distance

首先讓我們回憶一下反演的定義。

一些包含數字的序列 S 的反轉是當 S[i] > S[j] 和 i < j 時的情況,或者坦率地說,這是我們有無序元素時的情況。 例如對於序列:

1 4 3 7 5 6 2

我們有以下反轉 (4,3)、(4,2)、(3,2)、(7,5) 等。

我們將問題陳述如下:反演距離是兩個反演值之間的最大(就索引而言)距離。 例如,我們可以執行人腦搜索,得到對 (4,2) <=> (S[1], S[6]) 並且索引距離為 6-1 = 5,這是最大可能的案件。

這個問題可以在 O(n^2) 中通過查找所有反演並保持最大距離(如果我們找到更好的選擇則更新)以簡單的方式解決我們還可以使用歸並排序執行更好的反演搜索,因此在 O(nlogn )。 是否有可能存在 O(n) 算法? 請記住,我們只想要最大距離,我們不想找到所有反演。 請詳述。

是的,O(n) 算法是可能的。

我們可以用貪心算法提取嚴格遞增的子序列:

source:                          1 4 3 7 5 6 2
strictly increasing subsequence: 1 4   7

然后我們可以向后提取嚴格遞減的子序列:

source:                          1 4 3 7 5 6 2
strictly decreasing subsequence: 1           2

請注意,在找到這個嚴格遞減的子序列后,我們可以將其解釋為遞增序列(在法線方向)。

對於這些子序列的每個元素,我們需要將它們的索引存儲在源序列中。

現在可以通過合並這兩個子序列來找到“反轉距離”(類似於 OP 中提到的合並排序,但只需要一個合並通道):

merge 1 & 1 ... no inversion, advance both indices
merge 4 & 2 ... inversion found, distance=5, should advance second index,
                but here is end of subsequence, so we are done, max distance = 5

也許我的想法與@Evgeny 相同。 這是解釋:

make a strictly increasing array from the beginning we call it array1
make a strictly decreasing array from the ending which is array2 (But keep the values in increasing order)

***Keep track of original indexes of the values of both arrays.

Now start from the beginning of both arrays.

Do this loop following untill array1 or array2 checking is complete

    While( array1[index] > arry2[index] )
    {
        check the original distance between array1 index and arry2 index.
        Update result accordingly.
        increase array2 index.
    }
    increase both array index

Continue with the loop

在此過程結束時,您將獲得最大的結果。 這個解決方案的證明並不復雜,你可以自己嘗試一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM