Skip to content

Instantly share code, notes, and snippets.

@akouryy
Created December 30, 2014 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akouryy/90f2d761acd78ff81cb7 to your computer and use it in GitHub Desktop.
Save akouryy/90f2d761acd78ff81cb7 to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
template<class T> class BIT{
private:
/**
* [---------------------8]
* [---------4]
* [---2] [---6]
* [1] [3] [5] [7] [9]
*/
vector<T> pyon;
public:
BIT(int n){
pyon = vector<T>(n, (T)0);
}
/**
* [++++++++++++++++++++++]
* [----------]
* [----] [++++]
* [-] [-] [+] [-] [-]
* 5: 0101 + 1 -> 6
* 6: 0110 + 10 -> 8
* 8: 1000 + 1000 -> out of range
*/
void add(int i, int d){
i++;
while(i <= pyon.size()){
pyon[i - 1] += d;
i += i & -i;
}
}
/**
* [++++++++++++++++++++++]
* [----------]
* [----] [++++]
* [-] [-] [+] [-] [-]
* 5: 0101 - 1 -> 4
* 4: 0100 - 0100 -> 0
*/
T sum(int i){
i++;
T sum = (T)0;
while(i){
sum += pyon[i - 1];
i -= i & -i;
}
return sum;
}
};
int main(){
int N, sum = 0;
cin >> N;
BIT<int> pyon(N);
for(int i = 0; i < N; i++){
int a;
cin >> a;
sum += pyon.sum(--a);
pyon.add(a, 1);
}
cout << sum;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment