CodeForces 245H Queries for Number of Palindromes

题目链接

给出一个长度为n的字符串与q次询问,每次询问[l,r]的回文串个数

定义f[i][j]为[i,j]是否为回文串,g[i][j]为[i,j]回文串个数

\(len = 1: f[i][j] = true\)
\(\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ g[i][j] = 1\)
\(len = 2: f[i][j] = s[i]==s[j]\)
\(\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ g[i][j] = g[i+1][j]+g[i][j-1]+f[i][j]\)
\(len > 2: f[i][j] = f[i+1][j-1]\&\&s[i]==s[j]\)
\(\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ g[i][j]=g[i+1][j]+g[i][j-1]-g[i+1][j-1]+f[i][j]\)

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int q;
char s[5050];
bool f[5000][5000];
int g[5000][5000];
int main() {
	scanf("%s", s);
	int n = strlen(s);
	for(int i = 0; i < n; i++) {
		for(int j = i; j >= 0; j--) {
			if(i - j == 0) f[j][i] = 1;
			else if(i - j == 1 && s[i] == s[j]) f[j][i] = 1;
			else if(f[j + 1][i - 1] && s[i] == s[j]) f[j][i] = 1;
		}
	}
	for(int i = 0; i < n; i++) {
		for(int j = i; j >= 0; j--) {
			if(i - j == 0) g[j][i] = 1;
			else {
				g[j][i] = g[j + 1][i] + g[j][i - 1];
				if(i - j != 1) g[j][i] -= g[j + 1][i - 1];
				if(f[j][i]) g[j][i]++;
			}
		}
	}
	scanf("%d", &q);
	for(int i = 1; i <= q; i++) {
		int l, r;
		scanf("%d%d", &l, &r);
		printf("%d\n",g[l - 1][r - 1]);
	}
	return 0;
}

posted @ 2018-05-20 19:50  LJZ_C  阅读(167)  评论(0编辑  收藏  举报