分析:
连续消去
k
个数,可以表示为消去了若干次
f[i][j]
代表
i...j
这段数字可以全部消掉,那么这个状态可以由
f[i][k] and f[k+1][j]
,
f[i+1][j−1] and mark[a[i]−a[j]]
和
f[i+1][k−1] and f[k+1][j−1] and mark[a[i]−a[k]] and a[i]−a[k]==a[k]−a[j]
得到。
所以最终的
dp[i]=max(dp[i−1],dp[k]+f[k+1][j]?j−k:0)
复杂度:
o(n3)
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <string>
using namespace std;
typedef long long LL;
typedef vector <int> VI;
typedef pair <int,int> PII;
#define FOR(i,x,y) for(int i = x;i < y;++ i)
#define IFOR(i,x,y) for(int i = x;i > y;-- i)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
const int maxn = 330;
int n,m,a[maxn],dp[maxn],f[maxn][maxn];
map <int,int> hs;
void work(){
memset(f,0,sizeof(f));
FOR(i,0,n) f[i+1][i] = 1;
FOR(i,1,n) if(hs[a[i]-a[i-1]]) f[i-1][i] = 1;
FOR(i,2,n) if(a[i]-a[i-1] == a[i-1]-a[i-2] && hs[a[i]-a[i-1]]) f[i-2][i] = 1;
FOR(j,3,n){
IFOR(i,j-3,-1){
//if(hs[a[j]-a[j-1]]) f[i][j] |= f[i][j-2];
//if(hs[a[i+1]-a[i]]) f[i][j] |= f[i+2][j];
FOR(k,i+1,j) f[i][j] |= (f[i][k]&f[k+1][j]);
if(hs[a[j]-a[i]]) f[i][j] |= f[i+1][j-1];
FOR(k,i+1,j) if(a[j]-a[k] == a[k]-a[i] && hs[a[j]-a[k]])
f[i][j] |= (f[i+1][k-1]&f[k+1][j-1]);
}
}
memset(dp,0,sizeof(dp));
FOR(j,1,n){
if(f[0][j]) {dp[j] = j+1;continue;}
dp[j] = dp[j-1];
FOR(i,1,j) if(f[i][j]) dp[j] = max(dp[j],dp[i-1]+j-i+1);
}
printf("%d\n",dp[n-1]);
}
int main(){
//freopen("test.in","r",stdin);
int T; scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
FOR(i,0,n) scanf("%d",&a[i]);
hs.clear(); int u;
FOR(i,0,m) scanf("%d",&u),hs[u] = 1;
work();
}
return 0;
}