程序设计天梯赛——L1-050 倒数第N个字符串
题目详情 - L1-050 倒数第N个字符串 (pintia.cn)
给定一个完全由小写英文字母组成的字符串等差递增序列,该序列中的每个字符串的长度固定为 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
问题解析
可以先算一算,对于一个长度为L的字符串,他一共有多少种不同的类型。
我们可以把这个字符串看作是一个26进制的数,如果某一位是‘a',我们就把它看作0,某一位是’b‘,就把它看作1……以此类推,某一位是’z‘我们就把它看作是25。
这样,对于一个长度为L的字符串,最后的一个字符串自然就是:zzz……zz,我们把它转化成10进制数,就可以知道长度为L的字符串到底有几种类型了。不过因为我们这个算法,求得的第一个字符串大小是0,所以我们要在计算的结果上+1才是正确的。
然后减去N,来知道我们要求的是第几个字符串,再把这个数通过进制转化为26进制即可。
如果字符串长度不为L时,数已经为0了,那之后的位置都填上’a‘即可。
AC代码
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<math.h>
#include<set>
#include <random>
#include<numeric>
#include<string>
#include<string.h>
#include<iterator>
#include<fstream>
#include<map>
#include<unordered_map>
#include<stack>
#include<list>
#include<queue>
#include<iomanip>
#include<bitset>
//#pragma GCC optimize(2)
//#pragma GCC optimize(3)
#define endl '\n'
#define int ll
#define PI acos(-1)
#define INF 0x3f3f3f3f
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PII;
const int N = 2e5 + 50, MOD = 998244353;
void solve()
{
int n, num, res = 1;
cin >> n >> num;
for (int i = 1, j = 1; i <= n; i++, j *= 26)
{
res += j * 25;
}
res -= num;
string s;
for (int i = 1; i <= n; i++)
{
s += 'a' + res % 26;
res /= 26;
}
reverse(s.begin(), s.end());
cout << s;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t = 1;
//cin >> t;
while (t--)
{
solve();
}
return 0;
}