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
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include "kanapka.h"
#include "message.h"

#include <cstdio>
#include <limits>

inline long long from2(long long id, long long round)
{
	return id | (1ll << round);
}

inline long long from(long long id, long long nodes, long long round)
{
	long long from =  from2(id, round);
	return from >= nodes ? -1 : from;
}

inline bool sending(long long id, long long round)
{
	return ((id >> round) & 1ll) == 1ll;
}

inline long long to(long long id, long long round)
{
	return ((id) & (-1ll << ((round) + 1)));
}

inline bool ended(long long id, long long nodes, long long round)
{
	return (id == 0ll && from2(id, round) >= nodes) || (round >= 1ll && sending(id, round - 1));
}

#define MAX_NODES 100

long long m[MAX_NODES], p[MAX_NODES], s[MAX_NODES], t[MAX_NODES];

int main()
{
	int id = MyNodeId();
	int nodes = NumberOfNodes();

	long long n = GetN();

	if(id >= n)
		return 0;
	if(nodes > n)
		nodes = n;

	long long length = n / nodes;
	long long start = id * length;
	long long end = id == nodes - 1 ? n : start + length;

	m[id] = 0;
	p[id] = 0;
	s[id] = 0;
	t[id] = 0;

	long long acc = 0;

	for(long long i = start; i < end; ++i)
	{
		long long taste = GetTaste(i);

		acc += taste;
		if(acc > 0)
			acc = 0;
		if(m[id] > acc)
			m[id] = acc;

		t[id] += taste;

		if(p[id] > t[id])
			p[id] = t[id];
	}

	acc = 0;

	for(long long i = end - 1; i >= start; --i)
	{
		acc += GetTaste(i);

		if(s[id] > acc)
			s[id] = acc;
	}

	for(int round = 0; !ended(id, nodes, round); ++round)
	{
		if(sending(id, round))
		{
			long long destination = to(id, round);

			PutLL(destination, m[id]);
			PutLL(destination, p[id]);
			PutLL(destination, s[id]);
			PutLL(destination, t[id]);

			Send(destination);
		}
		else
		{
			long long source = from(id, nodes, round);

			if(source == -1)
				continue;

			Receive(source);

			m[source] = GetLL(source);
			p[source] = GetLL(source);
			s[source] = GetLL(source);
			t[source] = GetLL(source);

			if(m[id] > m[source])
				m[id] = m[source];

			acc = s[id] + p[source];
			if(m[id] > acc)
				m[id] = acc;

			acc = t[id] + p[source];
			if(p[id] > acc)
				p[id] = acc;

			acc = s[id] + t[source];
			s[id] = s[source];
			if(s[id] > acc)
				s[id] = acc;

			t[id] += t[source];
		}
	}

	if(id == 0)
		printf("%lld\n", t[0] - m[0]);

	return 0;
}