0% found this document useful (0 votes)
2 views2 pages

code7

Uploaded by

harshsinghal0906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

code7

Uploaded by

harshsinghal0906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

def solve():

import sys
input = sys.stdin.read
data = input().splitlines()

# Read inputs
n = int(data[0]) # Number of substrings
substrings = [data[i + 1] for i in range(n)]
main_string = data[n + 1]
k = int(data[n + 2])

# Preprocessing substrings
unique_chars = set(main_string)
valid_substrings = []
for sub in substrings:
filtered = "".join(c for c in sub if c in unique_chars)
if filtered:
valid_substrings.append(filtered)

# Check for "Impossible"


main_set = set(main_string)
available_chars = set("".join(valid_substrings))
if not main_set.issubset(available_chars):
print("Impossible")
return

# Helper function to calculate deletions


def calculate_deletions(segment, substring):
deletions = 0
j = 0
for char in substring:
if j < len(segment) and char == segment[j]:
j += 1
else:
deletions += 1
if j == len(segment): # Check if segment is fully matched
return deletions
return float('inf') # Impossible to match this segment

# Dynamic programming to calculate deletions


dp = [float('inf')] * (len(main_string) + 1)
dp[0] = 0 # Base case: 0 deletions to form an empty prefix

for i in range(len(main_string)):
for sub in valid_substrings:
m = len(sub)
if i + 1 >= m: # Ensure substring can fit
segment = main_string[i - m + 1:i + 1]
deletions = calculate_deletions(segment, sub)
if deletions != float('inf'): # Valid match
dp[i + 1] = min(dp[i + 1], dp[i - m + 1] + deletions)

# Determine the output


if dp[len(main_string)] <= k:
print("Possible")
else:
# Find the longest prefix that can be formed within K deletions
for i in range(len(main_string), -1, -1):
if dp[i] <= k:
print(main_string[:i])
return
print("Nothing")

You might also like