1088: 回文串询问Ⅱ
记忆DP
注意对于judge()函数我可以去掉,使用另一个dp来对所有可能l,r判断是否为回文串
#include<bits/stdc++.h>
using namespace std;
int n,q;
const int N=1010;
int dp[N][N];
char s[N];
bool judge(int l,int r){
while(l<r){
if(s[l]==s[r]){
l++;r--;
}
else return 0;
}
return 1;
}
int fun(int l,int r){
if(l>r){
return 0;
}
if(l==r){
dp[l][r]=1;
return 1;
}
else if(dp[l][r]!=0){
return dp[l][r];
}else{
dp[l][r]=fun(l,r-1)+fun(l+1,r)-fun(l+1,r-1)+judge(l,r);
return dp[l][r];
}
}
int main(){
while(scanf("%d%d",&n,&q)!=EOF){
memset(dp,0,sizeof(dp));
scanf("%s",s+1);
int len=strlen(s+1);
for(int i=1;i<=q;i++){
int l,r;
scanf("%d%d",&l,&r);
printf("%d\n",fun(l,r));
}
}
}

浙公网安备 33010602011771号