CodeForces245H - Queries for Number of Palindromes(区间dp)

dp(i)(j)表示在区间(i,j)里有多少个回文串,
dp(i)(j) = dp(i+1)(j) + dp(i)(j-1) - dp(i+1)(j-1) + flag(i,j).
若str(i)到str(j)是回文串,则flag(i,j)为1

#include <bits/stdc++.h>
#define maxn 5005
#define INF 1e9
using namespace std;
typedef long long ll;

char str[maxn];
int dp[maxn][maxn];
int flag[maxn][maxn], len;
void solve(int i, int j){

    while(i >= 0 && j < len){

        if(str[i] == str[j])
           flag[i][j] = 1;
        else
         break;  
        i--;
        j++;    
    }
}
int main(){

// freopen("in.txt", "r", stdin);
    while(scanf("%s", str) == 1){

        memset(flag, 0, sizeof(flag));
        len = strlen(str);
        for(int i = 0; i < len; i++){
            solve(i, i);
            solve(i, i+1);
        }
        for(int i = 0; i < len; i++)
          dp[i][i] = 1;
        for(int i = 1; i < len; i++)
          for(int j = 0; i + j < len; j++){
            int k1 = j, k2 = i + j;
            dp[k1][k2] = dp[k1][k2-1] + dp[k1+1][k2] - dp[k1+1][k2-1] + flag[k1][k2];
          }
        int t;

        cin >> t;
        for(int i = 0; i < t; i++){

            int a, b;
            scanf("%d%d", &a, &b);
            printf("%d\n", dp[a-1][b-1]);
        } 
    }
    return 0;
}

你可能感兴趣的:(CodeForces245H - Queries for Number of Palindromes(区间dp))