给出n个元素的键与值当两个相邻元素的键不互质时,可以使它们消失并对结果贡献它们的值,问最大结果
定义f[i][j]为[i,j]的答案则如果中间已经取完了则l,r可以合并
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int T, N;
int Key[305], Val[305];
long long sum[305];
long long f[305][305];
int GCD(int a, int b) {
return b == 0 ? a : GCD(b, a % b);
}
int main() {
scanf("%d", &T);
for(int kase = 1; kase <= T; kase++) {
scanf("%d", &N);
for(int i = 1; i <= N; i++) {
scanf("%d", &Key[i]);
}
for(int i = 1; i <= N; i++) {
scanf("%d", &Val[i]);
}
for(int i = 1; i <= N; i++) {
sum[i] = sum[i - 1] + Val[i];
}
memset(f, 0, sizeof(f));
for(int len = 2; len <= N; len++) {
for(int i = 1; i + len - 1 <= N; i++) {
int j = i + len - 1;
if(GCD(Key[i], Key[j]) != 1 &&
(len == 2 || f[i + 1][j - 1] == sum[j - 1] - sum[i])) {
f[i][j] = max(f[i][j],
f[i + 1][j - 1] + Val[i] + Val[j]);
}
for(int h = i; h < j; h++) {
f[i][j] = max(f[i][j], f[i][h] + f[h + 1][j]);
}
}
}
cout << f[1][N] << endl;
}
return 0;
}