求解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;
}

京公网安备 11010502036488号