Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:

Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code a_{i} is known (the code of the city in which they are going to).

Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.

Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.

Total comfort of a train trip is equal to sum of comfort for each segment.

Help Vladik to know maximal possible total comfort.


-----Input-----

First line contains single integer n (1 ≤ n ≤ 5000) — number of people.

Second line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 5000), where a_{i} denotes code of the city to which i-th person is going.


-----Output-----

The output should contain a single integer — maximal possible total comfort.


-----Examples-----
Input
6
4 4 2 5 2 3

Output
14

Input
9
5 1 3 1 5 2 4 2 5

Output
9



-----Note-----

In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14

In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.

Source: codeforces | Difficulty: HARD
Tags: Dynamic programming

Implementation


Solutions:
import sys
inf = 1 << 30

def solve():
	n = int(input())
	a = [0] + [int(i) for i in input().split()]
	maxi = max(a)
	f = [-1] * (maxi + 1)
	for i in range(1, n + 1):
		if f[a[i]] == -1:
			f[a[i]] = i
	l = [-1] * (maxi + 1)
	for i in range(n, 0, -1):
		if l[a[i]] == -1:
			l[a[i]] = i
	dp = [0] * (n + 1)
	for i in range(1, n + 1):
		dp[i] = dp[i - 1]
		if i == l[a[i]]:
			min_l = f[a[i]]
			max_r = i
			used = set()
			v = 0
			for j in range(i, -1, -1):
				min_l = min(min_l, f[a[j]])
				max_r = max(max_r, l[a[j]])
				if a[j] not in used:
					v ^= a[j]
					used.add(a[j])
				if max_r > i:
					break
				if j == min_l:
					dp[i] = max(dp[i], dp[j - 1] + v)
					break
	ans = dp[n]
	print(ans)
solve()


import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(11)]
prime[0] = prime[1] = False

def SieveOfEratosthenes(n=10):
	p = 2
	c = 0
	while p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				prime[i] = False
		p += 1

class DSU:

	def __init__(self, R, C):
		self.par = range(R * C + 1)
		self.rnk = [0] * (R * C + 1)
		self.sz = [1] * (R * C + 1)

	def find(self, x):
		if self.par[x] != x:
			self.par[x] = self.find(self.par[x])
		return self.par[x]

	def union(self, x, y):
		(xr, yr) = (self.find(x), self.find(y))
		if xr == yr:
			return
		if self.rnk[xr] < self.rnk[yr]:
			(xr, yr) = (yr, xr)
		if self.rnk[xr] == self.rnk[yr]:
			self.rnk[xr] += 1
		self.par[yr] = xr
		self.sz[xr] += self.sz[yr]

	def size(self, x):
		return self.sz[self.find(x)]

	def top(self):
		return self.size(len(self.sz) - 1) - 1

class LazySegTree:

	def __init__(self, _op, _e, _mapping, _composition, _id, v):

		def set(p, x):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			_d[p] = x
			for i in range(1, _log + 1):
				_update(p >> i)

		def get(p):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			return _d[p]

		def prod(l, r):
			assert 0 <= l <= r <= _n
			if l == r:
				return _e
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r >> i)
			sml = _e
			smr = _e
			while l < r:
				if l & 1:
					sml = _op(sml, _d[l])
					l += 1
				if r & 1:
					r -= 1
					smr = _op(_d[r], smr)
				l >>= 1
				r >>= 1
			return _op(sml, smr)

		def apply(l, r, f):
			assert 0 <= l <= r <= _n
			if l == r:
				return
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r - 1 >> i)
			l2 = l
			r2 = r
			while l < r:
				if l & 1:
					_all_apply(l, f)
					l += 1
				if r & 1:
					r -= 1
					_all_apply(r, f)
				l >>= 1
				r >>= 1
			l = l2
			r = r2
			for i in range(1, _log + 1):
				if l >> i << i != l:
					_update(l >> i)
				if r >> i << i != r:
					_update(r - 1 >> i)

		def _update(k):
			_d[k] = _op(_d[2 * k], _d[2 * k + 1])

		def _all_apply(k, f):
			_d[k] = _mapping(f, _d[k])
			if k < _size:
				_lz[k] = _composition(f, _lz[k])

		def _push(k):
			_all_apply(2 * k, _lz[k])
			_all_apply(2 * k + 1, _lz[k])
			_lz[k] = _id
		_n = len(v)
		_log = _n.bit_length()
		_size = 1 << _log
		_d = [_e] * (2 * _size)
		_lz = [_id] * _size
		for i in range(_n):
			_d[_size + i] = v[i]
		for i in range(_size - 1, 0, -1):
			_update(i)
		self.set = set
		self.get = get
		self.prod = prod
		self.apply = apply
