PAT L1 050 倒数第N个字符串 (递归/模拟)

给定一个完全由小写英文字母组成的字符串等差递增序列,该序列中的每个字符串的长度固定为 L,从 L 个 a 开始,以 1 为步长递增。例如当 L 为 3 时,序列为 { aaa, aab, aac, ..., aaz, aba, abb, ..., abz, ..., zzz }。这个序列的倒数第27个字符串就是 zyz。对于任意给定的 L,本题要求你给出对应序列倒数第 N 个字符串。

输入格式:

输入在一行中给出两个正整数 L(2 <= L <= 6)和 N(<= 105)。

输出格式:

在一行中输出对应序列倒数第 N 个字符串。题目保证这个字符串是存在的。

输入样例:
3 7417
输出样例:
pat

考试的时候一发过,现在写的时候就有点懵比了….

理论上不需要模拟 但是还是采用的模拟过的

初始设置为z 然后向前走n次模拟出结果

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<stack>
#include<set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int MAX_N=100000;
const int INF = 0x3f3f3f3f;
string s;
int l,n;
int change(int i){
    //cout<<i<<" "<<s[i]<<endl;
    if(s[i]=='a'){
        change(i-1);
    }
    else if(i==0&&s[i]=='a'){
        return -1;
    }
    else
        return i;
}
void next(){
    int j=change(l-1);
    if(j!=-1){
        s[j]=(char)s[j]-1;
        for(int i=j+1;i<l;i++){
            s[i]='z';
        }
    }

}
int main(){
    ios::sync_with_stdio(false);
    cin>>l>>n;
    int len=l;
    while(len--){
        s=s+'z';
    }
    n--;
    while(n--){
        //cout<<s<<endl;
        next();
    }
    cout<<s<<endl;
    return 0;
}

递归是真的真的简单….哇 考试的时候没想到
类似于转进制
从最后开始依次赋值
然后正向输出即可

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<stack>
#include<set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int MAX_N=100000;
const int INF = 0x3f3f3f3f;

int main(){
    ios::sync_with_stdio(false);
    int l,n;
    cin>>l>>n;
    int ans=pow(26,l)-n;
    char a[6];
    for(int i=5;i>=0;i--){
        a[i]=(char)(ans%26+'a');
        ans=ans/26;
    }
    for(int i=5-l+1;i<=5;i++)
        cout<<a[i];
    cout<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38842456/article/details/79779314