高效技巧-活用递推
The string APPAPT contains two PAT's as substrings. The first one is formed by the 2nd, the 4th, and the 6th characters, and the second one is formed by the 3rd, the 4th, and the 6th characters.
Now given any string, you are supposed to tell the number of PAT's contained in the string.
Input Specification:
Each input file contains one test case. For each case, there is only one line giving a string of no more than 10
5
characters containing only P, A, or T.
Output Specification:
For each test case, print in one line the number of PAT's contained in the string. Since the result may be a huge number, you only have to output the result moded by 1000000007.
Sample Input:
APPAPT
Sample Output:
2
思路:
直接暴力会超时。
另一个角度。对于一个确定位置的A来说,以它形成的PAT的个数等于它左边P的个数乘以它右边T的个数。例如字符串APPAPT的中间的A来说,它左边有两个P,右边有一个T,所以这个A能形成2个PAT。因此本问题就可以看作,对字符串中的每个A,计算它左边的P和它右边的A的个数的乘积,然后把所有A的这个乘积相加。
那如何更快获得每一个A左边P的个数呢?
只需要设定一个数组leftNumP,记录每一个左边P的个数(包括当前位)。接着从左到右遍历字符串,如果当前一位i是P,那么leftNumP[i]就等于leftNumP[i-1]+1;如果当前位i不是P,那leftNumP[i]就等于leftNumP[i-1]。以同样的方法计算出每一个A右边T的个数。
另外,在统计每一个A右边T的个数时直接计算答案ans。具体方法:定义一个变量rightNumT,记录当前累计右边T的个数。从右往左遍历,如果当前位i是T,那么令rightNumT加1;否则,如果当前位i为A,那么令ans加上leftNumP[i]与rightNumT[i]的乘积(注意取模)。
注意:
1.采用分别遍历P、A、T的方法会超时。
2.记得取模。
代码:
#include <cstdio> #include <cstring> #include <iostream> using namespace std; const int MAXN = 100010; const int MOD = 1000000007; char str[MAXN]; int leftNumP[MAXN] = {0}; int main(){ cin.getline(str,MAXN); int len = strlen(str); for(int i=0;i<len;i++){ if(i > 0) leftNumP[i] = leftNumP[i-1]; if(str[i] == 'P') leftNumP[i]++; } int ans = 0,rightNumT = 0; for(int i=len-1;i>=0;i--){ if(str[i] == 'T') rightNumT++; else if(str[i] == 'A') ans = (ans + leftNumP[i]*rightNumT) % MOD; } printf("%d\n",ans); return 0; }
__EOF__

本文链接:https://www.cnblogs.com/techgy/p/15049357.html
关于博主:I am a good person
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~