Created
June 18, 2016 00:53
-
-
Save mustafa-qamaruddin/c2a118c5f2bf927260c7c8b2a72a5658 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <string> | |
using namespace std; | |
typedef unsigned long long ull; | |
const int MAX_SIZE = 100000; | |
int data[MAX_SIZE]; | |
int sz; | |
void loadData() { | |
ifstream ifs("in.txt"); | |
if(ifs.is_open()) { | |
int x; | |
int i = 0; | |
while(ifs >> x) { | |
data[i] = x; | |
i++; | |
} | |
sz = i; | |
} | |
} | |
ull countSplitInversions(int a, int b) { | |
ull ret = 0; | |
int median = (a+b)/2; | |
int i = a; | |
int j = median + 1; | |
int len = b - a + 1; | |
int* temp_array = new int[len]; | |
for(int idx = 0; idx < len; idx++) | |
{ | |
if(i > median) | |
{ | |
temp_array[idx] = data[j]; | |
j++; | |
continue; | |
} | |
if(j > b) | |
{ | |
temp_array[idx] = data[i]; | |
i++; | |
continue; | |
} | |
if(data[i] <= data[j]) | |
{ | |
temp_array[idx] = data[i]; | |
i++; | |
} | |
if(data[i] > data[j]) | |
{ | |
temp_array[idx] = data[j]; | |
ret += median - i + 1; | |
j++; | |
} | |
} | |
int temp_idx = 0; | |
for(int idx = a; idx <= b; idx++) | |
{ | |
data[idx] = temp_array[temp_idx]; | |
temp_idx++; | |
} | |
return ret; | |
} | |
ull countInversions(int a, int b) { | |
// base case | |
if(b < a){ | |
return 0; | |
} | |
// base case | |
if(b == a) | |
{ | |
return 0; | |
} | |
int median = (a+b) / 2; | |
ull l = countInversions(a, median); | |
ull r = countInversions(median+1, b); | |
ull s = countSplitInversions(a, b); | |
return l+r+s; | |
} | |
int main() { | |
loadData(); | |
cout << countInversions(0, sz-1) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment