题目翻译:
给定一个字符串,统计“PAT”出现的次数,注意次序要保持,可以不连续。
范围如下:
解题思路:
首先得到最左侧的P位置begin,最右侧的T位置end。
然后统计这个区间A的位置,从左到右,依次求得P与A以及A与T之间P的数量、T的数量,然后相乘即可。(注意如果直接相乘会超时,需要采取一定策略:使用 pos
来跟踪已经统计过的区域,避免重复统计。)
最后相加得到结果。
本题也可以使用状态DP来解决,参考动态规划状态机
代码:
#include<bits/stdc++.h>
using namespace std;
string a;
int Count(int start, int back,char p)//统计一段字符串中某个字符出现的次数
{
int count = 0;
for (int i = start;i <= back;i++)
{
if (a[i] == p)
count++;
}
return count;
}
int main()
{
int result = 0;
cin >> a;
int begin = 0, end;
int c1 = 0, c2 = 0;
for (int i = 0;i < a.size() - 1;i++)
if (a[i] == 'P')
{
begin = i;break;
}
for (int i = a.size() - 1;i >= 0;i--)
if (a[i] == 'T')
{
end = i;break;
}
int tag = 0, pos;
for (int i = begin + 1;i <= end - 1;i++)
{
if (a[i] == 'A')
{
if (!tag)
{
tag = 1;
c1 = Count(begin, i - 1, 'P');
c2 = Count(i + 1, end, 'T');
}
else
{
c1 += Count(pos+1, i - 1, 'P');
c2 -= Count(pos+1, i - 1, 'T');
}
result = (result + (1ll * c1 * c2) % 1000000007) % 1000000007;
pos = i;
}
}
cout << result;
}
坑点:
对于测试点3和4的超时问题:是因为对某区域重复统计,可以使用 pos
来跟踪已经统计过的区域,避免重复统计。
对于测试点3和4的错误问题:是因为不仅每次相乘的结果要取余,相加的结果也要取余。
//result+=(c1*c2)%1000000007;//这种写法忽略了result可能超过1000000007,因此出错。
result = (result + (c1 * c2) % 1000000007) % 1000000007;//正确写法,是对每次相乘的结果取余,并对相加的结果也取余
二刷:
dp:
#include<bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
const int N = 1e5 + 10;
char s[N];
int f[N][4];
char p[] = " PAT";
int main() {
cin >> s + 1;
int len = strlen(s+1);//计算从s[1]开始的字符串长度
f[0][0] = 1;
for (int i = 1;i <= len;i++) {
for (int j = 0;j < 4;j++) {
f[i][j] = f[i - 1][j];
if (s[i] == p[j]) f[i][j] = (f[i][j] + f[i - 1][j - 1]) % MOD;
}
}
cout << f[len][3];
}