#K58137. Minimum Hamming Distance for Alternating Binary String

    ID: 30576 Type: Default 1000ms 256MiB

Minimum Hamming Distance for Alternating Binary String

Minimum Hamming Distance for Alternating Binary String

You are given a binary string b consisting of characters '0' and '1'. Your task is to determine the minimum number of character changes needed to convert b into a string c that is an alternating binary string. In other words, c should be of the form 0101… or 1010….

Let the Hamming distance between two strings of equal length be defined as the number of positions at which the corresponding symbols differ. You need to compute this Hamming distance for both of the possible alternating patterns and return the minimum of the two distances.

The problem can be formally described using the following mathematical formulation:

For a binary string b of length n, define two possible alternating patterns: \[ P_1 = \begin{cases} '0' & \text{if } i \text{ mod } 2 = 0, \\ '1' & \text{if } i \text{ mod } 2 = 1 \end{cases} \quad\text{and}\quad P_2 = \begin{cases} '1' & \text{if } i \text{ mod } 2 = 0, \\ '0' & \text{if } i \text{ mod } 2 = 1 \end{cases} \]

The answer is:

[ \min\Big{ \sum_{i=0}^{n-1} \mathbf{1}{{b[i] \neq P_1[i]}}, \sum{i=0}^{n-1} \mathbf{1}_{{b[i] \neq P_2[i]}} \Big} ]

Implement a solution that reads the input from stdin and writes the result to stdout.

inputFormat

The input consists of a single binary string b on one line. The string is non-empty and contains only the characters '0' and '1'.

For example:

0110

outputFormat

Output a single integer denoting the minimum number of changes needed to convert the given binary string into an alternating binary string. Print the result to stdout.

For example, for the input above, the output should be:

2
## sample
0110
2