A lot of nonsense is the number of exchanges required for a sequence of bubble sort.
Train of Thought: in fact, you need to find the number of reverse teams in a sequence
Case study:
9 1 0 5 4
9 there are four numbers smaller than it.
1 followed by 1
No after 0
5, followed by 1
4 NO
Therefore, the result is 4 + 1 + 0 + 1 + 0 = 6.
Therefore, if you are not clear about the definition of the reverse order, you can summarize it by yourself.
To put it bluntly, you need to use the merge sort to find the reverse logarithm.
The following is a method for searching the reverse logarithm of a cow:
Assume that the two parts are sorted in order (that is to say, the two parts to be merged are sorted separately) after a specific step is traced back to a specific step. Assume that the two sequences are
Sequence A1: 2 3 5 9
Sequence A2: 1 4 6 8
In this case, we want to combine A1 and A2 into a sequence.
Since the A2 sequence must all be after the A1 sequence before sorting, when we compare the A2 1 and A1 2, it is found that 1 <2 records the 1 of A2 first according to the merging idea, and here it is actually the optimization of Bubble sorting. Bubble is to sort the 1 of A2 in sequence with the 9, 5 of A1, 3, 2 requires four exchanges, but only one merge is complete. How can we record this 4? In fact, because 1 is smaller than 2 and there are four numbers after 2, that is to say, my result must be + 4, that is, record the A1 sequence to find the first number larger than A2, the number of remaining numbers is the number of exchanges.
My AC code (according to the ideas of Liu lujia, don't spray = ):
#include<stdio.h>#include<string.h>int n,a[500005],b[500005];__int64 sum;void merge_sort(int x,int y){ if(y-x>1) { int m=x+(y-x)/2; int p=x,q=m,i=x; merge_sort(x,m); merge_sort(m,y); while(p<m||q<y) { if(q>=y||(p<m&&a[p]<=a[q])) b[i++]=a[p++]; else { sum+=m-p; b[i++]=a[q++]; } } for(i=x;i<y;i++)a[i]=b[i]; }}int main(){ while(scanf("%d",&n)!=EOF) { if(n==0)break; memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); for(int i=0;i<n;i++) scanf("%d",&a[i]); sum=0; merge_sort(0,n); printf("%I64d\n",sum); } return 0;}