PAT 乙级 1040 有几个PAT

输入样例:
APPAPT
输出样例:
2

完成题目有两个要点(第一眼我还以为是DP)

  • 如何判断一个“PAT”
  • 如何提高效率

对于如何判断一个“PAT”,只要 A 的左至少有一个 P 且 右边至少有一个 T 就可以组成一个“PAT”,至于能组成多少个"PAT",是左边的 P 的数量 × 右边的 T 的数量

对于提高效率,注意到题目给的数据量可能会很大(长度不超过10^5),用简单的暴力算法肯定是会超时的,思路是用一张表记录当前位置的左边各有多少个 P 和 T(当前位置若含有 P T仍会计入) ,后序判断的时候直接查表即可。这样时间复杂度就是线性的了。

#include <iostream>
#include <string>
#include <map>
#include <algorithm>

using namespace std;

struct Count_P_T
{
    unsigned long long P,T;
    Count_P_T()
    {
        P=T=0;
    }
};

unsigned long long count(const string& s);

int main()
{
    string s;
    cin>>s;
    cout<<count(s);
    return 0;
}

unsigned long long count(const string& s)
{
    unsigned long long count=0,count_P=0,count_T=0,x=0;
    Count_P_T* p=new Count_P_T[s.length()];
    for(string::const_iterator itor=s.begin() ;itor!=s.end() ;itor++)
    {
        if(*itor=='P')
            count_P++;
        if(*itor=='T')
            count_T++;
        p[x].P=count_P;
        p[x++].T=count_T;
    }
    for(int i=0;i<s.length() ;i++)
    {
        if(s[i]=='A')
        {
            count+=p[i].P*(p[s.length()-1].T-p[i].T);
        }
    }
    delete p;
    return count%1000000007;
}

猜你喜欢

转载自www.cnblogs.com/FDProcess/p/9236228.html