Test instructions
Given a 1~n arrangement a0,a1,... an-1, the number of exchanges required to bubble sort the sequence (the algorithm that the bubble sort is to find the I that satisfies ai>ai+1 and exchange AI and ai+1 until such I does not exist).
Restrictions: 1<= n<= 100000
Input:
N=4, a={3,1,4,2}
Output:
3
The complexity of the bubbling sort is O (N2), all of which cannot be simulated by simulating the bubble sort process to calculate the required number of interchanges. However, we can solve this problem by selecting the appropriate data structure.
First, the number of exchanges required is equivalent to the number of (I,J) pairs that satisfy the I<j,ai>aj (the number of such pairs is called the number of reverse order). And for each J, if you can quickly find the number of I to meet I<j,ai>aj, then the problem is solved. We build a bit that is worth the 1~n, and do the following in the order of j=0,1,2,..., n-1.
* Add the "J" to the answer of the first AJ item obtained by the bit query
* Add 1 to the value of AJ position in bit
For each J, the (and) of the pre-AJ items obtained by the bit query is the number of I that satisfies the i<j,ai<=aj. Therefore, after subtracting this value from J, the number of I that satisfies I<j,ai>aj is obtained. Since the complexity of each J is O (Logn), the complexity of the entire algorithm is O (NLOGN).
#include <cstdio>using namespace Std;typedef long long ll;const int MAXN = 100000 + 10;int n;int a[maxn];int Bit[max N];int sum (int i) { int s = 0; while (i > 0) { s + = bit[i]; I-= i &-i; } return s;} void Add (int i, int x) { while (i <= N) { Bit[i] + = x; i + = i &-i; }} void Solve () { ll ans = 0; for (int j = 0; J < N; j + +) { ans + = j-sum (A[j]); Add (A[j], 1); } printf ("%lld\n", ans);} int main () { scanf ("%d", &n); for (int i = 0; i < n; i++) { scanf ("%d", &a[i]); } Solve (); return 0;}
Number of exchanges for bubbling sort