There are 6 cases, a < b and AA < Ab, C < D and AC > Ad, the number of these two cases multiplied, minus a = c, a = d, B = c, B = d in these four cases, using a tree array maintenance, le[i] means I left a number smaller than he, l E1[i] represents I left to the number of large numbers, Ri[i] represents I right than his small number of numbers, Ri1[i] represents I right than his large number of numbers.
Run the tree array two times to find out the four array values.
Pay attention to the case where the values are equal.
#include <cstdio> #include <iostream> #include <cstdlib> #include <cstring> #include <string > #include <algorithm> #include <map> #include <queue> #include <vector> #include <cmath > #include <utility>using namespace std;typedef long long ll;const int N = 60008, INF = 0x3f3f3f3f; #define MS (A, Nu m) memset (A, num, sizeof (a)) #define PB (a) push_back (a) #define for (I, n) for (int i = 0; i < n; i++) int C[n];int n;int Le [N], ri[n], le1[n], Ri1[n];int val[n];int b[n], tp[n];inline int lowbit (int x) {return x&-x;} inline void Add (int x, int val) {for (int i=x;i<=n;i+=lowbit (i)) {C[i] + = val; }}inline int sum (int x) {int ret = 0; for (int i=x;i>0;i-=lowbit (i)) {ret+=c[i]; } return ret;} int main () {while (~SCANF ("%d", &n)} {for (int i = 1; I <= n; i++) {scanf ("%d", &val[i]); Tp[i] = Val[i]; } sort (val + 1, val + n + 1); for (int i = 1; I <= n; i++){B[i] = Lower_bound (val + 1, val + n + 1, Tp[i])-Val; } MS (C, 0); for (int i = 1; I <= n; i++) {le[i] = SUM (b[i]-1); Le1[i] = SUM (n)-sum (B[i]); Add (B[i], 1); } MS (C, 0); for (int i = n; I >= 1; i--) {ri[i] = SUM (b[i]-1); Ri1[i] = SUM (n)-sum (B[i]); Add (B[i], 1); } LL ans= 0; LL sum = 0; for (int i = n; I >= 1; i--) {sum + = Ri1[i]; } ans = sum; sum = 0; for (int i = n; I >= 1; i--) {sum + = Ri[i]; } ans *= sum; sum = 0; for (int i = 1; I <= n; i++) {sum + = (LL) ri[i] * (LL) ri1[i]; Sum + = (LL) ri1[i] * (LL) le1[i]; Sum + = (LL) le[i] * (LL) le1[i]; Sum + = (LL) le[i] * (LL) ri[i]; } ans-= sum; printf ("%i64d\n", ans); } return 0;}
HDU5792 World is exploding (tree-like array)