Advertisement
Guest User

Untitled

a guest
Nov 19th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. using namespace std;
  4.  
  5. int *A, *B;
  6. long long merge(int *a, int *b, int p, int q, int r)  {
  7.     int i = p;
  8.     int j = q + 1;
  9.     int s = p;
  10.     long long wynik = 0, druga = 0;
  11.     while (i <= q && j <= r)
  12.     {
  13.       if (a[i] <= a[j])
  14.       {
  15.         b[s] = a[i];
  16.         i++;
  17.         wynik += druga;
  18.       }
  19.       else
  20.       {
  21.         b[s] = a[j];
  22.         j++;
  23.         druga++;
  24.       }
  25.       s++;
  26.     }
  27.  
  28.  
  29.     while (i <= q){
  30.       b[s] = a[i];
  31.       i++;
  32.       s++;
  33.       wynik += druga;
  34.     }
  35.    while (j <= r){
  36.       b[s] = a[j];
  37.       j++;
  38.       s++;
  39.     }
  40.  
  41.     for (int it = p; it <= r; it++)a[it] = b[it];
  42.     return wynik;
  43.   }
  44. long long mergesort(int *a, int *b, int p, int r){
  45.     long long wynik = 0;
  46.     if (p == r) return wynik;
  47.     int q = (p + r)/2;
  48.     wynik += mergesort(a, b, p, q);
  49.     wynik += mergesort(a, b, q + 1, r);
  50.     wynik += merge(a, b, p, q, r);
  51.     return wynik;
  52. }
  53. int main()
  54. {
  55.     int n, t;
  56.     cin >> n;
  57.     A = new int [n];
  58.     B = new int [n];
  59.  
  60.     for( int i = 0; i < n; i++){
  61.         scanf("%d",&t);
  62.         A[i] = t;
  63.     }
  64.     printf("%lld", mergesort(A, B, 0, n-1));
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement