我知道這個問題已經討論過,但我有興趣使用二進制索引樹來做這件事。我發現 this鏈接顯示如何做到這一點。我沒有完全按照解釋。有人能給我一個解釋爲什麼以下給出的是真實的。使用位計數倒數
Create a BIT of size greater than n(no of elements). Iterate through array A (
let j be the index of loop),and for each element A[j] do:
1) Add j-sum(A[j]) to the number of inversions
2) add(A[j], 1) (i.e. add 1 to the position A[j] on BIT. This effectively
counts the number of time value A[j] is seen so far)
我不明白爲什麼這個工程。
令人敬畏。非常感謝!! – frodo 2012-08-06 07:49:31
很棒的回答。有一件事:問題是爲什麼'j-sum(A [j])'被添加,你稍微塗了一點。我認爲'sum(A [j])'表示「到目前爲止所看到的A的元素數在0和A [j]之間」。在這種情況下,到目前爲止,元素的總數小於或等於* A [j]。到目前爲止,所有其他*元素因此必須大於j。那裏有多少?如果數組是基於0的,則必須有j(否則爲j-1)。所以到目前爲止,這些較大的元素必須有'j-sum(A [j])'。 (自'j == sum(A [n])'之後,與sum(A [n]) - sum(A [j])相同。) – 2012-10-03 21:09:43