Определен набор символов, из которых должен состоять пароль, причём каждый символ из набора должен встречаться хотя бы один раз. Также длина пароля не превосходит k символов.
В распоряжении есть последовательность символов, в которой может оказаться пароль.
Формат входных данных:
В первой строке ввода дана последовательность длины n (1 ≤ n ≤ 2 × 10^5) из строчных латинских букв - последовательность символов.
Во второй строке дан набор символов - требования к паролю, а в третьей - число k (1 ≤ k ≤2 × 10^5), максимальная длина пароля.
Формат выходных данных:
Выведите возможный пароль, удовлетворяющий указанным условиям. Если вариантов пароля несколько, выберите тот, который начинается в последовательности из первой строки правее (позже) других, а среди всех с одинаковым с ним началом - самый длинный.
Если восстановить пароль не удастся, выведите «-1» (без кавычек).
Assistant
To solve this problem efficiently, we'll utilize a method that leverages precomputing the next occurrence of each character and an efficient scanning technique. Here's a breakdown of the approach:
Algorithm Overview:
Precompute Next Occurrences:
For each position i in the string S, precompute the next occurrence of each character c from 'a' to 'z'.
This creates a next array where next[i][c] tells us the earliest position at or after i where character c occurs.
Process Positions from Right to Left:
Starting from the end of the string (position n), we iterate backwards to the start.
At each position i, we attempt to find if a valid password (substring) can start at i.
Determine the Substring Bounds:
For the set of required characters C, we find the maximum of next[i][c] for all c in C. Let's call this t.
If any next[i][c] exceeds n, it means that not all required characters are present from position i onwards, so we skip this i.
If t - i + 1 exceeds the maximum allowed length k, we cannot form a valid password starting at i, so we skip to the next i.
Else, we form a candidate substring from i to t', where t' is the farthest possible end within the allowed length: t' = min(i + k - 1, n).
Select the Desired Substring:
By iterating from right to left and following the above steps, the first valid substring we find will start at the largest possible i (as we desire the substring that starts as far right as possible).
Among substrings starting at the same position, we select the longest one, satisfying the requirement of choosing the longest among those starting at the same index.
Output the Result:
If we find a valid substring, we output it.
If no valid substring is found throughout the iteration, we output -1.
Here's the Python implementation of the above approach:
python
s = input().strip()
C = set(input().strip())
k = int(input())
n = len(s)
s = s # positions are 0-indexed in Python
next_char = [ [n+1]*26 for _ in range(n+2)] # next_char[i][c] is next occurrence of c from position i
# Preprocess next occurrences for each character
for i in range(n - 1, -1, -1):
for c in range(26):
next_char[i][c] = next_char[i + 1][c]
idx = ord(s[i]) - ord('a')
next_char[i][idx] = i
# Process positions from n downto 0
found = False
for i in range(n - 1, -1, -1):
t = -1
ok = True
for ch in C:
c_idx = ord(ch) - ord('a')
if next_char[i][c_idx] > n:
ok = False
break
t = max(t, next_char[i][c_idx])
if not ok:
continue
length = t - i + 1
if length > k:
continue
t_prime = min(i + k - 1, n -1) # Adjusted because Python is 0-based index
# Since we process from right to left, first one found is desired
print(s[i:t_prime + 1])
found = True
break
if not found:
print(-1)
Explanation of the Code:
We initialize the next_char array to hold the next occurrence of each character after a given position.
We fill this array using a reverse iteration to ensure correctness.
The main loop iterates from the end of the string towards the beginning, attempting to find a valid substring starting at each position.
If a valid substring is found (one that includes all required characters and is within the maximum length), it's printed immediately, and the loop exits.
If no valid substring is found after the full iteration, -1 is printed.
This algorithm operates in O(n * 26) time due to the preprocessing of the next_char array (with n being the length of the string and 26 being the number of lowercase letters), which is acceptable given the constraints of the problem.