Codeforces 835 D Palindromic characteristics(区间DP)

来源:互联网 发布:thinkphp5开发大型cms 编辑:程序博客网 时间:2024/05/01 14:54

题目地址
题意:给你一个字符串,在其中找到1~k阶回文子串的个数,如果一个字符串是回文的,则他一定是1阶回文子串(k阶回文子串要求它的的左边和右边都是k-1阶回文子串)
思路:dp[i][j]记录下标为i~j的子串是几阶回文子串,然后去求就好了(看代码注释)

#include <iostream>#include <cstring>#include <string>#include <queue>#include <vector>#include <map>#include <set>#include <stack>#include <cmath>#include <cstdio>#include <algorithm>#define N 5010#define M 200010#define K 1000010#define LL __int64#define inf 0x3f3f3f3f#define lson l,mid,ans<<1#define rson mid+1,r,ans<<1|1using namespace std;const LL mod = 998244353;const double eps = 1e-9;int dp[N][N];int ans[N];int main() {    cin.sync_with_stdio(false);    string str;    while (cin >> str) {        memset(ans, 0, sizeof(ans));        memset(dp, 0, sizeof(dp));        for (int i = 0; i < str.length(); i++) {            dp[i][i] = 1;            ans[1]++;            if (i != str.length() - 1 && str[i] == str[i + 1]) {//判断是不是连续两个相同字母,因为这个是2阶子串                dp[i][i + 1] = 2;                ans[1]++;                ans[2]++;            }        }        for (int i = 3; i <= str.length(); i++) {//枚举子串长度            for (int j = 0; j + i - 1 < str.length(); j++) {//枚举子串起始位置                if (dp[j + 1][j + i - 2] && str[j] == str[j + i - 1]) {//如果j+1~j+i-2的子串是n阶子串的话,就可以向外扩张                    dp[j][j + i - 1] = dp[j][j + i / 2 - 1] + 1;//就是右半边子串原有阶数+1                    for (int k = 1; k <= dp[j][j + i - 1]; k++) {                        ans[k]++;//只要是n阶回文子串就是1~n-1阶子串                    }                }            }        }        for (int i = 1; i <= str.length(); i++) {            cout << ans[i] << " ";        }        cout << endl;    }    return 0;}
阅读全文
0 0
原创粉丝点击