思路:
令dp[i]表示前i个的最大舒适度。则如果区间[j, i](1 < j <= i)满足条件,有如下转移:dp[i] = max(dp[i], dp[j - 1] + cur)。其中,cur为区间[j, i]的舒适度。
实现:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 const int MAXN = 5005; 7 int n, a[MAXN], l[MAXN], r[MAXN], vis[MAXN], dp[MAXN]; 8 9 int main() 10 { 11 cin >> n; 12 for (int i = 1; i <= n; i++) 13 cin >> a[i]; 14 for (int i = 1; i <= n; i++) 15 { 16 if (!l[a[i]]) l[a[i]] = i; 17 r[a[i]] = i; 18 } 19 for (int i = 1; i <= n; i++) 20 { 21 dp[i] = dp[i - 1]; 22 int cur = 0; 23 memset(vis, 0, sizeof(vis)); 24 int minL = l[a[i]]; 25 for (int j = i; j >= 1; j--) 26 { 27 if (r[a[j]] > i) break; 28 if (!vis[a[j]]) vis[a[j]] = 1, cur ^= a[j]; 29 minL = min(minL, l[a[j]]); 30 if (minL >= j) dp[i] = max(dp[i], dp[j - 1] + cur); 31 } 32 } 33 cout << dp[n] << endl; 34 return 0; 35 }