1 solutions

  • -2
    @ 2025-7-19 22:35:07

    我们直接从起点出发dfsdfs就可以得到结果了,而且不需要回溯。

    一个trick是,这个树如果很深的话,你无脑dfsdfs就会TLE,所以对于nextnext不是00的位置,O(1)O(1)决策过去就行。

    #include <bits/stdc++.h>
    #define ll long long
    #define maxn 200005
    #define mod 998244353
    using namespace std;
    int n;
    int nxt[maxn];
    char s[maxn];
    void dfs(int i)
    {
    	if (i == n + 1)
    	{
    		printf("%s\n", s + 1);
    		exit(0);
    	}
    	if (nxt[i])
    	{
    		s[i] = s[nxt[i]];
    		dfs(i + 1);
    		return;
    	}
    	for (char c = 'a'; c <= 'z'; c++)
    	{
    		int now = nxt[i - 1];
    		while (now != 0 && s[now + 1] != c)
    			now = nxt[now];
    		if (s[now + 1] == c)
    			now++;
    		if (now == nxt[i])
    		{
    			s[i] = c;
    			dfs(i + 1);
    			break;
    		}
    	}
    	return;
    }
    int main()
    {
    	cin >> n;
    	for (int i = 1; i <= n; i++)
    		cin >> nxt[i];
    	s[1] = 'a';
    	dfs(2);
    }
    
    
    • 1

    Information

    ID
    7
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    8
    Tags
    (None)
    # Submissions
    47
    Accepted
    8
    Uploaded By