Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. #define MAXN 100005
  4. long long merge(int A[],int left,int mid,int right)
  5. {
  6. int i=left,j=mid,k=0;
  7. int temp[right-left+1];
  8. long long count=0;
  9. while(i<mid&&j<=right)
  10. {
  11. if(A[i]<=A[j]){
  12. temp[k++]=A[i++];
  13. }
  14. else{
  15. temp[k++]=A[j++];
  16. count+=mid-i;
  17.  
  18.  
  19. }
  20. }
  21. while(i<mid){
  22. temp[k++]=A[i++];
  23. }
  24. while(j<=right){
  25. temp[k++]=A[j++];
  26. }
  27. for(int i=left,k=0;i<=right;i++,k++){
  28.  
  29. A[i]=temp[k];}
  30.  
  31. return count;
  32. }
  33. long long merge_sort(int A[],int left,int right){
  34. long long count=0;
  35. if(right>left){
  36. int mid=(left+right)/2;
  37. long long countleft=merge_sort(A,left,mid);
  38. long long countright=merge_sort(A,mid+1,right);
  39. long long mycount=merge(A,left,mid+1,right);
  40. return mycount+countleft+countright;
  41. }
  42. return count;
  43. }
  44. long long solve(int A[],int n)
  45. {
  46. long long ans=merge_sort(A,0,n-1);
  47. return ans;
  48. }
  49. int main()
  50. {
  51. int n,A[MAXN];
  52. cin>>n;
  53. for(int i = 0; i < n ; i++){
  54. cin>>A[i];
  55. }
  56. cout<<solve(A,n)<<endl;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement