Question address: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1394
Tree array. I first thought about it, but I didn't think of it:
When the number of team heads is placed at the end of the team, the number of reverse orders in the queue may change...
When deducting the number of reverse orders, we forget to subtract the number of new reverse orders!
# Include <iostream> # include <cstdio> # include <cstring> # define LL (v <1) # define RR (v <1 | 1) # define max (A, B) (a)> (B )? (A) :( B) using namespace STD; int N; int s [5200]; int num [5200]; int rec [5200]; void add (INT V) {While (v <= N) {num [v] ++; V + = V &-V ;}} int query (INT v) {int sum = 0; while (V> 0) {sum + = num [v]; V-= V &-V;} return sum;} int main () {int I, j, TMP, sum, Mn; while (~ Scanf ("% d", & N) {memset (Num, 0, sizeof (Num); for (I = 1; I <= N; I ++) {scanf ("% d", & S [I]); s [I] ++;} sum = 0; for (I = N; I> = 1; I --) {// create bit add (s [I]); REC [I] = query (s [I]-1 ); // count the reverse order sum + = rec [I]; // count and record the reverse order} memset (Num, 0, sizeof (Num )); // reconstruct bit Mn = sum; for (I = 1; I <= N; I ++) {// Old and New reverse orders, sum-= rec [I] + query (s [I]-1); add (s [I]); // move to the end of each operation, enter the new bit sum + = n-s [I]; // Add the new reverse order number if (sum <Mn) Mn = sum ;} printf ("% d \ n", Mn);} return 0 ;}