[Solution] Flipping Failure CodeChef Solution
Problem
Chef has a binary string with him and he wants to modify it using the following two types of operations -
- Type 1 : Choose any two indices and such that and swap and . This operation costs rupee and can be performed any number of times.
- Type 2 : Choose any prefix of length , where , and reverse this prefix of the binary string. This operation is free of cost and can be performed at most once.
Chef wants to obtain the lexicographically smallest string. Can you help him find the minimum cost to obtain the lexicographically smallest string?
Note:
- denotes the length of the string .
- A string is lexicographically smaller than string , if , where is the first index where and differ.
Input Format
- The first line of input will contain a single integer , denoting the number of test cases.
- Each test case consists of a single line of input denoting , the original string.
Output Format
For each test case, output the minimum cost to obtain the lexicographically minimal string.
Explanation:
Test case 1: You can perform an operation of Type 1 by choosing and . So from , you get , and it has cost you rupee so far. Then, you perform an operation of Type 2, by choosing . So you reverse the entire string, and so from , you get . This operation is free of cost. This is the lexicographically smallest string that you can achieve, and it cost us rupee to get there. So the answer is .
Test case 2: You can perform an operation of Type 2, by choosing . So you reverse the prefix of length 2, and so from , you get . This operation is free of cost. This is the lexicographically smallest string that you can achieve, and it cost us rupees to get there. So the answer is .
Test case 3: You can perform an operation of Type 1 by choosing and . So from , you get , and it has cost you rupee so far. Then, you perform an operation of Type 2, by choosing . So you reverse the prefix of length 5, and so from , you get . This operation is free of cost. This is the lexicographically smallest string that you can achieve, and it cost us rupee to get there. So the answer is .
No comments:
Post a Comment