Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Mahesh and his lost array CodeChef Solution

Problem -Mahesh and his lost array CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

Mahesh and his lost array CodeChef Solution in C++14

#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
	// your code goes here

	int t; cin>>t;
	while(t--){
	    int n; cin>>n;
	    	multiset<int>ms;
	    for(int i=0;i<(1<<n);i++){
	        int a; cin>>a;
	        if(a!=0) ms.insert(a);
	       // cout<<a<<" ";
	    }
	    vector<int>v,ans;
	      
	    auto it = ms.begin();
	    int f=*it;
	    v.push_back(f);
	    ans.push_back(f);
	    ms.erase(ms.find(f));
	   // it++;
	 
	   if(ans.size()<n)  {
	         it = ms.begin();
	         int s=*it;
    	     v.push_back(s);
    	     ans.push_back(s);
    	     ms.erase(ms.find(s));
	        
        	 int tmp = f+s;
        	 v.push_back(tmp);
        	 ms.erase(ms.find(tmp));
	   }
	   
	   //cout<<f<<" "<<s<<"\n";

	    while(ans.size()<n){
	         int m=v.size();
	         auto it1 = ms.begin();
	         int val = *it1;
	         ans.push_back(val);
	         v.push_back(val);
	         ms.erase(ms.find(val));
	         for(int i=0;i<m;i++){
	            int valtmp = v[i]+val;
	            ms.erase(ms.find(valtmp));
	            v.push_back(valtmp);
	         }
	    }
	    
	    for(auto i:ans) cout<<i<<" ";
	    cout<<"\n";
	    
	}
	return 0;
}

Mahesh and his lost array CodeChef Solution in PYTH 3

from itertools import permutations
from bisect import bisect_left as bl
for __ in range(int(input())):
    n=int(input())
    li=list(map(int,input().split()))
    li.sort()
    li.pop(0)
    t0=[]
    s=[]
    while li:
        t1=[]
        c=li.pop(0)
        for i in t0:
            li.pop(bl(li,c+i))
            t1.append(c+i)
        t1.append(c)
        t0=t0+list(t1)
        s.append(c)
    for i in range(n):
        print(s[i],end=' ')
    print()

Mahesh and his lost array CodeChef Solution in C

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

int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

void merge(int* a, int* b,int n)
{
    int i=0,j=0,k=0,c[35000];

    while(i<n && j<n)
    {
        if(a[i]<=b[j])
        {
            c[k++]=a[i++];
        }
        else
        {
            c[k++]=b[j++];
        }
    }

    while(i<n)
    {
        c[k++]=a[i++];
    }

    while(j<n)
    {
        c[k++]=b[j++];
    }

    for(i=0;i<2*n;i++)
    {
        b[i]=c[i];
    }
}

int main()
{
	int t,a[35000],n,p,i,num,mysum[35000],found,p2,next,temp[35000],j,numbers[20];

	scanf("%d",&t);

	while(t--)
	{
        scanf("%d",&n);

        p=pow(2,n);

        for(i=0;i<p;i++)
        {
            scanf("%d",&a[i]);
        }


        qsort(a,p,sizeof(int),cmpfunc);

        mysum[0]=a[0];
        mysum[1]=a[1];

        numbers[0]=a[1];

        found = 1;
        p2=2;

        i=2;

        while(found<n)
        {
            while(i<p2 && a[i]==mysum[i])
            {
                i++;
            }

            next=a[i];

            numbers[found]=next;

            found++;

            for(j=0;j<p2;j++)
            {
                temp[j]=next+mysum[j];
            }
            merge(temp,mysum,p2);

            i++;
            p2*=2;
        }

        for(i=0;i<n;i++)
        {
            printf("%d ",numbers[i]);
        }

        printf("\n");

	}

	return 0;
}

Mahesh and his lost array CodeChef Solution in JAVA

import java.util.*;

public class Main {

	public static Scanner sc = new Scanner (System.in);
	
	public static void main(String[] args) {
	    
	    int t = sc.nextInt();
	    
	    while(t-->0){
	        
	        int n = sc.nextInt();
	        int size = 1<<n;
	        int arr[] = new int[size];
	        
	        for(int i=0; i<size; i++){
	            arr[i] = sc.nextInt();
	        }
	        
	        Arrays.sort(arr);
	        
	        int ans[] = new int[n];
	        int pos = 0;
	        
	        PriorityQueue<Integer> pq = new PriorityQueue<>();
	        List<Integer> sub = new ArrayList<>();
	        
	        for(int i=1; i<size; i++){
	            
	            int curr = -1;
	            
	            if(!pq.isEmpty()){
	                curr = pq.peek();
	            }
	            
	            if(curr == arr[i]){
	                pq.poll();
	            }else{
	                
	                ans[pos++] = arr[i];
	                
	                int len = sub.size();
	                
	                for(int j=0; j<len; j++){
	                    int val = sub.get(j)+arr[i];
	                    sub.add(val);
	                    pq.add(val);
	                }
	                sub.add(arr[i]);
	                
	            }
	            
	            if(pos == n) break;
	                
	            
	        }
	        
	        for(int i=0;i<n;i++)
                System.out.print(ans[i]+" ");
            System.out.println();
	        
	        
	        
	        
	        
	    }
	
		
	}

}

Mahesh and his lost array CodeChef Solution in PYPY 3

# cook your dish here

