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
//#include "rpa_linux/includes/message.h"
#include "message.h"
#include "teatr.h"
#include "bits/stdc++.h"

using namespace std;

#define dbg(...) //
//#define dbg printf

using ull = unsigned long long;


void add_to(ull larger_than[6], int value, int elements=1) {
    for (int i = 0; i < value; ++i) {
        larger_than[i] += elements;
    }
}

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

    {
        // 1st pass, find in every chunk

        int start = (int) (((ull) node * (ull) n) / ((ull) nodes));
        int end = (int) (((ull) (node + 1) * (ull) n) / ((ull) nodes));

        // so far number of elements larger than index
        ull larger_than[6] = {0};
        int values[6] = {0};
        ull conflicts = 0;

        for (int i = start; i < end; ++i) {
            auto element = GetElement(i);
            conflicts += larger_than[element];

            values[element]++;
            add_to(larger_than, element);

        }

        dbg("%llu\n", conflicts);


        // send nr of conflicts to master
        PutLL(0, conflicts);
        // and number of elements with values
        PutInt(0, values[1]);
        PutInt(0, values[2]);
        PutInt(0, values[3]);
        PutInt(0, values[4]);
        PutInt(0, values[5]);

        Send(0);
    }

    // receive on master, else stop
    if (MyNodeId() != 0) {
        return 0;
    }

    {
        dbg("\n\n");

        ull conflicts = 0;
        ull larger_than[6] = {0};
        for (int i = 0; i < nodes; ++i) {
            Receive(i);
            conflicts += GetLL(i);

            int values[6];

            for (int j = 1; j <= 5; ++j) {
                values[j] = GetInt(i);
                conflicts += larger_than[j] * values[j];
            }
            for (int j = 1; j <= 5; ++j) {
                add_to(larger_than, j, values[j]);
            }
        }

        printf("%llu\n", conflicts);
    }

    return 0;
}