codeforces 245H . Queries for Number of Palindromes 区间dp

题目链接

 

给一个字符串, q个询问, 每次询问求出[l, r]里有多少个回文串。

 

区间dp, dp[l][r]表示[l, r]内有多少个回文串。 dp[l][r] = dp[l+1][r]+dp[l][r-1]-dp[l+1][r-1]+flag[l][r], 如果是回文串flag[l][r]为1。

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int mod = 1e9+7;
const int inf = 1061109567;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
string s;
int dp[5005][5005], flag[5005][5005];
int judge(int l, int r) {
    if(~flag[l][r])
        return flag[l][r];
    if(l == r)
        return flag[l][r] = 1;
    if(l == r-1 &&s[l] == s[r])
        return flag[l][r] = 1;
    int tmpl = l, tmpr = r;
    while(l<r) {
        if(s[l]!=s[r])
            return flag[tmpl][tmpr] = 0;
        return flag[tmpl][tmpr] = judge(l+1, r-1);
    }
}
int dfs(int l, int r) {
    if(~dp[l][r])
        return dp[l][r];
    if(l>r)
        return dp[l][r] = 0;
    if(l == r)
        return dp[l][r] = 1;
    dp[l][r] = dfs(l+1, r)+dfs(l, r-1)-dfs(l+1, r-1)+judge(l, r);
    return dp[l][r];
}
int main()
{
    mem1(dp);
    mem1(flag);
    cin>>s;
    int n, a, b;
    cin>>n;
    dfs(0, s.size()-1);
    for(int i = 0; i<n; i++) {
        scanf("%d%d", &a, &b);
        printf("%d\n", dp[a-1][b-1]);
    }
    return 0;
}

 

posted on 2016-03-11 09:25  yohaha  阅读(183)  评论(0编辑  收藏  举报

导航