CF1927B Following the String solution

· · 题解

形式化题意:给定一个长度为 n 的序列 \{a\},a_i 表示一个字符( a-z )在区间 [s_1,s_{i-1}] 的出现次数。求一种合法的字符串 s 使得其满足上述条件,s 只由 a-z 组成。

由题意可知,s_i 只与 s_1,\dots s_{i-1} 相关,所以在求 s_i 的时候只需要知道 s_1,\dots s_{i-1} 中 a-z 出现的次数就可以了。可以用一个数组 cnt 统计 a-z 的出现次数,然后每次求 s_i 的时候遍历一遍 cnt ,如果发现有一个 cnt[j]==a[i] 的字母,就把 cnt[j]++ ,然后输出并跳出循环。

因为题目中说了数据保证有解,所以不需要考虑无解的情况。

时间复杂度 O(n)。

code:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN=2e5+5;
int T;
int n;
int a[MAXN];
int cnt[200];
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>T;
    while(T--)
    {
        memset(cnt,0,sizeof(cnt));
        cin>>n;
        for(int i=1;i<=n;++i)
        {
            cin>>a[i];
            for(int j='a';j<='z';++j)
            {
                if(cnt[j]==a[i])
                {
                    ++cnt[j];
                    cout<<(char)(j);
                    break;
                }
            }
        }
        cout<<'\n';
    }
    return 0;
}