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
题目大意:给定一个序列,划分成若干个子序列,不用全部划分,子序列之间不能相交,相同的数字必须在同一子序列内,每个序列的价值是子序列内所有数的异或和,问这个序列划分后所有子序列的价值和最大是多少。
L,R数组记录每个数字出现的首尾位数,然后遍历每个数字的首尾区间,保证区间合法,同时扩展区间,dp处理累计价值。
#include <cstdio>
#include <cstring>
#include<algorithm>
using namespace std;
int l[5050],r[5050];
int ans[5050];
int a[5050];
int main(){
memset(l,127,sizeof(l));
memset(r,-127,sizeof(r));
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
cin>>a[i];
l[a[i]]=min(i,l[a[i]]);
r[a[i]]=max(i,r[a[i]]);//要先初始化才能比较
}
int cnt=0;
for(int i=1;i<=n;i++)
{
ans[i]=max(ans[i],ans[i-1]);
if(l[a[i]]!=i)
continue;
int k=a[i];
int d=r[a[i]];
int t=1;
for(int j=i+1;j<=d;j++)
{
if(l[a[j]]<i) //保证子序列合法
{
t=0;
break;
}
if(r[a[j]]>d) //扩展子序列
d=r[a[j]];
if(l[a[j]]==j)
k^=a[j];
}
if(t)
ans[d]=max(ans[d],ans[i]+k);
}
cout<<ans[n]<<endl;
}