[CF245H] Queries for Number of Palindromes (容斥原理dp计数)

题目链接:http://codeforces.com/problemset/problem/245/H

题目大意:给你一个字符串s,对于每次查询,输入为一个数对(i,j),输出s[i..j]之间回文串的个数。

容斥原理: dp[i][j] = dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];

if( str[i]==str[j] 并且 str[i+1..j-1]是回文串 ) dp[i][j]++;

代码:

 #include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <bitset>
#include <cmath>
#include <numeric>
#include <iterator>
#include <iostream>
#include <cstdlib>
#include <functional>
#include <queue>
#include <stack>
#include <string>
using namespace std;
#define PB push_back
#define MP make_pair
#define SZ size()
#define ST begin()
#define ED end()
#define CLR clear()
#define ZERO(x) memset((x),0,sizeof(x))
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
const double EPS = 1e-; const int MAX_N = ;
char str[MAX_N];
int dp[MAX_N][MAX_N];
int q; bool IsPalindromes(int i,int j){
if(i>=j) return true;
return dp[i][j] == dp[i+][j]+dp[i][j-]-dp[i+][j-]+;
} int main() {
scanf("%s",str+);
int length = strlen(str+);
// printf("length: %d\n",length);
for(int i=;i<=length;i++) dp[i][i] = ; for(int len = ; len<=length; len++) {
for(int i=;i<=length;i++) {
int j = i+len-;
if( j>length ) continue;
dp[i][j] = dp[i][j-]+dp[i+][j]-dp[i+][j-];
if( str[i]==str[j] ) {
if( IsPalindromes(i+,j-) ) {
dp[i][j] ++ ;
}
}
}
} // for(int i=1;i<=length;i++) {
// for(int j=1;j<=length;j++) {
// printf("%d ",dp[i][j]);
// }
// puts("");
// } scanf("%d",&q); while( q-- ) {
int l,r;
scanf("%d%d",&l,&r);
printf("%d\n",dp[l][r]);
} return ;
}
上一篇:selenium通过WebDriverWait实现ajax测试,实现等页面元素加载完成


下一篇:Linux:读取文件,每行拆分,并比较拆分数组长度