CF1287A Angry Students

· · 题解

思路

只是一道简单题,纯模拟,不过我的思路和各位大佬略有不同。我使用了 ans 来记录当前的时间。不断遍历这个字符串,如果发生了变化,就把 pd 标为真,同时把 ans 加一。退出循环后,直接输出 ans。此外,要注意两点,一是要从后往前遍历,二是要遍历到字符串倒数第二位否则会越界。 这道题我们可以用 do-while 来简化代码。具体用法如下:

do
{

    //需要执行的语句

}while(boolean_expression);

相比 while 循环它会先执行循环体在判断条件。

代码

#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include<bits/stdc++.h>
#define re register
#define un unsigned
#define ll long long
using namespace std;
template<class T> inline void rd(T &x){
    int fl=1;x=0;char c=getchar();
    for(;!isdigit(c);c=getchar()) if(c=='-') fl=-fl;
    for(;isdigit(c);c=getchar()) x=(x<<3)+(x<<1)+c-'0';
    x*=fl;
}
template<class T> inline void wr(T x){
    if(x<0) x=-x,putchar('-');
    if(x<10){putchar(x+'0');return ;}
    int tmp[40]={0},cnt=0;
    while(x) tmp[cnt++]=x%10,x/=10;
    for(re int i=cnt-1;i>=0;--i) putchar(tmp[i]+'0');
}//以上为快读及头文件。
int main()
{
    string s;
    int ans=0,n,k;
    rd(n);
    for(re un int i=0;i<n;i++)
    {
        ans=0;
        rd(k);
        cin>>s;
        bool pd=0;
        do
        {
            pd=0;
            for(int j=k-1;j>0;j--)
            {
                if(s[j]=='P'&&s[j-1]=='A')
                {
                    s[j]='A';
                    pd=1; 
                }
            }//倒序遍历字符串,如果有变化pd变为真。
            if(pd==1)ans++;
        }while(pd==1);
        wr(ans);
        puts("");
    }
    return 0;
}