做法1 写T了;
这是做法2;
#include <bits/stdc++.h>
using namespace std;
#define ls rt<<1
#define rs rt<<1|1
#define LL long long
#define PI acos(-1.0)
#define eps 1e-8
#define Pair pair<double,double>
// notice
#define mod 998244353
#define MAXN 1e18
#define MS 2009
LL n,m;
LL a[MS];
struct node{
int pos;
LL val;
};
vector<node > vc[MS];
LL dp[MS][MS];
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
for(int i=1;i<=n;i++){
cin >> a[i];
}
for(int i=1;i<=n;i++){
LL t = -1 ,t1 = a[i] ,t2 = a[i];
for(int j=i-1;j>=1;j--){
t1 &= a[j];
t2 |= a[j];
LL cc = t1^t2;
if(cc != t){
t = cc;
vc[i].push_back({j,cc});
}
}
vc[i].push_back({1,-1});
}
//-- 初始化第 1 层信息
LL t1 = a[1], t2 = a[1];
for(int i=2;i<=n;i++){
t1 &= a[i];
t2 |= a[i];
LL cc = t1^t2;
dp[1][i] = cc;
}
//-- 计算每一层
for(int i=2;i<=m;i++){
for(int j=i+1;j<=n;j++){ //-- (j<=i)时 dp[i][j] 都设为 0
dp[i][j] = dp[i-1][j-1]; //-- 将第 j 个元素作为单个一组
for(int k=0;k<vc[j].size()-1;k++){
if(vc[j][k].pos <= i-1) break;
dp[i][j] = max(dp[i][j] ,dp[i-1][vc[j][k].pos-1] + vc[j][k].val);
}
}
}
cout << dp[m][n] << "\n";
return 0;
}
原文:https://www.cnblogs.com/Tecode/p/14817206.html