Arrange a binary string to get maximum value within a range of indices C/C++?


In case of a given string consisting of only 0’s and 1’s, we are given M non-intersecting ranges A, B( A <= B), more specifically [A1, B1], [A2, B2], …, [AM, BM], Any two of these intervals does not overlap — formally, in case of each valid i, j such that i!=j, either Ai<Bj or Bj<Ai.

The activity is to find a legal or valid permutation which will hold the following two conditions simultaneously −

  • Sum of numbers between all M given ranges will be largest.

  • The string will be lexicographically maximum. A string 1100 is lexicographically higher than string 1001.

Examples

Input
11100
3
3 4
5 5
Output
00111
First we put 1’s in position 3 and 4 then in 5 as there are no 1’s left, the string formed is 00111.
Input
0000111
2
1 1
1 2
Output
1110000

In the above example we 1st put 1 in 1st and 2nd position then we have another ‘1’ left,

So, we use it to maximize the string lexicographically and we put it in the 3rd position and thus the rearrangement is complete.

Updated on: 29-Jan-2020

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements