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
81
82
83
84
85
86
87
88
89
/*
 *  Copyright (C) 2018  Paweł Widera
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details:
 *  http://www.gnu.org/licenses/gpl.html
 */
#include "message.h"
#include "teatr.h"

#define rows GetN
#define read GetElement

#define node_id MyNodeId
#define nodes NumberOfNodes
#define push PutInt
#define pop GetInt
#define push_long PutLL
#define pop_long GetLL
#define send Send
#define receive Receive

#include <vector>
#include <iostream>
using namespace std;


int merge(vector<int>::iterator begin, vector<int>::iterator middle, vector<int>::iterator end) {
	int inversions = 0;

	for (;begin < middle; ++begin) {
		// compare elements from left and right halfs
		if (*begin > *middle) {
			// insert right element to the left half
			int value = *begin;
			*begin = *middle;
			++inversions;

			// insert left element to the right half
			vector<int>::iterator i = middle+1;
			// shift elements left if needed
			while (i < end && *i < value) {
				swap(*(i-1), *i);
				++i;
				++inversions;
			}
			*(i-1) = value;
		}
	}
	return inversions;
}


int merge_sort(vector<int>::iterator begin, vector<int>::iterator end) {
	int size = end - begin;
	if (size < 2) {
		return 0;
	}
	vector<int>::iterator middle = begin + size / 2;
	return merge_sort(begin, middle) + merge_sort(middle, end) + merge(begin, middle, end);
}


int main() {
	int n = rows();
	int k = nodes();

	if (node_id() > 0) {
		return 0;
	}

	vector<int> heights;
	heights.reserve(n);

	for (int i = 0; i < n; ++i) {
		heights.emplace_back(read(i));
	}

	int invertions = merge_sort(heights.begin(), heights.end());
	cout << invertions << endl;
	return 0;
}