Queuing of Children in previous questions (reverse order of tree array)
Queuing time limit for previous questions: 1.0 s memory limit: 256.0 MBProblem description n children stand in a row. Now we want to sort them in ascending order of height, but each time we can only exchange two adjacent children.
Every child is unhappy. At the beginning, all the children were not happy.
If a child is asked to exchange for the first time, his unhappiness increases by 1. If the child is asked to exchange for the second time, then his unhappiness increases by 2 (that is, his unhappiness is 3), and so on. When a child is asked to exchange k for the second time, his unhappiness increases by k.
What is the minimum sum of unhappiness for all the children in the queue from low to high.
If two children are in the same height, it doesn't matter who is standing in front of them. The first line in the input format contains an integer n, indicating the number of children.
The second row contains n integers H1 H2... Hn, indicating the height of each child. The output format outputs a row containing an integer, indicating the child's unhappiness and the minimum value. Sample input 3
3, 2, 1, and output 9 examples indicate that the first is to switch between 3 and 2, then between 3 and 1, and between 2 and 1, each child is 3 unhappy and 9 in total. Data scale and conventions for 10% of data, 1 <= n <= 10;
For 30% of data, 1 <= n <= 1000;
For 50% of data, 1 <= n <= 10000;
For 100% of data, 1 <= n <= 100000,0 <= Hi <= 1000000.
Solution: Use a tree array to solve Reverse Order pairs.
The number of exchanges between friends is the number of smaller numbers on the left and right of each number. Ans = for details about the reverse logarithm formed by the left and the reverse logarithm formed by the right + the reverse logarithm formed by the right, see the code.
# Include
# Include
# Include
Using namespace std; int c [1000010], a [1000010] ;__ int64 sg [100010], q [100010]; int n; int lowbit (int k) {return k & (-k);} void add (int num, int k) {while (k <1000010) {c [k] + = num; k + = lowbit (k) ;}} int sum (int k) {int s = 0; while (k) {s + = c [k]; k-= lowbit (k);} return s;} int main () {int I; q [1] = 1; for (I = 2; I <100010; I ++) {q [I] = q [I-1] + I;} while (~ Scanf ("% d", & n) {memset (c, 0, sizeof (c); memset (sg, 0, sizeof (sg )); for (I = 0; I
= 0; I --) {add (1, a [I] + 1); sg [I] + = sum (a [I]); // The right side is smaller than him. The purpose is to increase the left side and the right side is smaller than him to get the number of times he exchanged} // int s = Min + Max; __int64 ans = 0; for (I = 0; I