题目:https://vjudge.net/contest/378940#problem/A
解析:这题用到了归并排序。
代码:
#include<bits/stdc++.h> #define max 1000001 long long a[max],b[max]; long long count; void Merge(long long a[],int start,int mid,int end) //归并排序的合并部分 { int i=start,j=mid+1,k=start; while(i<=mid&&j<=end) { if(a[i]<=a[j]) { b[k++]=a[i++]; } else { count+=j-k;//统计逆序数对 b[k++]=a[j++]; } } while(i<=mid) { b[k++]=a[i++]; } while(j<=end) { b[k++]=a[j++]; } for(int i=start;i<=end;i++) { a[i]=b[i]; } } void MergeSort(long long a[],int start,int end) //归并排序 { if(start<end) { int mid=(start+end)/2; MergeSort(a,start,mid); // 将前半部分排序 MergeSort(a,mid+1,end); // 将后半部分排序 Merge(a,start,mid,end); // 合并前后两个部分 } } int main() { int m; scanf("%d",&m); count=0; for(int i=0;i<m;i++) { scanf("%d",a+i); } MergeSort(a,0,m-1); printf("%lld ",count); }
参考资料:
1.https://blog.csdn.net/qq_40938077/article/details/85331296?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase
2.https://blog.csdn.net/weixin_40557407/article/details/82946489?utm_medium=distribute.pc_relevant_download.none-task-blog-blogcommendfrombaidu-1.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-blogcommendfrombaidu-1.nonecas