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

using namespace std;

const int MAX = 1e6;

template<typename T> class fenwick_t {
 public:
  vector<T> fenw;
  int n;

  fenwick_t(int n):n(n) {
    fenw.resize(n);
  }

  void modify(int x, T value) {
    while (x < n) {
      fenw[x] += value;
      x |= x + 1;
    }
  }

  T query(int x) {
    T result{};
    while (x >= 0) {
      result += fenw[x];
      x = (x & x + 1) - 1;
    }
    return result;
  }
};

int main() {
  int n = GetN(), nblock = 1;
  while ((nblock + 2) * (nblock + 1) / 2 <= NumberOfNodes()) {
    ++nblock;
  }
  int sblock = (n + nblock - 1) / nblock;
  if (MyNodeId() >= (nblock + 1) * nblock / 2) {
    return 0;
  }
  long long answer = 0;
  if (MyNodeId() < nblock) {
    int l = MyNodeId() * sblock, r = min(n, (MyNodeId() + 1) * sblock);
    fenwick_t<int> fenwick(MAX);
    for (int i = r - 1; i >= l; --i) {
      int x = GetElement(i) - 1;
      answer += fenwick.query(x - 1);
      fenwick.modify(x, 1);
    }
  } else {
    int current = MyNodeId() - nblock, l = -1, r = -1;
    for (int i = 0; i < nblock; ++i) {
      for (int j = 0; j < i; ++j) {
        if (!current) {
          l = j;
          r = i;
          goto outer;
        }
        --current;
      }
    }
    outer:;
    vector<int> cnt(MAX + 1);
    int lr = r * sblock, rr = min(n, (r + 1) * sblock);
    for (int i = lr; i < rr; ++i) {
      ++cnt[GetElement(i)];
    }
    for (int i = 1; i <= MAX; ++i) {
      cnt[i] += cnt[i - 1];
    }
    int ll = l * sblock, rl = min(n, (l + 1) * sblock);
    for (int i = ll; i < rl; ++i) {
      answer += cnt[GetElement(i) - 1];
    }
  }
  if (MyNodeId()) {
    PutLL(0, answer);
    Send(0);
  } else {
    for (int i = 1; i < (nblock + 1) * nblock / 2; ++i) {
      Receive(i);
      answer += GetLL(i);
    }
    printf("%lld\n", answer);
  }
  return 0;
}