Ideas:
Number of shards and number of exchanges after Bubble Sorting Optimization
The number of exchanges equals to the number of reverse orders
Because the Bubble Sorting is a temporary shift sorting, the next shift reduces a reverse order
Number of bubbles:
Calculate the number of numbers in front of each number a [I], which is greater than that in front of it, and record it as B [I].
The answer is max {B []} + 1.
No swap for the last trip
A total of so many bubble max {B []} + 1
Because for each number, each trip moves the number above it to the end of it.
After max {B []}, the front of each number is no longer bigger than it ,..,,.
Overall order ..,.
(Idea from neko13)
Code:
# Include
# Include
# Include
# Include
# Include
# Define N 100010 using namespace std; int c [N], maxn; inline int Lowbit (int x) {return x & (-x);} int sum (int I) // change the update point to x {int ans = 0; while (I <= maxn) {ans + = c [I]; I ++ = Lowbit (I );} return ans;} void change (int x, int value) {// [1, x] increment to valuefor (int I = x; I> = 1; i-= Lowbit (I) c [I] + = value;} int a [N]; set
Myset; set
: Iterator p; map
Mymap; int main () {int n, I; while (~ Scanf (% d, & n) {myset. clear (); mymap. clear (); maxn = n + 1; // discrete for (I = 0; I <n; I ++) scanf (% d, & a [I]), myset. insert (a [I]); int top = 1; for (p = myset. begin (); p! = Myset. end (); p ++) mymap. insert (pair
(* P, top ++); for (I = 0; I <n; I ++) {a [I] = mymap. find (a [I])-> second; c [I] = 0;} // int maxx = 0, he = 0; for (I = 0; I <n; I ++) {int ni = sum (a [I]); change (a [I], 1); maxx = max (ni, maxx ); he + = ni;} int ans2 = 0; maxx ++; while (maxx --) ans2 + = -- n; printf (% d, ans2, he ); // The number of exchange times is: the number of reverse orders (the number of exchanges equals the number of reverse orders because the Bubble Sorting is a forward order, and the next order is reduced by a reverse order) // The number of sorted rows is max (the reverse order of each number) + 1 (the last one is not exchanged)} return 0;}/* 55 1 2 3 4 */