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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
#include "message.h"
#include "teatr.h"
#include "bits/stdc++.h"
using namespace std;

typedef long long ll;
const int BASE = (1<<20);

int w[2*BASE+5];

void add(int pos, int val) {
	pos += BASE-1;
	
	w[pos] += 1;
	pos /= 2;
	
	while(pos > 0) {
		w[pos] = w[2*pos] + w[2*pos+1];
		pos /= 2;
	}
}

int get(int a, int b) {
	
	if(a > b) return 0;
	
	a += BASE-1;
	b += BASE-1;
	
	int ret = w[a];
	if(a != b)
		ret += w[b];
		
	while(a/2 != b/2) {
		if(a%2 == 0) ret += w[a+1];
		if(b%2 == 1) ret += w[b-1];
		a /= 2; b/= 2;
	}
	
	return ret;
}

ll calc(vector<int>& v) {
	
	ll ret = 0;
	
	for(int e : v) {
		ret += get(e+1,BASE);
		add(e,1);
	}
	
	return ret;
}


int n, on;

int getElem(int a) {
	if(a >= on) 
		return BASE;
	return GetElement(a);
}

int pref[BASE+5];

int main() {
	on = GetN();
	n = on;
	
	int node = MyNodeId();
	int nn = NumberOfNodes();
	
	while(n%nn!=0) n++;
	
	int len = n/nn;
			
	vector<int> v;
		
	int a = node*len;
	int b = a+len-1;

	for(int i = a; i <= b; ++i) {
		v.push_back(getElem(i));
	}
		
	ll res = calc(v);
	
	for(int e : v) {
		pref[e]++;
	}
	
	for(int i = 1; i <= BASE; ++i) {
		pref[i] += pref[i-1];
	} 
	
	for(int i = 0; i < a; ++i) {
		res += pref[getElem(i)-1];
	}
	
	if(node > 0) {
		PutLL(0,res);
		Send(0);
	}
	else {
		for(int i = 1; i < nn; ++i) {
			Receive(i);
			res += GetLL(i);
		}
		printf("%lld\n",res);
	}	
}