活用递推

来源:互联网 发布:如何使用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;}
原创粉丝点击