活用递推
来源:互联网 发布:如何使用r软件 编辑:程序博客网 时间:2024/06/06 00:23
求解PAT中
APPAPT中有多少个“PAT”的方法,此处答案为2。
1.如果用暴力求解的话,会超时;
2.换一种想法,就会很轻松,有多少个“PAT”,
我们可以遍历string s,如果遇到‘A’,就数
它左边有多少个’P’ pcount,右边有多少个’T’ tcount,
将sum=pcount*tcount,就是这个‘A’总共的结果,
遍历的过程中实现累加。
编程如下:
#include <iostream>#include <cstdio>#include <cstdlib>#include <string>#include <cstring>#include <sstream>#include <cmath>#include <vector>#include <algorithm>using namespace std;int main(){ string s; cin>>s; string::iterator it=s.begin(); int sum=0; while(it!=s.end()) { int pcount=0,tcount=0; if(*it=='A') { pcount=(int)count(s.begin(),it,'P'); tcount=(int)count(it,s.end(),'T'); sum+=pcount*tcount; } it++; } cout<<sum<<endl; return 0;}
以上做法会超时,因为循环过程中多次用count,以下做法完全正确,也比较方便,思想也是基于上面的。
#include <cstdio>#include <iostream>#include <cmath>#include <string> #include <cstring>#include <algorithm>using namespace std;string s;int main(){ cin>>s; int tcount=(int)count(s.begin(),s.end(),'T'); long long ans=0LL; int pcount=0; for(auto x:s) { if(x=='P') { pcount++; } else if(x=='A') { ans+=pcount*tcount; } else if(x=='T') { tcount--; } } cout<<ans%1000000007; return 0;}
阅读全文
0 0
- 活用递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 递推
- 数据结构实验之二叉树一:树的同构
- Express 4.x中间件morgan(logger)的详细解析
- 【数据库】oracle客户端PL/SQL
- tensorflow根据人脸分辨性别
- nginx-tomcat-redis共享session
- 活用递推
- 大学英语单词U
- 微信公众平台的Java开发详解(工程代码+解析)
- vi 的基本使用
- 流水线调度问题——动态规划
- hibernate映射笔记
- 5.2.从键盘任意输出一个整数,编程判断它的奇偶性。
- Linux下的ssh免密登录原理
- 网站卡顿,JS代码该优化了