summaryrefslogtreecommitdiffstats
path: root/Main/Python/2016/S4.py
blob: 1fdc065d25127da48a9cddab1746fcda5920535a (plain)
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
from queue import Queue

N = int(input())
riceballs = list(map(int, input().split()))


def find_operations(r, start=0, end=None):
	if end is None:
		end = len(r) - 1
	output = []
	for i in range(start, end):
		if i < len(r) - 1:
			if r[i] == r[i + 1]:
				output.append((i, i + 1))
		if i < len(r) - 2:
			if r[i] == r[i + 2]:
				output.append((i, i + 2))
	return output


def clean(ops, start=0, end=None):
	if end is None:
		end = len(ops)
	output = []
	for op in ops:
		a, b = op
		if not (start < a < end or start < b < end):
			if a > end:
				a -= 1
			if b > end:
				b -= 1
			output.append((a, b))
	return output


q = Queue()
q.put((riceballs, find_operations(riceballs)))
visited = set()
output = 0
while not q.empty():
	r, ops = q.get()
	if tuple(r) in visited:
		continue
	visited.add(tuple(r))

	output = max(output, max(r))

	for op in ops:
		temp = r[:]
		a, b = op
		if a > len(temp)-1 or b > len(temp)-1 or temp[a] != temp[b]:
			continue

		if b - a == 1:
			temp = temp[:op[0]] + [temp[op[0]] * 2] + temp[op[1] + 1:]
			start, end = max(0, a - 2), min(a + 2, len(temp))
			temp2 = find_operations(temp, start, end) + ops
			q.put((temp, temp2))
		else:
			temp = temp[:op[0]] + [sum(temp[a:b + 1])] + temp[op[1] + 1:]
			start, end = max(0, a - 2), min(a + 2, len(temp))
			temp2 = find_operations(temp, start, end) + ops
			q.put((temp, temp2))
print(output)