Advertisement
Guest User

inversions-PROP

a guest
Apr 16th, 2014
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. void swap(vector<int>& V, int e, int d){
  6.     int aux = V[e];
  7.     V[e] = V[d];
  8.     V[d] = aux;
  9. }
  10.  
  11. int conta_inv(vector<int>& V, int e, int d){
  12.    
  13.     if (e>=d) return 0;
  14.     else if (e == d-1){
  15.         if (V[e] > V[d]) {
  16.             swap(V, e, d);
  17.             return 1;
  18.            
  19.         }
  20.         else return 0;
  21.     }
  22.     else {
  23.  
  24.         int m = (e+d)/2;
  25.         int inv_e = conta_inv(V, e, m);
  26.         int inv_d = conta_inv(V, m+1, d);
  27.        
  28.        
  29.         int cont = 0;
  30.        
  31.         vector<int> v1,v2;
  32.        
  33.         for (int x=e; x<=m; x++) v1.push_back(V[x]);
  34.         for (int x=m+1; x<=d; x++) v2.push_back(V[x]);
  35.  
  36.         int i = 0;
  37.         int j = 0;
  38.         int k = e;
  39.         while (i < v1.size() and j < v2.size()){
  40.             if (v1[i] <= v2[j]){
  41.                 V[k] = v1[i];
  42.                 i++;
  43.             }
  44.             else {
  45.                 V[k] = v2[j];
  46.                 j++;
  47.                 cont += v1.size() - i;
  48.             }
  49.             k++;
  50.         }
  51.         while (i < v1.size()){
  52.             V[k] = v1[i];
  53.             i++; k++;
  54.         }
  55.         while (j < v2.size()){
  56.             V[k] = v2[j];
  57.             j++; k++;
  58.         }
  59.  
  60.         return inv_e + inv_d + cont;
  61.     }
  62. }
  63.  
  64. int main(){
  65.     int n;
  66.     while (cin >> n) {
  67.         vector<int> V(n);
  68.         for (int i=0; i<n; i++) cin >> V[i];
  69.         cout << conta_inv(V,0,n-1) << endl;
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement