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
90
#include <bits/stdc++.h>

#include "teatr.h"
#include "message.h"

using namespace std;

uint64_t inv(vector<int> &v, vector<int> &t, int from, int to)
{
	if (from + 1 >= to) return 0;

	int mid = (to + from) / 2;
	uint64_t I;
	I = inv(v, t, from, mid);
	I += inv(v, t, mid, to);

	int i = from;
	int j = mid;
	int k = from;
	while (i < mid && j < to) {
		if (v[i] <= v[j]) {
			t[k++] = v[i++];
		} else {
			t[k++] = v[j++];
			I += mid - i;
		}
	}
	while (i < mid) t[k++] = v[i++];
	while (j < to)  t[k++] = v[j++];
	for (i = from; i < to; i++) v[i] = t[i];
	return I;
}

int main()
{
	int N = GetN();

	int from = (uint64_t)N *  MyNodeId()    / NumberOfNodes();
	int to   = (uint64_t)N * (MyNodeId()+1) / NumberOfNodes();
	
	const int max_k = 1000000;

	vector<int> Rc, M, temp;

	Rc.resize(max_k+1, 0);
	M.resize(to - from, 0);

	for(int i=from; i<to; i++) {
		int k = GetElement(i);
		assert(0 <= k);
		assert(k <= max_k);
		M[i-from] = k;
	}

	int max_r = 0;
	for(int i=to; i<N; i++) {
		int k = GetElement(i);
		assert(0 <= k);
		assert(k <= max_k);
		if (k > max_r) max_r = k;
		Rc[k]++;
	}
	Rc.resize(max_r+1);

	temp.resize(M.size());
	uint64_t I = inv(M, temp, 0, M.size());

	for(size_t i=0, j=0; i < M.size() && j < Rc.size();) {
		if (M[i] <= (int)j) {
			i++;
		} else {
			I += (uint64_t)Rc[j] * (M.size() - i);
			j++;
		}
	}

	if (MyNodeId() == 0) {
		for (int i=0; i<NumberOfNodes()-1; i++) {
			int s = Receive(-1);
			I += GetLL(s);
		}
		cout << I << endl;
	} else {
		PutLL(0, I);
		Send(0);
	}
	return 0;
}

// vim: se cindent :