fork download
  1. def shortest_string_for_connected_components(S):
  2. N = len(S)
  3.  
  4. # dp[k] will hold the minimum length of a string that results in exactly k connected components
  5. dp = [float('inf')] * (N + 1)
  6. dp[0] = 0 # 0 components require 0 length
  7.  
  8. # To track the positions of each character
  9. from collections import defaultdict
  10.  
  11. # For each starting point
  12. for l in range(N):
  13. seen = set() # To track characters in the current substring
  14. for r in range(l, N):
  15. seen.add(S[r])
  16. # The number of unique characters in the substring S[l:r+1]
  17. unique_count = len(seen)
  18. dp[unique_count] = min(dp[unique_count], r - l + 1)
  19.  
  20. # Prepare the result
  21. result = []
  22. for k in range(1, N + 1):
  23. result.append(dp[k] if dp[k] != float('inf') else 0)
  24.  
  25. return result
  26.  
  27. # Read input
  28. S = input().strip()
  29. result = shortest_string_for_connected_components(S)
  30. print(' '.join(map(str, result)))
Success #stdin #stdout 0.03s 9680KB
stdin
aabcabcaa
stdout
1 2 3 0 0 0 0 0 0