Codeforces Round #416 (Div. 2)-C. Vladik and Memorable Trip

原题链接

C. Vladik and Memorable Trip
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 ai 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 rXOR 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 a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai 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
dp[i]表示对于1..i最大的comfort值;

对于每个目的地求出数组中最左边和最右边人的索引node[].l, node[].r

#include 
#define maxn 5005
using namespace std;

struct Node {
	int l, r;
}node[maxn];
int vis[maxn], num[maxn], dp[maxn];
int main() {
//	freopen("in.txt", "r", stdin);
	int n;
	scanf("%d", &n);
	for(int i = 1; i <= n; i++) {
		scanf("%d", num+i);
	}
	for(int i = n; i >= 1; i--) {
		if(node[num[i]].r == 0) {
			node[num[i]].r = node[num[i]].l = i;
		}
		else
		 node[num[i]].l = i;
	}
	for(int i = 1; i <= n; i++) {
		int ans = 0, mins = 100000;
		memset(vis, 0, sizeof(vis));
		for(int j = i; j >= 1; j--) {
			if(node[num[j]].r > i)
			 break;
			mins = min(node[num[j]].l, mins);
			if(vis[num[j]] == 0) {
				ans ^= num[j];
				vis[num[j]] = 1;
			}
			if(j == mins) {
				dp[i] = max(dp[i], ans+dp[j-1]);
			}
		}
		dp[i] = max(dp[i], dp[i-1]);
	}
	cout << dp[n] << endl;
	
	return 0;
}


你可能感兴趣的:(动态规划)