#include <iostream> #include <vector> #include "teatr.h" #include "message.h" using namespace std; typedef long long ll; int n; ll Merge(vector<int>& L, vector<int>& P, vector<int>& wyn) { int l = 0, p = 0; ll inv = 0; while (l < L.size() || p < P.size()) { if (l < L.size() && p < P.size()) { if (L[l] <= P[p]) { wyn.push_back(L[l]); ++l; } else { wyn.push_back(P[p]); ++p; inv += L.size() - l; } } else { if (l < L.size()) { wyn.push_back(L[l]); ++l; } else { wyn.push_back(P[p]); ++p; } } } return inv; } ll MergeSort(vector<int>& a, int l, int p) { if (l == p) return 0; int s = (l + p) / 2; ll inv = MergeSort(a, l, s) + MergeSort(a, s + 1, p); vector<int> L, P; for (int i = l; i <= p; ++i) { if (i <= s) L.push_back(a[i]); else P.push_back(a[i]); } vector<int> wyn; inv += Merge(L, P, wyn); for (int i = 0; i < wyn.size(); ++i) a[i + l] = wyn[i]; return inv; } int main() { if (MyNodeId() != 0) return EXIT_SUCCESS; n = GetN(); vector<int> a(n); for (int i = 0; i < n; ++i) a[i] = GetElement(i); cout << MergeSort(a, 0, n - 1); return EXIT_SUCCESS; }
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 73 74 75 76 77 78 79 80 | #include <iostream> #include <vector> #include "teatr.h" #include "message.h" using namespace std; typedef long long ll; int n; ll Merge(vector<int>& L, vector<int>& P, vector<int>& wyn) { int l = 0, p = 0; ll inv = 0; while (l < L.size() || p < P.size()) { if (l < L.size() && p < P.size()) { if (L[l] <= P[p]) { wyn.push_back(L[l]); ++l; } else { wyn.push_back(P[p]); ++p; inv += L.size() - l; } } else { if (l < L.size()) { wyn.push_back(L[l]); ++l; } else { wyn.push_back(P[p]); ++p; } } } return inv; } ll MergeSort(vector<int>& a, int l, int p) { if (l == p) return 0; int s = (l + p) / 2; ll inv = MergeSort(a, l, s) + MergeSort(a, s + 1, p); vector<int> L, P; for (int i = l; i <= p; ++i) { if (i <= s) L.push_back(a[i]); else P.push_back(a[i]); } vector<int> wyn; inv += Merge(L, P, wyn); for (int i = 0; i < wyn.size(); ++i) a[i + l] = wyn[i]; return inv; } int main() { if (MyNodeId() != 0) return EXIT_SUCCESS; n = GetN(); vector<int> a(n); for (int i = 0; i < n; ++i) a[i] = GetElement(i); cout << MergeSort(a, 0, n - 1); return EXIT_SUCCESS; } |