What's Next?


Problem Statement :


Johnny is playing with a large binary number, . The number is so large that it needs to be compressed into an array of integers, , where the values in even indices () represent some number of consecutive  bits and the values in odd indices () represent some number of consecutive  bits in alternating substrings of .

For example, suppose we have array .  represents ,  represents ,  represents ,  represents , and  represents . The number of consecutive binary characters in the  substring of  corresponds to integer , as shown in this diagram:

When we assemble the sequential alternating sequences of 's and 's, we get .

We define setCount() to be the number of 's in a binary number, . Johnny wants to find a binary number, , that is the smallest binary number  where setCount() = setCount(). He then wants to compress  into an array of integers,  (in the same way that integer array  contains the compressed form of binary string ).

Johnny isn't sure how to solve the problem. Given array , find integer array  and print its length on a new line. Then print the elements of array  as a single line of space-separated integers.

Input Format

The first line contains a single positive integer, , denoting the number of test cases. Each of the  subsequent lines describes a test case over  lines:

The first line contains a single positive integer, , denoting the length of array .
The second line contains  positive space-separated integers describing the respective elements in integer array  (i.e., ).


Output Format

For each test case, print the following  lines:

Print the length of integer array  (the array representing the compressed form of binary integer ) on a new line.
Print each element of  as a single line of space-separated integers.
It is guaranteed that a solution exists.



Solution :



title-img


                            Solution in C :

In  C :






#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() 
{

    int t;
    scanf("%d", &t);
    
    for(int num_test_cases = 0; num_test_cases < t; num_test_cases++)
    {
        int n;
        scanf("%d", &n);
        unsigned long long a[n];
        for(int i = 0; i < n; i++)
        {
            scanf("%llu", &a[i]);
        }

        if((n == 1) && (a[0] == 1))
        {
          printf("2\n1 1\n");
          continue;
        }

        int size = n + 2;
        unsigned long long b[size];
        
        if(n % 2) //odd
        {
            size = n + 2;
            for(int i = 0; i < n - 2; i++)
            {
                b[i] = a[i];
            }
            
            b[n - 2] = a[n - 2] - 1; 
            b[n - 1] = 1;
            b[n] = 1;
            b[n + 1] = a[n - 1] - 1; 

        } else { //even
           
            size = n + 1; 
            for(int i = 0; i < n - 3; i++)
            {
                b[i] = a[i];
            }
            
            b[n - 3] = a[n - 3] - 1;
            b[n - 2] = 1;
            b[n - 1] = a[n - 1] + 1;
            b[n] = a[n - 2] - 1;
            
        }

        int zero_index = -1;

        //check for 0's
        if(b[size - 1] == 0)
        {
          size--; 
        }
        for(int i = 0; i < size; i++)
        {
          if(b[i] == 0)
          {
            zero_index = i; //note where that 0 is
            size = size - 2; 
            break;
          }
        }

        printf("%d\n", size);
        for(int i = 0; i < size; i++)
        {
            if(zero_index == -1)
            {
              printf("%llu", b[i]);

            } else {

              if(i == zero_index - 1)
              {
                printf("%llu", b[i] + 1);
              } else if((i == zero_index) || (i == zero_index + 1)) {
                size++;
                continue;
              } else {
                printf("%llu", b[i]);
              }
            }

            if(i < size - 1)
            {
              printf(" ");
            }
            
        }
        printf("\n");
        
        
    }
    
    
    return 0;
}
                        


                        Solution in C++ :

In  C++  :