MIL = 1 << 20

def makeNode(total, count):
	return total * MIL + count

def getTotal(node):
	return math.floor(node / MIL)

def getCount(node):
	return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)

def nodeOp(node1, node2):
	return node1 + node2
	return makeNode(getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2))
identityMapping = -1

def mapping(tag, node):
	if tag == identityMapping:
		return node
	count = getCount(node)
	return makeNode(tag * count, count)

def composition(mapping1, mapping2):
	return mapping1 if mapping1 != identityMapping else mapping2

def memodict(f):

	class memodict(dict):

		def __missing__(self, key):
			ret = self[key] = f(key)
			return ret
	return memodict().__getitem__

def pollard_rho(n):
	if n & 1 == 0:
		return 2
	if n % 3 == 0:
		return 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			prev = p
			p = p * p % n
			if p == 1:
				return math.gcd(prev - 1, n)
			if p == n - 1:
				break
		else:
			for i in range(2, n):
				(x, y) = (i, (i * i + 1) % n)
				f = math.gcd(abs(x - y), n)
				while f == 1:
					(x, y) = ((x * x + 1) % n, (y * y + 1) % n)
					y = (y * y + 1) % n
					f = math.gcd(abs(x - y), n)
				if f != n:
					return f
	return n

@memodict
def prime_factors(n):
	if n <= 1:
		return Counter()
	f = pollard_rho(n)
	return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
	factors = [1]
	for (p, exp) in prime_factors(n).items():
		factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
	return factors

