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
#include <bits/stdc++.h>
#include "message.h"
#include "teatr.h"
using namespace std;

using ll = long long;

const int MAXV = 1000002;

namespace fenwick {
int data[MAXV];
// value[i] += v
void add(int i, int v){ for (; i < MAXV; i |= i + 1) data[i] += v; }
// Returns value[0] + value[1] + ... + value[i]
int sum(int i){ int s=0; while(i>=0) { s+=data[i]; i=(i&(i+1))-1; } return s; }
}


int pre[MAXV];
int post[MAXV];

int n;
int id;
int nodes;

pair<int, int> get_range(int d) {
  static int interval_len = n / nodes + 1;
  return {min(n, interval_len * d), min(n, interval_len * (d+1))};
}

int main() {
  n = GetN();
  nodes = min(n, NumberOfNodes());
  if (nodes % 2 == 0) {
    nodes--;
  }
  id = MyNodeId();
  auto r = get_range(id);
  if (r.first >= n) {
    PutLL(0, 0);
    Send(0);
    return 0;
  }

  for (int i = id + 1; i <= id + nodes/2; i++) {
    int *cnt = i < nodes ? post : pre;
    auto rd = get_range(i % nodes);
    for (int j = rd.first; j < rd.second; j++) {
      cnt[GetElement(j)]++;
    }
  }


  for (int i = MAXV; i > 0; i--) {
    pre[i-1] += pre[i];
  }
  for (int i = 1; i < MAXV; i++) {
    post[i] += post[i-1];
  }
  ll res = 0;
  for (int i = r.second-1; i >= r.first; i--) {
    int v = GetElement(i);
    res += pre[v+1];
    res += post[v-1];
    res += fenwick::sum(v-1);
    fenwick::add(v, 1);
  }

  if (id) {
    PutLL(0, res);
    Send(0);
  } else {
    for (int foo = NumberOfNodes(); foo > 1; foo--) {
      int s = Receive(-1);
      res += GetLL(s);
    }
    printf("%lld\n", res);
  }
}