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

void send(int counts[5], long long arguments, int target) {
    for (size_t i = 0; i < 5; ++i) {
        PutInt(target, counts[i]);
    }
    PutLL(target, arguments);
    Send(target);
}

long long merge(int counts[5]) {
    int target = Receive(-1);
    int remote_counts[5];
    for (size_t i = 0; i < 5; ++i) {
        remote_counts[i] = GetInt(target);
    }
    long long arguments = GetLL(target);

    for (size_t i = 0; i < 4; ++i) {
        for (size_t j = i + 1; j < 5; ++j) {
            arguments += counts[i] * remote_counts[j];
        }
    }

    for (size_t i = 0; i < 5; ++i) {
        counts[i] += remote_counts[i];
    }

    return arguments;
}

int main() {
    int id = MyNodeId();
    int numb = NumberOfNodes();
    int N = GetN();

    int start = N * id / numb;
    int end = N * (id + 1) / numb;

    int counts[5] = {};
    long long arguments = {};
    for (int i = start; i < end; ++i) {
        int E = GetElement(i);

        if (E > 5) {
            return 123;
        }

        counts[E - 1]++;

        for (int j = E; j < 5; ++j) {
            arguments += counts[j];
        }
    }

    std::cerr << counts[0] << ":" << counts[1] << ":" << counts[2] << ":" << counts[3] << ":" << counts[4] << ":" << arguments << "\n";

    int mult = 1;

    while (mult * 2 < numb) {
        if ((id / mult) % 2 == 1) {
            arguments += merge(counts);
        } else if (id + mult < numb) {
            send(counts, arguments, id + mult);
            return 0;
        }

        mult *= 2;
    }

    if (id != numb - 1) {
        send(counts, arguments, numb - 1);
    } else {
        arguments += merge(counts);
        std::cout << arguments << "\n";
    }
}