def all_factors(n):
	(small, large) = ([], [])
	for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
		if not n % i:
			small.append(i)
			large.append(n // i)
	if small[-1] == large[-1]:
		large.pop()
	large.reverse()
	small.extend(large)
	return small

def binarySearch(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = n
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			res = mid
			right = mid - 1
		else:
			left = mid + 1
	return res

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = -1
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = mid
			left = mid + 1
	return res
t = 1
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	lmost = [99999999] * 5001
	rmost = [-1] * 5001
	dp = [0] * 5001
	for i in range(n):
		lmost[a[i]] = min(lmost[a[i]], i)
	for i in range(n - 1, -1, -1):
		rmost[a[i]] = max(rmost[a[i]], i)
	for i in range(n):
		val = 0
		m = lmost[a[i]]
		dp[i] = dp[i - 1]
		for j in range(i, -1, -1):
			if rmost[a[j]] > i:
				break
			if rmost[a[j]] == j:
				val = val ^ a[j]
			m = min(m, lmost[a[j]])
			if m == j:
				dp[i] = max(dp[i], dp[j - 1] + val)
	print(max(dp))


import cProfile
from sys import stdin, stderr
from heapq import heappush, heappop
from random import randrange

def readInts():
	return map(int, stdin.readline().strip().split())

def print_err(*args, **kwargs):
	print(*args, file=stderr, **kwargs)

def create_heap(ns):
	mins = {}
	maxs = {}
	for (i, v) in enumerate(ns):
		if v not in mins:
			mins[v] = i
		maxs[v] = i
	ranges = {}
	rheap = []
	for (v, minix) in mins.items():
		maxix = maxs[v]
		ranges[v] = (minix, maxix)
		heappush(rheap, (maxix - minix + 1, minix))
	return (ranges, rheap)

def create_heap2(ns):
	mins = {}
	maxs = {}
	for (i, v) in enumerate(ns):
		if v not in mins:
			mins[v] = i
		maxs[v] = i
	ranges = {}
	rheap = []
	for (v, minix) in mins.items():
		maxix = maxs[v]
		ranges[v] = (minix, maxix)
		heappush(rheap, (maxix - minix + 1, minix, set([v])))
	return (ranges, rheap)

def solve(n, ns):
	(ranges, pq) = create_heap(ns)
	resolved_ranges = {}
	while pq:
		(w, lo_ix) = heappop(pq)
		if lo_ix in resolved_ranges:
			continue
		tot_subs = 0
		tot_x = 0
		ix = lo_ix
		fail = False
		xsv = set()
		while ix < lo_ix + w:
			v = ns[ix]
			(lo2, hi2) = ranges[v]
			if lo2 < lo_ix or hi2 > lo_ix + w - 1:
				lo2 = min(lo2, lo_ix)
				hi2 = max(hi2, lo_ix + w - 1)
				heappush(pq, (hi2 - lo2 + 1, lo2))
				fail = True
				break
			if ix in resolved_ranges:
				(rhi_ix, c, x) = resolved_ranges[ix]
				tot_x ^= x
				tot_subs += c
				ix = rhi_ix + 1
				continue
			if v not in xsv:
				xsv.add(v)
				tot_x ^= v
			ix += 1
		if not fail:
			resolved_ranges[lo_ix] = (lo_ix + w - 1, max(tot_x, tot_subs), tot_x)
	ix = 0
	tot_c = 0
	while ix < n:
		(rhi, c, _) = resolved_ranges[ix]
		ix = rhi + 1
		tot_c += c
	return tot_c

def solve2(n, ns):
	(ranges, pq) = create_heap(ns)
	resolved_ranges = {}
	while pq:
		(w, lo_ix, xs) = heappop(pq)
		print(len(pq), w, lo_ix, xs)
		if lo_ix in resolved_ranges:
			print(len(pq))
			continue
		tot_subs = 0
		tot_x = 0
		for x in xs:
			tot_x ^= x
		ix = lo_ix
		fail = False
		while ix < lo_ix + w:
			v = ns[ix]
			if v in xs:
				ix += 1
				continue
			if ix in resolved_ranges:
				(rhi_ix, c, x) = resolved_ranges[ix]
				tot_x ^= x
				tot_subs += c
				ix = rhi_ix + 1
				continue
			(lo2, hi2) = ranges[v]
			lo2 = min(lo2, lo_ix)
			hi2 = max(hi2, lo_ix + w - 1)
			xs.add(v)
			heappush(pq, (hi2 - lo2 + 1, lo2, xs))
			fail = True
			break
		if not fail:
			resolved_ranges[lo_ix] = (lo_ix + w - 1, max(tot_x, tot_subs), tot_x)
	ix = 0
	tot_c = 0
	while ix < n:
		(rhi, c, _) = resolved_ranges[ix]
		ix = rhi + 1
		tot_c += c
	return tot_c

def test():
	n = 5000
	ns = []
	for _ in range(n):
		ns.append(randrange(1, n // 2))
	print(solve(n, ns))

def run():
	(n,) = readInts()
	ns = list(readInts())
	print(solve(n, ns))
run()


inf = 1 << 30
n = int(input())
a = [0] + [int(i) for i in input().split()]
maxi = max(a)
f = [-1] * (maxi + 1)
for i in range(1, n + 1):
	if f[a[i]] == -1:
		f[a[i]] = i
l = [-1] * (maxi + 1)
for i in range(n, 0, -1):
	if l[a[i]] == -1:
		l[a[i]] = i
dp = [0] * (n + 1)
for i in range(1, n + 1):
	dp[i] = dp[i - 1]
	if i == l[a[i]]:
		min_l = f[a[i]]
		max_r = i
		vis = set()
		v = 0
		for j in range(i, -1, -1):
			min_l = min(min_l, f[a[j]])
			max_r = max(max_r, l[a[j]])
			if a[j] not in vis:
				v ^= a[j]
				vis.add(a[j])
			if max_r > i:
				break
			if j == min_l:
				dp[i] = max(dp[i], dp[j - 1] + v)
				break
print(dp[n])


n = int(input())
a = input()
b = list(map(int, a.strip().split()))
L = {}
R = {}
vis = {}
dp = []
for i in range(n):
	if L.get(b[i]) == None:
		L[b[i]] = i
	R[b[i]] = i
	dp.append(0)
dp.append(0)
for i in range(n):
	vis.clear()
	if i > 0:
		dp[i] = dp[i - 1]
	ans = 0
	Min = i
	j = i
	while j >= 0:
		t = b[j]
		if vis.get(t) == None:
			if R[t] > i:
				break
			Min = min(Min, L[t])
			ans ^= t
			vis[t] = 1
		if j <= Min:
			dp[i] = max(dp[i], dp[j - 1] + ans)
		j -= 1
print(dp[n - 1])


def dp():
	dparr = [0] * len(sections)
	for i in range(len(sections) - 1, -1, -1):
		(_, curend, curcomfort) = sections[i]
		nextsection = i + 1
		try:
			while sections[nextsection][0] <= curend:
				nextsection += 1
		except IndexError:
			inc = curcomfort
		else:
			inc = curcomfort + dparr[nextsection]
		exc = 0 if i == len(sections) - 1 else dparr[i + 1]
		dparr[i] = max(inc, exc)
	return dparr[0]
n = int(input())
zs = list(map(int, input().split()))
sections = []
seenstartz = set()
first = {z: i for (i, z) in reversed(list(enumerate(zs)))}
last = {z: i for (i, z) in enumerate(zs)}
for (start, z) in enumerate(zs):
	if z in seenstartz:
		continue
	seenstartz.add(z)
	end = last[z]
	comfort = 0
	i = start
	while i <= end:
		if first[zs[i]] < start:
			break
		if i == last[zs[i]]:
			comfort ^= zs[i]
		end = max(end, last[zs[i]])
		i += 1
	else:
		sections.append((start, end, comfort))
ans = dp()
print(ans)


n = int(input())
a = list(map(int, input().split()))
(R, L) = ({}, {})
for i in range(n):
	if a[i] not in L:
		L[a[i]] = i
	R[a[i]] = i
dp = [0] * (n + 1)
for i in range(n):
	dp[i] = dp[i - 1]
	if R[a[i]] != i:
		continue
	s = 0
	l = L[a[i]]
	for j in range(i, -1, -1):
		if R[a[j]] <= i:
			if R[a[j]] == j:
				s ^= a[j]
			l = min(l, L[a[j]])
			if j == l:
				dp[i] = max(dp[i], dp[j - 1] + s)
		else:
			break
print(dp[n - 1])


n = int(input())
a = list(map(int, input().split()))
dp = [0] * (n + 1)
(f, l) = ({}, {})
for i in range(len(a)):
	x = a[i]
	if x not in f:
		f[x] = i
	l[x] = i
pr = [a[0]]
for i in range(1, len(a) + 1):
	j = i
	mx = 0
	nums = set()
	curxor = 0
	b = i
	while j > 0:
		x = a[j - 1]
		if l[x] > i - 1:
			break
		if x not in nums:
			nums.add(x)
			curxor ^= x
		b = min(b, f[x] + 1)
		if b == j:
			mx = max(mx, dp[j - 1] + curxor)
		j -= 1
	dp[i] = max(dp[i - 1], mx)
print(dp[len(a)])


n = int(input())
a = list(map(int, input().split()))
lmost = [99999999] * 5001
rmost = [-1] * 5001
dp = [0] * 5001
for i in range(n):
	lmost[a[i]] = min(lmost[a[i]], i)
for i in range(n - 1, -1, -1):
	rmost[a[i]] = max(rmost[a[i]], i)
for i in range(n):
	val = 0
	m = lmost[a[i]]
	dp[i] = dp[i - 1]
	for j in range(i, -1, -1):
		if rmost[a[j]] > i:
			break
		if rmost[a[j]] == j:
			val = val ^ a[j]
		m = min(m, lmost[a[j]])
		if m == j:
			dp[i] = max(dp[i], dp[j - 1] + val)
print(max(dp))


people = int(input())
cities = list(map(int, input().split()))
maximum = max(cities)
(last, first) = ([-1 for i in range(maximum + 1)], [float('inf') for i in range(maximum + 1)])
for i in range(people):
	first[cities[i]] = min(i, first[cities[i]])
	last[cities[i]] = max(i, last[cities[i]])
dp = [0 for i in range(people)]
dp[0] = cities[0] if last[cities[0]] == 0 else 0
for i in range(1, people):
	min_first = float('inf')
	max_last = -1
	used = set()
	xor = 0
	for j in range(i, -1, -1):
		min_first = min(min_first, first[cities[j]])
		max_last = max(max_last, last[cities[j]])
		if cities[j] not in used:
			xor ^= cities[j]
		used.add(cities[j])
		if min_first >= j and max_last <= i:
			if j != 0:
				dp[i] = max(dp[i], dp[j - 1] + xor)
			else:
				dp[i] = max(dp[i], xor)
	dp[i] = max(dp[i], dp[i - 1])
print(dp[-1])


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
n = int(input())
l = list(map(int, input().split()))
l = [-1] + l
dp = [0 for j in range(n + 1)]
d = defaultdict(int)
d1 = defaultdict(int)
for i in range(1, n + 1):
	d[l[i]] = max(d[l[i]], i)
	if d1[l[i]] == 0:
		d1[l[i]] = i
for i in range(1, n + 1):
	mi = n + 6
	ma = 0
	tot = set()
	cur = 0
	for j in range(i, -1, -1):
		if l[j] not in tot:
			cur ^= l[j]
			tot.add(l[j])
		ma = max(ma, d[l[j]])
		mi = min(mi, d1[l[j]])
		if ma <= i and mi >= j:
			dp[i] = max(dp[i], dp[j - 1] + cur)
		dp[i] = max(dp[i], dp[j])
print(dp[n])


import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
n = int(input())
b = list(map(int, input().split()))
first = dict()
last = dict()
for i in range(n):
	if b[i] not in first.keys():
		first[b[i]] = i + 1
	if b[n - i - 1] not in last.keys():
		last[b[n - i - 1]] = n - i
dp = [[-float('inf'), -float('inf')] for i in range(n + 1)]
dp[0] = [0, 0]
for i in range(1, n + 1):
	dp[i][0] = max(dp[i - 1])
	tot = 0
	l = dict()
	j = i
	val = 0
	while j >= 1:
		if last[b[j - 1]] == j:
			l[b[j - 1]] = 1
			val ^= b[j - 1]
			tot += 1
		if first[b[j - 1]] == j:
			tot += -1
		if b[j - 1] not in l.keys():
			break
		elif tot == 0:
			dp[i][1] = max(dp[i][1], max(dp[j - 1]) + val)
		j += -1
print(max(dp[n]))


from collections import Counter, defaultdict
R = lambda : map(int, input().split())
n = int(input())
arr = list(R())
cnts = Counter(arr)
dp = [0] * (n + 1)
for i in range(n):
	acc = defaultdict(int)
	(cnt, xor) = (0, 0)
	dp[i] = dp[i - 1]
	for j in range(i, -1, -1):
		acc[arr[j]] += 1
		if acc[arr[j]] == cnts[arr[j]]:
			cnt += 1
			xor = xor ^ arr[j]
		if len(acc) == cnt:
			dp[i] = max(dp[i], dp[j - 1] + xor)
print(dp[n - 1])


n = int(input())
a = [int(i) for i in input().split()]
prefix = dict()
suffix = dict()
for i in range(n):
	if a[i] not in prefix:
		prefix[a[i]] = i
	suffix[a[i]] = i
dp = [0 for i in range(n + 1)]
for i in range(n):
	dp[i] = dp[i - 1]
	if suffix[a[i]] != i:
		continue
	cur = 0
	min_ind = prefix[a[i]]
	for j in range(i, -1, -1):
		if suffix[a[j]] <= i:
			if suffix[a[j]] == j:
				cur = cur ^ a[j]
			min_ind = min(min_ind, prefix[a[j]])
			if j == min_ind:
				dp[i] = max(dp[i], dp[j - 1] + cur)
		else:
			break
print(dp[n - 1])


length = int(input())
array = [0] + [int(x) for x in input().split()]
dp = [0] * (length + 1)
end = [0] * 5001
start = [5001] * 5001
vis = [0] * 5001
for i in range(1, length + 1):
	start[array[i]] = min(start[array[i]], i)
	end[array[i]] = max(end[array[i]], i)
for i in range(1, length + 1):
	dp[i] = dp[i - 1]
	chk = [0] * 5001
	ll = i
	cur = 0
	for j in range(i, 0, -1):
		ll = min(ll, start[array[j]])
		if end[array[j]] > i:
			break
		if chk[array[j]] == 0:
			cur = array[j] ^ cur
			chk[array[j]] = 1
		if ll == j:
			dp[i] = max(dp[i], dp[j - 1] + cur)
print(dp[length])