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
#include <iostream>
#include <cstdio>
#include <vector>

using namespace std;

int n, s, licz;
long long m, a, x, INF, bity, result, res;
long long pot[65];

vector < pair <long long, long long> > v, w;

int main ()
{
	INF = 5000000000000000000LL;
	pot[0] = 1;
	for (int i = 1; i < 64; ++i) pot[i] = pot[i - 1] * 2;
	scanf("%d%lld", &n, &m);
	v.push_back(make_pair(-1, 0));
	while (n--)
	{
		if (v.back().first == m) v.pop_back();
		v.push_back(make_pair(m, INF));
		scanf("%lld", &a);
		w.clear();
		result = INF * -1;
		s = v.size() - 1;
		for (int i = 0; i < s; ++i)
		{
			x = v[i].first + 1;
			licz = 0;
			bity = 0;
			while (pot[licz] <= x)
			{
				if (x & pot[licz]) bity++;
				licz++;
			}
			res = v[i].second + a * bity;
			if (res > result)
			{
				w.push_back(make_pair(x, res));
				result = res;
			}
			if (a >= 0)
			{
				for (int j = 0; ; ++j)
				{
					if (x & pot[j]) continue;
					x ^= pot[j];
					if (x > v[i + 1].first) break;
					res += a;
					if (res > result)
					{
						w.push_back(make_pair(x, res));
						result = res;
					}
				}
			}
			else if (bity > 1)
			{
				licz = 0;
				for (int j = 0; ; ++j)
				{
					if (x & pot[j])
					{
						licz++;
						bity--;
						x ^= pot[j];
						res -= a;
					}
					else if (licz >= 2)
					{
						bity++;
						x ^= pot[j];
						res += a;
						if (x > v[i + 1].first) break;
						if (res > result)
						{
							w.push_back(make_pair(x, res));
							result = res;
						}
						if (bity == 1) break;
						bity--;
						x ^= pot[j];
						res -= a;
						licz = 1;
					}
				}
			}
		}
		v.clear();
		v = w;
	}
	result = v.back().second;
	printf("%lld\n", result);
	return 0;
}