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

typedef struct {
    long long total;
    long long worst;
    long long left;
    long long right;
} chunk_t;

void merge(chunk_t* first, chunk_t* second)
{
    if (first->worst > second->worst) {
        first->worst = second->worst;
    }
    if (first->worst > (first->right + second->left)) {
        first->worst = first->right + second->left;
    }

    if (first->left > first->total + second->left) {
        first->left = first->total + second->left ;
    }

    first->right = (first->right + second->total < second->right) ? first->right + second->total : second->right;

    first->total += second->total;
}

int main()
{
    long long n = GetN();
    int nodes = NumberOfNodes();
    int myId = MyNodeId();
    long long chunkPerNode = (n + nodes - 1)/ nodes;
    chunk_t result;

    if (n < nodes) {
        if (myId == 0) {
            long long int i;
            chunk_t next;
            result.total = result.left = result.right = result.worst = GetTaste(0);
            for (i = 1; i < n; ++i) {
                next.total = next.left = next.right = next.worst = GetTaste(i);
                merge(&result, &next);
            }
            printf("%lld\n", result.total - result.worst);
        }
    } else {
        long long int i;
        chunk_t next;
        result.total = result.left = result.right = result.worst = GetTaste(chunkPerNode * myId);
        for (i = chunkPerNode * myId + 1; i < (chunkPerNode * (myId + 1)) && i < n; ++i) {
            next.total = next.left = next.right = next.worst = GetTaste(i);
            merge(&result, &next);
        }
        
        if (myId > 0) {
            PutLL(0, result.total);
            PutLL(0, result.worst);
            PutLL(0, result.left);
            PutLL(0, result.right);
            Send(0);
        } else {
            chunk_t next;
            int j;
            for (j = 1; j < nodes; ++j) {
                Receive(j);
                next.total = GetLL(j); 
                next.worst = GetLL(j);
                next.left = GetLL(j); 
                next.right = GetLL(j); 
                merge(&result, &next);
            }
            printf("%lld\n", result.total - result.worst);
        }
    }
    return 0;
}