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

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →