#include <iostream> #include <message.h> #include <teatr.h> #include <vector> using namespace std; void merge(vector<int>& t, long long& b, long long& m, long long& e, long long& sum) { vector<long long> wyn; long long i, j; for(i = b, j = m; i < m && j < e;) { if(t[i] <= t[j]) { wyn.push_back(t[i]); ++i; } else { wyn.push_back(t[j]); ++j; sum += m - i; } } while(i < m) { wyn.push_back(t[i]); ++i; } while(j < e) { wyn.push_back(t[j]); ++j; } for(long long k = 0; k < e - b; k++) { t[b + k] = wyn[k]; } } void merge_sort(vector<int>& t, long long b, long long e, long long& sum) { if(b != e - 1) { long long mid = (b + e) / 2; merge_sort(t, b, mid, sum); merge_sort(t, mid, e, sum); merge(t, b, mid, e, sum); } } int main() { if(!MyNodeId()) { vector<int> t; int n = GetN(); for(int i = 0; i < n; i++) { int a = GetElement(i); t.push_back(a); } long long sum = 0; long long e = t.size(); long long b = 0; merge_sort(t, b, e, sum); cout << sum << endl; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | #include <iostream> #include <message.h> #include <teatr.h> #include <vector> using namespace std; void merge(vector<int>& t, long long& b, long long& m, long long& e, long long& sum) { vector<long long> wyn; long long i, j; for(i = b, j = m; i < m && j < e;) { if(t[i] <= t[j]) { wyn.push_back(t[i]); ++i; } else { wyn.push_back(t[j]); ++j; sum += m - i; } } while(i < m) { wyn.push_back(t[i]); ++i; } while(j < e) { wyn.push_back(t[j]); ++j; } for(long long k = 0; k < e - b; k++) { t[b + k] = wyn[k]; } } void merge_sort(vector<int>& t, long long b, long long e, long long& sum) { if(b != e - 1) { long long mid = (b + e) / 2; merge_sort(t, b, mid, sum); merge_sort(t, mid, e, sum); merge(t, b, mid, e, sum); } } int main() { if(!MyNodeId()) { vector<int> t; int n = GetN(); for(int i = 0; i < n; i++) { int a = GetElement(i); t.push_back(a); } long long sum = 0; long long e = t.size(); long long b = 0; merge_sort(t, b, e, sum); cout << sum << endl; } } |