Created
February 3, 2012 11:58
-
-
Save kubo39/1729835 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio; | |
class BinaryIndexedTree { | |
int size; | |
int[] bits; | |
this(int l){ | |
size = l; | |
bits.length = l+1; | |
} | |
int sum(int i){ | |
int s; | |
while(i > 0){ | |
s += bits[i]; | |
i -= i & -i; | |
} | |
return s; | |
} | |
void add(int i, int x){ | |
while(i<=size){ | |
bits[i] += x; | |
i += i & -i; | |
} | |
} | |
} | |
void main(char[][] args){ | |
/* バブルソートの計算回数を数える */ | |
int[] a = [3, 1, 4, 2]; | |
int ans; | |
BinaryIndexedTree bits = new BinaryIndexedTree(a.length); | |
foreach(int i, int v; a){ | |
ans += i - bits.sum(v); | |
bits.add(v, 1); | |
/* bits.bitsは交換しなくていい組の数 */ | |
writef("%d: ans=%d v=%d ", i, ans, v); | |
writeln(bits.bits); | |
} | |
writeln(ans); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ ./binaryindexedtree
0: ans=0 v=3 [0, 0, 0, 1, 1]
1: ans=1 v=1 [0, 1, 1, 1, 2]
2: ans=1 v=4 [0, 1, 1, 1, 3]
3: ans=3 v=2 [0, 1, 2, 1, 4]
3