To solve this problem, we need to split a string of length ( n ) into ( k ) non-empty substrings such that the sum of the lengths of the two longest substrings is minimized.
Approach
The key insight to minimize the sum of the two longest substrings is to distribute the length of the string as evenly as possible among the ( k ) substrings. Here's the detailed approach:
- Base Length Calculation: Compute the base length of each substring if the string were divided evenly. This is given by ( \text{base} = n // k ).
- Remainder Calculation: Compute the remainder when ( n ) is divided by ( k ), denoted as ( r = n \% k ). This remainder tells us how many substrings will have an extra length of 1 (since we can't split the string into fractions).
- Sum Calculation:
- If ( r = 0 ): All substrings are of length ( \text{base} ), so the sum of the two longest is ( 2 \times \text{base} ).
- If ( r = 1 ): One substring is of length ( \text{base} + 1 ) and the rest are ( \text{base} ), so the sum is ( \text{base} + (\text{base} + 1) = 2 \times \text{base} + \text{1} ).
- If ( r \geq 2 ): At least two substrings are of length ( \text{base} + \text{1} ), so the sum of the two longest is ( (\text{base} + \text{1}) + (\text{base} + \text{1}) = 2 \times (\text{base} + \text{1}) ).
Solution Code
n = int(input()) # Length of the string
k = int(input()) # Number of substrings to split into
base = n // k
remainder = n % k
if remainder == 0:
print(base * 2)
elif remainder == 1:
print(base * 2 + 1)
else:
print((base + 1) * 2)
Explanation
- Even Distribution: When the string length is divisible by ( k ), all substrings are of equal length, so the sum of the two longest is twice the base length.
- One Extra: If there is a remainder of 1, only one substring is longer by 1, so the sum is the base length plus the longer length.
- Multiple Extras: If the remainder is more than 1, at least two substrings are longer by 1, so their sum is twice the longer length.
This approach efficiently computes the minimal sum with constant time complexity ( O(1) ), making it optimal for any valid input values of ( n ) and ( k ).
Note: The input here assumes you provide the length of the string ( n ) and the number of substrings ( k ). If the input is the string itself, you can replace ( n ) with ( len(s) ) where ( s ) is the input string. For example:
s = input().strip()
k = int(input())
n = len(s)
# Rest of the code as above
This solution ensures that we get the minimal possible sum of the two longest substrings by leveraging even distribution of the string length. It's both optimal and easy to understand.

作者声明:本文包含人工智能生成内容。