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

#define NPERNODE 1024 * 1024

#define TABSZ 128 * 1024
long long tab[TABSZ * 2 + 7];

void tinit() {
    for (int i = TABSZ - 1; i > 0; --i)
        tab[i] = tab[2 * i] + tab[2 * i + 1];
}
void tadd(int i) {
    i += TABSZ;
    while (i) {
        tab[i]++;
        i /= 2;
    }
}
long long tget(int from, int to) {
    long long ret = 0;
    from += TABSZ - 1;
    to += TABSZ + 1;
    while ((from / 2) != (to / 2)) {
        if (!(from & 1))
            ret += tab[from + 1];
        if (to & 1)
            ret += tab[to - 1];
        from /= 2;
        to /= 2;
    }
    return ret;
}

int main() {
    int x;
    int nn = NumberOfNodes();
    int n = GetN();
    int lstart = (MyNodeId()) * NPERNODE;
    int lend = (MyNodeId() + 1) * NPERNODE;
    long long* val = &tab[TABSZ];
    for (int i = lend; i < n; i++)
        ++val[GetElement(i)];
    tinit();

    long long lansw = 0;
    for (int i = std::min(lend - 1, n - 1); i >= lstart; i--) {
        x = GetElement(i);
        lansw += tget(0, x - 1);
        tadd(x);
    }

    if (MyNodeId() == 0) {
        for (int i = 1; i < nn; i++) {
            Receive(i);
            lansw += GetLL(i);
        }
        printf("%lli\n", lansw);
    } else {
        PutLL(0, lansw);
        Send(0);
    }
}