#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
  int T;
  scanf("%d", &T);
  for (int testcase = 0; testcase < T; testcase++)
  {
    int n;
    scanf("%d", &n);
    vector<long long> dat(n);
    for (int i = 0; i < n; i++) {
      scanf("%lld", &dat[i]);
    }
    vector<long long> ans;
    if (n == 1) {
      ans.push_back(1);
      ans.push_back(1);
      ans.push_back(dat[0] - 1);
    }
    else if (n == 2) {
      ans.push_back(1);
      ans.push_back(1 + dat[1]);
      ans.push_back(dat[0] - 1);
    }
    else if (n % 2 == 0) {
      for (int i = 0; i < n - 3; i++) {
        ans.push_back(dat[i]);
      }
      ans.push_back(dat[n - 3] - 1);
      ans.push_back(1);
      ans.push_back(1 + dat[n - 1]);
      ans.push_back(dat[n - 2] - 1);
    }
    else {
      for (int i = 0; i < n - 2; i++) {
        ans.push_back(dat[i]);
      }
      ans.push_back(dat[n - 2] - 1);
      ans.push_back(1);
      ans.push_back(1);
      ans.push_back(dat[n - 1] - 1);
    }
    for (;;)
    {
      vector<long long> res;
      for (int i = 0; i < ans.size(); i++)
      {
        long long v = ans[i];
        if (v == 0) {
          if (i + 1 < ans.size()) {
            res.back() += ans[i + 1];
            i++;
          }
          continue;
        }
        res.push_back(v);
      }
      if (res == ans)
        break;
      ans = res;
    }
    printf("%d\n", (int)ans.size());
    for (int i = 0; i < ans.size(); i++) {
      printf("%lld%c", ans[i], " \n"[i + 1 == ans.size()]);
    }
  }
  return 0;
}
                    


                        Solution in Java :

In  Java :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        for (int i = 0; i < t; i++) {
            int n = sc.nextInt();
            long[] a = new long[n];
            for (int j = 0; j < n; j++) {
                a[j] = sc.nextLong();
            }
            if (n==1) {
                if (a[0]==1) {
                    System.out.println(2);
                    System.out.println("1 1");
                } else {
                    System.out.println(3);
                    System.out.println("1 1 "+(a[0]-1));
                }
                continue;
            } else if (n==2) {
                if (a[0]==1) {
                    System.out.println(2);
                    System.out.println("1 "+(a[1]+1));
                } else {
                    System.out.println(3);
                    System.out.println("1 "+(a[1]+1)+" "+(a[0]-1));
                }
                continue;
            }
            int last = (n-1)/2*2;
            ArrayList<Long> al = new ArrayList<Long>();
            for (int j = 0; j < last-1; j++) {
                al.add(a[j]);
            }
            al.add(a[last-1]-1);
            al.add(1l);
            if (last < n-1)
                al.add(1l+a[n-1]);
            else
                al.add(1l);
            al.add(a[last]-1);
            for (int j = 0; j < al.size(); j++) {
                if (al.get(j)==0) {
                    long repnum = al.remove(j-1);
                    al.remove(j-1);
                    if (j-1<al.size())
                        repnum += al.remove(j-1);
                    al.add(j-1,repnum);
                }
            }
            System.out.println(al.size());
            for (int j = 0; j < al.size(); j++) {
                if (j > 0)
                    System.out.print(" ");
                System.out.print(al.get(j));
            }
            System.out.println();
        }
    }
}
                    


                        Solution in Python : 
                            
In  Python3 :







T = int(input())
for t in range(T):
   N = int(input())
   A = [int(x) for x in input().split()]
   if N == 1:
      A = [1, 1, A[0] - 1]
   elif N == 2:
      A = [1, A[1] + 1, A[0] - 1]
   elif N & 1:
      A.append(1)
      A.append(A[-2] - 1)
      A[-4] -= 1
      A[-3] = 1
   else:
      A.append(A[-2] - 1)
      A[-4] -= 1
      A[-3] = 1
      A[-2] += 1
   while A[-1] == 0: A.pop()
   for i in range(len(A)-2, 0, -1):
      if A[i] == 0:
         A[i-1] += A[i+1]
         del A[i:i+2]
   print(len(A))
   print(' '.join(map(str, A)))
                    


View More Similar Problems

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →