The first time I wrote a tree-like array, I felt that the lowbit bit operation was quite powerful.
Because-X is equivalent to the bits of x and then the whole plus 1, so the rightmost one 1 and the end of the 0, take the inverse plus one unchanged.
For example, 1000 negation is 0111 plus one gets 1000, so the operation will not change after
The left side of the rightmost 1 is reversed, plus one does not affect the left half, so all 0 after the operation
For this problem, it seems that it's not easy to think of a tree-like array.
Note that each person's skill value is different.
From left to right scan each a[i], another x[a[i]] = 1, and then statistics x[1]...x[a[i]-1] and is the first person on the left hand skill value is smaller than the number of people c[i], so the number of people on the left of the first person is greater than he is i-1-c[i]
Similarly, from right to left scan A[i], also x[a[i]] = 1, statistics x[1]...x[a[i]-1] and is the person on the right hand skill value is smaller than his number d[i], so his right hand skill value is greater than his number is n-i-d[i]
In accordance with the counting principle, the total scheme number is sum{c[i] * N-i-d[i] + d[i] * I-1-c[i]}
1#include <cstdio>2#include <vector>3#include <algorithm>4 using namespacestd;5 6InlineintLowbit (intx) {returnX & (-x); }7 8 structFenwicktree9 {Ten intN; Onevector<int>C; A - voidResizeintN) { This->n =N; C.resize (n); } - voidClear () {Fill (C.begin (), C.end (),0); } the - intSumintx) - { - intRET =0; + while(x) - { +RET + =C[x]; AX-=lowbit (x); at } - returnret; - } - - voidAddintXintd) - { in while(x <=N) - { toC[X] + =D; +X + =lowbit (x); - } the } * }f; $ Panax Notoginseng Const intMAXN =20000+Ten; - intA[MAXN], C[MAXN], D[MAXN]; the + intMain () A { the //freopen ("In.txt", "R", stdin); + - intT; $scanf"%d", &T); $ while(t--) - { - intN, Maxa =0; thescanf"%d", &n); - for(inti =1; I <= N; i++) {scanf ("%d", &a[i]); Maxa =Max (Maxa, A[i]);}Wuyi f.resize (Maxa); F.clear (); the for(inti =1; I <= N; i++) - { WuF.add (A[i],1); -C[i] = f.sum (A[i]-1); About } $ f.clear (); - for(inti = n; i >0; i--) - { -F.add (A[i],1); AD[i] = f.sum (A[i]-1); + } the Long LongAns =0; - for(inti =1; I <= N; i++) ans + = (Long Long) c[i]* (N-i-d[i]) + (Long Long) d[i]* (I-1-c[i]); $printf"%lld\n", ans); the } the the return 0; the}
code June
LA 4329 (tree-shaped array) Ping pong