for _ in range(int(input())):
    n =int(input())
    arr=[int(c) for c in input().split()]
    subset =[]
    arr.sort()
    p =[]
    ans =[]
    x = 1
    while len(ans)!= n:
        while len(p) >0 and p[0] < arr[x]:
            p.pop(0)

        if p and p[0] == arr[x]:
            p.pop(0)
        else:
            ans.append(arr[x])
            subset.append(arr[x])
            for i in range(len(subset)-1):
                subset.append(subset[i] + arr[x])
                p.append(subset[i] + arr[x])
        
        p.sort()

        x+=1

    print(*ans)

Mahesh and his lost array CodeChef Solution in PYTH

import heapq
for _ in xrange(input()):
    n=input()
    a=map(int,raw_input().split())
    if n==1:

        print a[1]
        continue
    heapq.heapify(a)
    heapq.heappop(a)
    l=[]
    c1=heapq.heappop(a)
    c2=heapq.heappop(a)
    l.append(c1)
    l.append(c2)
    r=[c1,c2,c1+c2]
    fir=a[0]
    ind=2
    r1=[i for i in r]
    """if fir==r[2]:
        heapq.heappop(a)
        ind=3
    else:
        for i in range(3):
            r.append(r+i)
        heapq.heappop(a)
        l.append(fir)"""

    while len(l)!=n:
        if a[0] in r and a[0]!=l[-1]:
            r.remove(a[0])
            heapq.heappop(a)

        else:
            cu=heapq.heappop(a)
            n5=len(r1)
            r.append(cu)
            r1.append(cu)
            for i in range(n5):
                r.append(cu+r1[i])
                r1.append(cu+r1[i])

            l.append(cu)

    for i in l:
        print i,
    print
"""2
1
0 10
2
0 1 1 2"""



Mahesh and his lost array CodeChef Solution in C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;

// (づ°ω°)づミ★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    public object Solve()
    {
        for (int tt = ReadInt(); tt > 0; tt--)
        {
            int n = ReadInt();
            var a = ReadIntArray();
            var dict = new Dictionary<int, int>();
            foreach (int aa in a)
            {
                if (!dict.ContainsKey(aa))
                    dict[aa] = 0;
                dict[aa]++;
            }
            if (dict[0] == 1)
                dict.Remove(0);
            else
                dict[0]--;

            var ans = new int[n];
            for (int i = 0; i < n; i++)
            {
                ans[i] = dict.Keys.Min();
                for (int mask = 1; mask < 1 << i + 1; mask++)
                {
                    if ((mask & 1 << i) == 0)
                        continue;
                    int sum = 0;
                    for (int j = 0; j <= i; j++)
                        if ((mask >> j & 1) == 1)
                            sum += ans[j];
                    if (dict[sum] == 1)
                        dict.Remove(sum);
                    else
                        dict[sum]--;
                }
            }

            WriteArray(ans);
        }

        return null;
    }


    #region I/O
    protected static TextReader reader;
    protected static TextWriter writer;

    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = Console.In;
        writer = new StreamWriter(Console.OpenStandardOutput());
#endif

        Solver solver = new Solver();

        try
        {
            object result = solver.Solve();
            if (result != null)
            {
                writer.WriteLine(result);
            }
        }
        catch (Exception ex)
        {
#if DEBUG
            Console.WriteLine(ex);
#else
            Console.WriteLine(ex);
            throw;
#endif
        }
        reader.Close();
        writer.Close();
    }

    #endregion

    #region Read/Write

    private static Queue<string> currentLineTokens = new Queue<string>();

    private static string[] ReadAndSplitLine()
    {
        return reader.ReadLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public static string ReadToken()
    {
        while (currentLineTokens.Count == 0)
            currentLineTokens = new Queue<string>(ReadAndSplitLine());
        return currentLineTokens.Dequeue();
    }

    public static int ReadInt()
    {
        return int.Parse(ReadToken());
    }

    public static long ReadLong()
    {
        return long.Parse(ReadToken());
    }

    public static double ReadDouble()
    {
        return double.Parse(ReadToken(), CultureInfo.InvariantCulture);
    }

    public static int[] ReadIntArray()
    {
        return ReadAndSplitLine().Select(x => int.Parse(x)).ToArray();
    }

    public static long[] ReadLongArray()
    {
        return ReadAndSplitLine().Select(x => long.Parse(x)).ToArray();
    }

    public static double[] ReadDoubleArray()
    {
        return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray();
    }

    public static int[][] ReadIntMatrix(int numberOfRows)
    {
        int[][] matrix = new int[numberOfRows][];
        for (int i = 0; i < numberOfRows; i++)
            matrix[i] = ReadIntArray();
        return matrix;
    }

    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows);
        int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++)
        {
            ret[i] = new int[numberOfRows];
            for (int j = 0; j < numberOfRows; j++)
                ret[i][j] = matrix[j][i];
        }
        return ret;
    }

    public static string[] ReadLines(int quantity)
    {
        string[] lines = new string[quantity];
        for (int i = 0; i < quantity; i++)
            lines[i] = reader.ReadLine().Trim();
        return lines;
    }

    public static void WriteArray<T>(params T[] array)
    {
        writer.WriteLine(string.Join(" ", array.Select(x => x.ToString()).ToArray()));
    }

    #endregion
}
Mahesh and his lost array CodeChef Solution Review:

In our experience, we suggest you solve this Mahesh and his lost array CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Mahesh and his lost array CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Mahesh and his lost array CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *