题解:P17287 [Algo Beat Contest 013 & MSOI R2] 付之一笑

· · 题解

前言:

刚刚打完比赛就来写题解啦~

思路:

纯模拟,只需将每个字符串进行遍历即可,

当 p=1 时,字符直接输出;将数字转化为字符,需要累加。

当 p=2 时,数字直接输出;将字符转化为数字,每个字符对应唯一数字。

注意不要写反了!

AC代码:

#include<bits/stdc++.h>
using namespace std;
string s;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int q;
    cin>>q;
    for(int i=1;i<=q;i++)
    {
        int p;
        cin>>p>>s;
        int l=s.length();
        if(p==1)
        {
            int j=0;
            while(j<l)
            {
                if(s[j]>='0'&&s[j]<='9')
                {
                    int k=(int)(s[j]-'0');
                    j++;
                    while(s[j]>='0'&&s[j]<='9')
                    {
                        k=k*10+(int)(s[j]-'0'); // 注意要乘 10 ,达到累加效果
                        j++; // 直接加 j 效率更高 
                    }
                    cout<<(char)(k+'a'-1); //减 1 不要漏写 
                }
                else
                {
                    cout<<s[j];
                    j++;
                }
            }
        }
        else
        {
            for(int j=0;j<l;j++)
            {
                if(s[j]>='0'&&s[j]<='9') cout<<s[j];
                else cout<<(int)(s[j]-'a'+1);
            }
        } // 数字串较为简单,不进行解释 
        cout<<endl; // 换行也不要忘了写 
    }
    return 0;
}

这样就可以做到 O(\lvert s \rvert) 的时间复杂度,不会超时。

恭喜你又看完了一篇题解!