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
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include "krazki.h"
#include "message.h"

using std::vector;

int main() {

    int N = NumberOfNodes();
    int node = MyNodeId();

    int n = PipeHeight();
    int m = NumberOfDiscs();
    int lenPerNode = n / N;
    int start = lenPerNode * node;
    int end = (node == N - 1) ? n : lenPerNode * (node + 1);
    int size = end - start;

    vector<long long> pipe((unsigned int) size);
    long long int min = LONG_LONG_MAX;
    for (int i = 0; i < size; i++) {
        long long hole = HoleDiameter(start + i + 1);
        min = std::min(hole, min);
        pipe[i] = min;
    }

//    std::cout << "subpipe " << node << ": [";
//    for (auto &item : pipe) {
//        std::cout << item << "-";
//    }
//    std::cout << '\b' << "]" << std::endl;

    int stack = 0;
    bool (*comp)(const long long int &, const long long int &)=[](const long long int &k, const long long int &a) {
                return k > a;
            };
    auto last = pipe.end();
    for (int i = 0; i < m; i++) {
        long long int kr = DiscDiameter(i + 1);
        vector<long long int>::iterator it;
        if (kr <= pipe[size - 1])
            it = pipe.end();
        else
            it = std::upper_bound(pipe.begin(), last, kr, comp);
        int idx;
        if (it == pipe.end()) {
            if (node == N-1)
                idx = size;
            else
                continue;
        } else {
            idx = (int) (it - pipe.begin());
            last = it;
        }
        stack = std::min(idx - size, stack) - 1;
    }
    if (node != 0) {
        PutInt(0, -stack);
        Send(0);
    } else {
        std::vector<int> all((unsigned long long)(N));
        all[0] = -stack;

        for (int i = 1; i < N; i++) {
            const int src = Receive(-1);
            all[src] = GetInt(src);
        }

        int max_stack = n;
        int acc = 0;
        for (int i = N - 1; i >= 0; i--) {
//            std::cout << "subpipe len "<< i << ": "<< all[i] << std::endl;
            int c_size = ((i == N - 1) ? n : lenPerNode * (i + 1)) - (lenPerNode * i);
            int c_stack = all[i];
            if (c_stack != 0) {
                max_stack = std::min(max_stack, n - acc - c_stack);
//                std::cout << "aprox len: " << (n - acc - c_stack) << std::endl;
            }
            acc += c_size;
        }

        std::cout << std::max(0, max_stack + 1) << std::endl;
    }

}