The basic idea is the same as the number of reverse orders for solving a line segment tree. The previous article "reverse order for line segment Tree" also introduced that the input array is discrete first, different elements in the array can be directly hashed. If the same number exists, binary can be used.
After discretization, find f [I] + 1 ~ for each f [I ~ The number in N, that is, to the I position, is a total number larger than F [I]. After statistics, the number at the position of F [I] is increased by 1.
In this way, the statistics are similar to a [I] ~ The sum of N can be imagined to count the tree array in turn, that is, adding lowbit during statistics and downgrading lowbit during update.
Take poj 2299 as an example.
#include <iostream>#include <cstring>#include <cstdio>#include <cmath>#include <set>#include <stack>#include <cctype>#include <algorithm>#define lson o<<1, l, m#define rson o<<1|1, m+1, rusing namespace std;typedef long long LL;const int maxn = 500050;const int mod = 99999997;const int MAX = 0x3f3f3f3f;int n, tmp, f[maxn];LL c[maxn];struct C { int num, pos;}in[maxn];bool cmp(C x, C y) { return x.num < y.num;}int main(){ while(cin >> n, n) { for(int i = 1; i <= n; i++) { scanf("%d", &in[i].num); in[i].pos = i; } sort(in+1, in+1+n, cmp); LL sum = 0; memset(c, 0, sizeof(c)); for(int i = 1; i <= n; i++) f[ in[i].pos ] = i; for(int i = 1; i <= n; i++) { for(int j = f[i]+1; j <= n; j += j&(-j)) sum += c[j]; for(int j = f[i]; j > 0; j -= j&(-j)) c[j]++; } cout << sum << endl; } return 0;}