CF245H

Queries for Number of Palindromes

题面翻译

题目描述

给你一个字符串s由小写字母组成,有q组询问,每组询问给你两个数,l和r,问在字符串区间l到r的字串中,包含多少回文串。

输入格式

第1行,给出s,s的长度小于5000
第2行给出q(1<=q<=10^6)
第2至2+q行 给出每组询问的l和r

输出格式

输出每组询问所问的数量。

输入格式

The first line contains string $ s $ $ (1<=|s|<=5000) $ . The second line contains a single integer $ q $ $ (1<=q<=10^{6}) $ — the number of queries. Next $ q $ lines contain the queries. The $ i $ -th of these lines contains two space-separated integers $ l_{i},r_{i} $ $ (1<=l_{i}<=r_{i}<=|s|) $ — the description of the $ i $ -th query.

It is guaranteed that the given string consists only of lowercase English letters.

输出格式

Print $ q $ integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.

样例 #1

样例输入 #1

caaaba
5
1 1
1 4
2 3
4 6
4 5

样例输出 #1

1
7
3
4
2

提示

Consider the fourth query in the first test case. String $ s[4...\ 6] $ = «aba». Its palindrome substrings are: «a», «b», «a», «aba».

区间DP好题
首先如何统计f[l][r]
容斥:f[l][r]=f[l+1][r]+f[l][r-1]-f[l+1][r-1]+if(回文)
pd[l][r]:l~r是否为回文
预处理与区间DP类似
因为若l+1~r-1是回文且s[l]==s[r]那么pd[l][r]=1;
还有个点

不要用string!!!

超级超级慢!!!
用char数组快得多!
点击查看代码
#include<bits/stdc++.h>
using namespace std;
char s[5005];
int n,q,l,r,f[5005][5005];
int pd[5005][5005];
inline int read() {
    int x=0,f=0;
    char ch=getchar();
    while(!isdigit(ch))f|=(ch=='-'),ch=getchar();
    while(isdigit(ch))x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
    return f?-x:x;
}
int main()
{
	ios::sync_with_stdio(false);
	scanf("%s",s+1);
	n=strlen(s+1);
//	memset(pd,0,sizeof(pd));
	for(int l=1;l<=n;l++)
		for(int i=1;i+l-1<=n;i++)
		{
			int j=i+l-1;
			if(s[i]!=s[j])continue;
			if(i>=j-1||pd[i+1][j-1])pd[i][j]=1;
		}
	for(int i=1;i<=n;i++)
	{
		f[i][i]=1;
		if(s[i]==s[i+1])f[i][i+1]=3;
		else f[i][i+1]=2;
	}
	for(int l=3;l<=n;l++)
		for(int i=1;i+l-1<=n;i++)
			{
				int j=i+l-1;
				f[i][j]=f[i+1][j]+f[i][j-1]-f[i+1][j-1]+pd[i][j];
			}
	
	int Q=read();
    while(Q--){
        int l=read(),r=read();
        printf("%d\n",f[l][r]);
    }
	return 0;
} 
posted @ 2023-01-17 23:36  PKU_IMCOMING  阅读(15)  评论(0)    收藏  举报