#C14051. Minimum Adjacent Swaps to Group Target Characters
Minimum Adjacent Swaps to Group Target Characters
Minimum Adjacent Swaps to Group Target Characters
Given a list of strings and a target string, your task is to determine the minimum number of adjacent swaps required to group all occurrences of the target string consecutively within the list. If the target string is not present in the list, then the answer is -1.
Let the positions (0-indexed) of the target in the list be \(p_1, p_2, \dots, p_k\) in sorted order. The optimal solution is achieved by aligning these indices around the median position \(p_m\) (with \(m = \lfloor k/2 \rfloor\)). The total number of swaps required is given by: \[ \text{swaps} = \sum_{i=1}^{k} \left| (p_m - (m - (i-1))) - p_i \right| \] If there is no occurrence of the target string, print -1.
inputFormat
The input is read from standard input (stdin) and has the following format:
- An integer
n
representing the number of elements in the list. - A line containing
n
space separated strings. Ifn
is 0, this line may be empty. - A string representing the target string.
outputFormat
Output a single integer denoting the minimum number of adjacent swaps required to group all occurrences of the target consecutively. If the target is not found in the list, output -1
.
3
a b c
d
-1