跳到正文

题解

CF1927B Following the String solution

littlebug约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
CF1927B

版本

  1. v1当前

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

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

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

时间复杂度 O(n)O(n)。

code:

C++
#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;
}
原文