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
#include "message.h"
#include "teatr.h"

#include <cstdio>
#include <algorithm>

using LL = long long;

constexpr int max_element = 1000000;
constexpr int size = max_element + 2;
constexpr int block = 1000000;

LL counts[size], A[size];

#define LSB(i) ((i) & -(i))
#define SUM(x) \
  ({int i = (x); LL s = 0; while (i > 0) s += A[i], i -= LSB(i); s;})
#define INC(x) \
  ({int i = (x); while (i < size) ++A[i], i += LSB(i);})

int main()
{
  int id = MyNodeId();
  int n  = GetN();
  int nodes = NumberOfNodes();

  // range [lower, upper)
  int lower = id * block;
  int upper = (id + 1) * block;

  if (lower >= n) {
    PutLL(0, 0);
    Send(0);
    return 0;
  }
  upper = std::min(upper, n);

  LL result = 0;

  for (int i = upper; i < n; i++) counts[GetElement(i)]++;
  for (int i = 1; i <= max_element; i++) counts[i] += counts[i - 1];

  for (int i = upper - 1; i >= lower; i--) {
    int e = GetElement(i);
    result += SUM(e - 1) + counts[e - 1];
    INC(e);
  }

  if (id != 0) {
    PutLL(0, result);
    Send(0);
  }
  else {
    for (int i = 1; i < nodes; i++) {
      int sender_id = Receive(-1);
      result += GetLL(sender_id);
    }

    std::printf("%lld\n", result);
  }
}