Chef and Subsequences CodeChef Solution

Problem -Chef and Subsequences 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.

Chef and Subsequences CodeChef Solution in C++14

#include<bits/stdc++.h>
#include<iostream>
#define pw(a) (1LL<<(a))
#define L ((p)<<1)
#define R ((p)<<1|1)
#define endl '\n'
#define int long long
using namespace std;
 
typedef long long LL;
typedef double DD;
typedef pair<int,int> PAIR;
 
const int INF=0x3f3f3f3f;
const int mod=998244353;
const int N=5e5+10;
int n,m,k,T,ans,cnt,sum;
int A[N];
void dfs(int k,int n,int sum,vector<int>&v,vector<int>&a)
{
	if(k==n)
	{
		a.emplace_back(sum);
		return ;
	}
	if(v[k]<=m/sum) dfs(k+1,n,sum*v[k],v,a);
	dfs(k+1,n,sum,v,a);
}
signed main(void)
{
	cin>>n>>m;
	vector<int>u(n/2),v(n-n/2);
for(int &x:u) cin>>x;
	for(int &x:v) cin>>x;
	vector<int>a,b;
	dfs(0,n/2,1,u,a);
	dfs(0,n-n/2,1,v,b);
	sort(a.begin(),a.end());
	for(int x:b)
	{
		int pos=upper_bound(a.begin(),a.end(),m/x)-a.begin();
		ans+=pos;
	}
	cout<<ans-1<<endl;
	return 0;
}

Chef and Subsequences CodeChef Solution in PYTH 3

# cook your dish here
import bisect


def create_subsets(arr,k):
    subset = []
    l = len(arr)
    val  = 2**l
    for i in range(val):
        s = 1
        for j in range(l):
            if i&(1<<j):
                s*=arr[j]
        if s<=k:
            subset.append(s)
    subset.sort()
    return subset



n,k=[int(c) for c in input().split()]
arr =[int(c) for c in input().split()]

b = arr[:(n//2)]
c = arr[(n//2):]

subset1 = create_subsets(b,k)
subset2 = create_subsets(c,k)
# print(b,c)
# print(subset1,subset2)
ans = 0
for i in subset1:
    ans+= bisect.bisect_right(subset2,k//i)

print(ans-1)

Chef and Subsequences CodeChef Solution in C

#include<stdio.h>

long long int ctr=-1,ans=0;
int idx_l=0,idx_r=0;

typedef struct product
{
    int p[300],l;
}pr;

pr left_h[35000],right_h[35000];

pr mult(pr prod,long long int b)
{
    auto long long int ans,carry=0;
    int i=0;
    while(1)
    {
        ans=prod.p[i]*b;
        prod.p[i]=(ans+carry)%10;
        carry=(ans+carry)/10;
        i++;
        if(i>=prod.l && carry==0)
        {
            prod.l=i;
            break;
        }
    }
    return prod;
}
 
int comp(pr prod,pr k)//returns 0 if prod <= k else returns 1
{
    int i;
    if(prod.l>k.l)
    return 1;
    else if(prod.l<k.l)
    return 0;
    else
    {
        for(i=prod.l-1;i>=0;i--)
        if(prod.p[i] > k.p[i])
        return 1;
        else if(prod.p[i] < k.p[i])
        return 0;
        
        if(i<0)
        return 0;
    }
}
 
void chefcode(long long int a[],int i,int n,pr prod,pr k,pr half[])
{
    if(ctr!=-1)
    prod=mult(prod,a[i-1]);
    
	if(!comp(prod,k))
	{
	    ctr++;
	    
	    if(ctr > 0)
	    half[ctr-1]=prod;//erroneous!	    
    }
	else
	return;
	
	for(i;i<n;i++)
	chefcode(a,i+1,n,prod,k,half);
	
	return ;
}
void swap(int i,int j,pr half[])
{
    pr tmp=half[j];
    half[j]=half[i];
    half[i]=tmp;
}
void sort(long long int a[],int n)
{
    int i,j;
    
    for(i=1;i<n;i++)
    for(j=i;j>0;j--)
    if(a[j]<a[j-1] && a[j]!=a[j-1])
    a[j]^=a[j-1]^=a[j]^=a[j-1];
}
void heapify(pr arr[],int n,int i)
{
    int smallest = i;  
    int l = 2*i + 1;  
    int r = 2*i + 2;  
    
    if(l < n && comp(arr[l],arr[smallest]))
        smallest = l;
 
    if(r < n && comp(arr[r],arr[smallest]))
        smallest = r;
 
    if (smallest != i)
    {
        swap(i,smallest,arr);
        
        heapify(arr, n, smallest);
    }
}
void heapsort(pr arr[],int n)
{
    int i;
    
    for (i = n / 2 - 1; i >= 0; i--)
        heapify(arr, n, i);
 
    for (i=n-1; i>=0; i--)
    {
        swap(0,i,arr);
        
        heapify(arr, i, 0);
    }
}
pr product(pr a, pr b)
{
	int i=0,j,carry=0,val=0;
	pr c;
	while(i < a.l+b.l-1 || carry!=0)
	{
		for(j=0;j<b.l;j++)
		{
			if(i-j>=0 && i-j<a.l)
		    val+=b.p[j] * a.p[i-j];
		}
		c.p[i]=(val+carry)%10;
		carry=(val+carry)/10;
		val=0;i++;
	}
	c.l=i;
	
	return c;
}
int b_search(pr arr[],int low,int high,pr key,pr k)
{
    while(low < high)
    {
        int mid=(low+high+1)/2;
        if(!comp(product(arr[mid],key),k))
        low=mid;
        
        else
        high=mid-1;
    }
    if(!comp(product(arr[low],key),k))
    return low;
    return -1;
}
void print(pr arr[],int n)
{
	int i,j;
	for(i=0;i<n;i++)
	{
	    for(j=arr[i].l-1;j>=0;j--)
	    printf("%d",arr[i].p[j]);
	    
	    printf("\n");
	}
}
int main()
{
	long long int x,a[30];
	int i,n;
	pr prod,k;
	for(i=0;i<300;i++)
	prod.p[i]=0;
	
	k.l=0;
    prod.p[0]=1;
    prod.l=1;
	scanf("%d %lld",&n,&x);
 
	for(i=0;i<n;i++)
	scanf("%lld",&a[i]);
    
    sort(a,n);
    
    while(x)
    {
        k.p[k.l++]=x%10;
        x/=10;
    }
    
	chefcode(a,0,n/2,prod,k,left_h);
	ans+=ctr;idx_l=ctr;
	//printf("ans1=%lld\n",ans);
	ctr=-1;
	chefcode(a,n/2,n,prod,k,right_h);
	ans+=ctr;idx_r=ctr;
	//printf("ans2=%lld\n",ans);
	/*
	print(left_h,idx_l);//correct!
	printf("idx_l=%d\n",idx_l);
	printf("\n");
	print(right_h,idx_r);//correct!
	printf("idx_r=%d\n",idx_r);
	//*/
	
	heapsort(left_h,idx_l);
	heapsort(right_h,idx_r);
	/*
	printf("after sorting:\n");
	print(left_h,idx_l);//correct!
	printf("\n");
	print(right_h,idx_r);//correct!
	//*/	
	
	int j=idx_r-1;
	
	for(i=0;i<idx_l;i++)
	if(!comp(left_h[i],k))
	{
	    if(j==-1)
	    break;
	    j=b_search(right_h,0,j,left_h[i],k);
	    
	    ans+=j+1;
	}
	
	printf("%lld",ans);
	return 0;
}  

Chef and Subsequences CodeChef Solution in JAVA

 import java.util.*;
import java.io.*;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.math.BigInteger;
public final class Main{
    static class Reader {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;
 
        public Reader() {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }
 
        public Reader(String file_name) throws IOException {
            din = new DataInputStream(
                new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }
 
        public String readLine() throws IOException {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1) {
                if (c == '\n') {
                    if (cnt != 0) {
                        break;
                    }
                    else {
                        continue;
                    }
                }
                buf[cnt++] = (byte)c;
            }
            return new String(buf, 0, cnt);
        }
 
        public int nextInt() throws IOException {
            int ret = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
 
            if (neg)
                return -ret;
            return ret;
        }
 
        public long nextLong() throws IOException {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }
 
        public double nextDouble() throws IOException {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
 
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (c == '.') {
                while ((c = read()) >= '0' && c <= '9') {
                    ret += (c - '0') / (div *= 10);
                }
            }
            if (neg) return -ret;
            return ret;
        }
 
        private void fillBuffer() throws IOException {
            bytesRead = din.read(buffer, bufferPointer = 0,
                                 BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }
        private byte read() throws IOException {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }
 
        public void close() throws IOException {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Kattio extends PrintWriter {
        private BufferedReader r;
        private StringTokenizer st;
    
        // standard input
        public Kattio() { this(System.in, System.out); }
        public Kattio(InputStream i, OutputStream o) {
            super(o);
            r = new BufferedReader(new InputStreamReader(i));
        }
        // USACO-style file input
        public Kattio(String problemName) throws IOException {
            super(new FileWriter(problemName + ".out"));
            r = new BufferedReader(new FileReader(problemName + ".in"));
        }
    
        // returns null if no more input
        public String next() {
            try {
                while (st == null || !st.hasMoreTokens())
                    st = new StringTokenizer(r.readLine());
                return st.nextToken();
            } catch (Exception e) { }
            return null;
        }
    
        public int nextInt() { return Integer.parseInt(next()); }
        public double nextDouble() { return Double.parseDouble(next()); }
        public long nextLong() { return Long.parseLong(next()); }
    }   
    
    static Kattio sc = new Kattio();
    static long  mod  = (long)1e9+7;
    static PrintWriter out =new PrintWriter(System.out);
    public static void buildHeap(int arr[], int n) {
        for(int i = n/2-1;i>=0;i--) {
            heapify(arr,n,i);
        }
        
    }
 
    //Heapify function to maintain heap property.
    public static void heapify(int arr[], int n, int i) {
        int l = i*2 + 1 , r = i*2 + 2;
        int small = l;
        if(r<n&& arr[r]<arr[small]) {
            small = r;
        }
        if(l>=n || arr[i]< arr[small]) return;
        if(small != i)swap(small, i, arr);
        heapify(arr,n,small);
    }
    public static void swap(int i,int j,int arr[]) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    public static void heapSort(int arr[], int n) {
        buildHeap(arr,n);
        System.out.println(Arrays.toString(arr));
        int ans[] = new int[n];
        int l = 0 , r = n-1;
        while(l<=r) {
            swap(l,r,arr);
            r--;
            heapify(arr,r + 1,0);
            
        }       
    }
    public static long getInversion(String a) {
        long zero =0;
        for(char ch : a.toCharArray()) {
            if(ch=='0') zero++;
        }
        long ans = 0;
        for(char ch : a.toCharArray()) {
            if(ch=='1') {
                ans += zero;
            }
            else zero--;
        }
        return  ans;
    }
    public static List<Integer> getAllParent (int node) {
        List<Integer> list = new ArrayList<>();
        while(node >= 1) {
            list.add(node);
            node /= 2;
        }
        return list;
    }
    public static boolean isSubsequence(String small, String big) {

        int i =0 , j = 0;
        while(i< small.length() && j < big.length()) {
            if(small.charAt(i) == big.charAt(j)) {
                i++;
                j++;
            }
            else {
                j++;
            }
        }
        if(i >= small.length()) return true;
        else return false;
    }
    static long arr[][] = new long[1005][1005];
    public static void main(String[] args)throws IOException {
        int t =  1;
        while(t-->0) {
            solve();
        }
        out.close();
    }
    
    public static void solve()throws IOException {
        int n = sc.nextInt();
        long k = sc.nextLong();
        List<Long> list = new ArrayList<>();
        for(int i =0;i<n;i++) {
            long val = sc.nextLong();
            if(val > k) continue;
            list.add(val);
        }
        if(list.size() == 0) {
            System.out.println(0);
            return;
        }
        n = list.size();
        List<BigInteger> list1 = new ArrayList<>();
        List<BigInteger> list2 = new ArrayList<>();
        callfun(new BigInteger("1"),0 , n/2 , list ,list1);
        callfun(new BigInteger("1"), n/2 + 1 , n -1, list , list2);
        Collections.sort(list1);
        Collections.sort(list2);
        // System.out.println(list1);
        // System.out.println(list2);
        
        BigInteger nk = new BigInteger(k + "");
        long ans = 0;
        for(int i =0;i<list1.size();i++)  {
            int l = 0 , r = list2.size() -1;
            while(l <= r) {
                int mid = l + (r-l)/2;
                BigInteger check = list2.get(mid).multiply(list1.get(i));
                if(check.compareTo(nk) <= 0) {
                    l = mid + 1;
                }
                else r = mid-1;
            }
            if(r < 0) continue;
            else ans += r +  1;
        }
        System.out.println(ans - 1);
    }

    public static void callfun(BigInteger mul , int l ,int r, List<Long> arr , List<BigInteger> list) {
        if(r < l) {
            list.add(mul);
            return;
        }
        callfun(mul , l+1 ,r ,  arr , list);
        BigInteger newval = new BigInteger(arr.get(l) + "");
        newval = mul.multiply(newval);
        callfun(newval, l + 1 , r , arr , list);
    }
    
    public static void dfs(HashSet<Integer> set , int node , int arr[] , List<Integer> list) {
        if(set.contains(node)) {
            list.add(node + 1);
            return;
        }
        set.add(node);
        dfs(set , arr[node]-1 , arr,list);
    }
    public static int getLastIndex(long val , int l , int r ,long arr[]) {
        if(arr[l] > val) return -1;
        if(arr[r] <= val) return r;
        while(l <= r) {
            int mid = l + (r-l)/2;
            if(arr[mid] > val) {
                r = mid-1;
            }
            else l = mid + 1;
        }
        return r;
    }


    public static long getx(long num) {
        for(long i =0;i<=64;i++) {
            if((1l<<i) == num) return i;
        }
        return 64;
    }
    public static long pow(long a , long b) {
        long mod = (long)1e9+7;
        if(b == 1) return a;
        if(b == 0) return 1;
        long ans = pow(a , b/2)%mod;
        if(b%2 == 0) {
            return (ans*ans)%mod;
        }
        else {
            return ((ans*ans)%mod*a)%mod;
        }
    }
    public static long getAns(int len) {
        long mod = 998244353l;
        if(len == 1) return 45;
        else {
            long min = pow(10 , len -1);
            long max = pow(10 , len) -1;
            long ans = (max - min + 1)%mod;
            ans = ((ans*(ans + 1))%mod)/2;
            return (ans + getAns(len -1))%mod;
        }
    }
    public static int maxLen(int[] arr, int n) {
        for(int i =0;i<n;i++) {
            if(arr[i] == 0)arr[i] = -1;
        }
        for(int i =1;i<n;i++) {
            arr[i] += arr[i-1];
        }
        System.out.println(Arrays.toString(arr));
        HashMap<Integer , Integer> map = new HashMap<>();
        map.put(0 ,-1);
        int ans = 0;
        for(int  i = 0;i<n;i++) {
            if(map.containsKey(arr[i]*-1)) {
                ans = Math.max(ans ,i -  map.get(arr[i]*-1));
            }
            map.putIfAbsent(arr[i] , i);
        }
        return ans;
    }
    public static int getDifference(char a[] , char b[] , int l1 , int r1,int l2,int r2) {
        int ans = 0;
        while(l1<=r1 && l2 <= r2) {
            if(a[l1] != b[l2]) ans++;
            l1++;
            l2++;
        }
        return ans;
    }

    public static long callfun(int x1 , int y1,int x2,int y2,long arr[][] , long memo[][]) {
        if(x1 == x2 && y1 ==  y2) return arr[x1][y1];
        if(x1 > x2) return Integer.MIN_VALUE;
        if(y1 > y2) return Integer.MIN_VALUE;
        if(memo[x1][y1] != -1) return memo[x1][y1];
        else {
            return memo[x1][y1] = arr[x1][y1] + Math.max(callfun(x1 + 1 ,y1 ,x2,y2,arr , memo ),callfun(x1 ,y1 + 1 ,x2,y2,arr , memo )); 
        }
    }
    public static boolean isVowel(char ch) {
        if(ch == 'a' || ch == 'e'||ch == 'i' || ch == 'o' || ch == 'u') return true;
        return false;
    }

    
    
    public static String getAns(int i,int j,String s) {
        if(j>=s.length()) return s.charAt(i) + "";
        while(i>=0 && j<s.length() && s.charAt(i) == s.charAt(j)) {
            i--;
            j++;
        }
        return s.substring(i +1, j);
    }
    
    
    public static int getFactor(int num) {
        if(num==1) return 1;
        int ans = 2;
        int k = num/2;
        for(int i = 2;i<=k;i++) {
            if(num%i==0) ans++;
        }
        return Math.abs(ans);
    }
   


    public static int geti(char ch) {
        if(ch=='R') return 2;
        if(ch=='L') return 3;
        if(ch=='U') return 1;
        else return 0;
    }
    public static int[] readarr()throws IOException {
        int n = sc.nextInt();
        int arr[] = new int[n];
        for(int i =0;i<n;i++) {
            arr[i] =  sc.nextInt();
        }
        return arr;
    }
 
    public static boolean isPowerOfTwo (long x) {
        return x!=0 && ((x&(x-1)) == 0);
    }
    public static boolean isPrime(long num) {
        if(num==1) return false;
        if(num<=3) return true;
        if(num%2==0||num%3==0) return false;
        for(long i =5;i*i<=num;i+=6) {
            if(num%i==0) return false;
        }
        return true;
    }
    public static boolean isPrime(int num) {
        if(num==1) return false;
        if(num<=3) return true;
        if(num%2==0||num%3==0) return false;
        for(int i =5;i*i<=num;i+=6) {
            if(num%i==0) return false;
        }
        return true;
    }
    public static long gcd(long a , long b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }
    public static long get_gcd(long a , long b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }
    public static long fac(long num)  {
        long ans = 1;
        int mod = (int)1e9+7;
        for(long i = 2;i<=num;i++) {
            ans  =  (ans*i)%mod;
        }
        return ans;
    }
}

Chef and Subsequences CodeChef Solution in PYPY 3

from sys import stdin
input = stdin.readline

def ncr(n , r):

    num , den = 1 , 1
    for i in range(r):

        num *= n
        den *= r

        n , r = n - 1 , r - 1

    return num // den


def solve(i , prod):

    if(i == len(b)):return 1

    ans = solve(i + 1 , prod)

    p = prod
    for j in range(1 , d[b[i]] + 1):

        p *= b[i]
        if(p > k):break

        ans += solve(i + 1 , p) * ncr(d[b[i]] , j)


    return ans


def answer():

    global b , d

    d = dict()
    for i in range(n):

        d[a[i]] = d.get(a[i] , 0) + 1


    b = list(d.keys())
    ans = solve(0 , 1)

    return ans - 1

    
for T in range(1):

    n , k = map(int,input().split())
    a = list(map(int,input().split()))

    print(answer())

Chef and Subsequences CodeChef Solution in PYTH

from bisect import bisect_right
def find_le(a, x):
    i = bisect_right(a, x)
    if i:
        return i-1
    return -1
n,k = map(int,raw_input().split()); a = map(int,raw_input().split())
n1 = n - n/2; n2 = n - n1; ls1 = a[:n1]; ls2 = a[n1:]; t = []; u = []; ans = 0
for i in xrange(1,pow(2,n1)):
	f = 0; p = 1;
	for j in xrange(n1):
		if i & (1<<j):
			f = 1;p *= ls1[j]
	if f:
		if p <= k:
			t.append(p); ans += 1
for i in xrange(1,pow(2,n2)):
	f = 0; p = 1;
	for j in xrange(n2):
		if i & (1<<j):
			f = 1; p *= ls2[j]
	if f:
		if p <= k:
			u.append(p); ans += 1
t.sort(); u.sort();
for num in t:
	ans += find_le(u,k*1.0/num)+1 
print ans

Chef and Subsequences CodeChef Solution in C#

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTest
{
    class Program
    {

        public static double[] L = new double[32720];
        public static double[] R = new double[32720];

        public static void Main()
        {
            int N;
            long K;
            string[] tokens;

            StreamReader reader = new StreamReader(Console.OpenStandardInput());

            tokens = reader.ReadLine().Split(' ');
            N = int.Parse(tokens[0]);
            K = long.Parse(tokens[1]);

            long[] A = new long[N];
            double[] lg = new double[N];
            double lgK = Math.Log10(K);
            tokens = reader.ReadLine().Split(' ');


            for (int i = 0; i < N; i++)
            {
                A[i] = long.Parse(tokens[i]);
                lg[i] = Math.Log10(A[i]);
            }

            if (N == 1)
            {
                Console.WriteLine(A[0] <= K ? 1 : 0);
                return;
            }

            int j;
            int mask;
            int L = N / 2;
            int R = N - L;

            double[] B = new double[1 << L];
            double[] C = new double[1 << R];

            int count;
            double sum;
            int ans = 0;

            // left
            count = 1 << L;

            for (int i = 1; i < count; i++)
            {
                j = 0;
                sum = 0.0;
                mask = 1 << (L - 1);
                while (mask > 0)
                {
                    if ((mask & i) > 0)
                    {
                        sum += lg[j];
                    }
                    mask >>= 1;
                    j++;
                }
                B[i] = sum;
            }

            count = 1 << R;

            for (int i = 1; i < count; i++)
            {
                j = L;
                sum = 0.0;

                mask = 1 << (R - 1);
                while (mask > 0)
                {
                    if ((mask & i) > 0)
                    {
                        sum += lg[j];
                    }
                    mask >>= 1;
                    j++;
                }
                C[i] = sum;
            }

            MergeSort(C, 1, count - 1);

            ans = 0;
            int a, b, mid;
            count = 1 << L;
            for (int i = 1; i < count; i++)
            {
                if (B[i] > lgK) continue;
                ans++;

                if(B[i] + C[1] > lgK)
                {
                    continue;
                }
                
                // upper
                a = 1;
                b = (1 << R) - 1;
                while (a <= b)
                {
                    mid = (b + a) / 2;
                    if (C[mid] + B[i] > lgK)
                    {
                        b = mid-1;
                    }
                    else
                    {
                        a = mid+1;
                    }
                }

                ans += b;
            }
            
            count = 1 << R;
            for(int i = 1; i< count; i++)
            {
                if (C[i] <= lgK)
                {
                    ans++;
                }
                else break;
            }

            Console.WriteLine(ans);
            reader.Close();

        }

        public static void MergeSort(double[] A, int p, int r)
        {
            if (p < r)
            {
                int q = (p + r) >> 1;
                MergeSort(A, p, q);
                MergeSort(A, q + 1, r);
                Merge(A, p, q, r);
            }
        }

        public static void Merge(double[] A, int p, int q, int r)
        {
            int n1, n2, i, j;
            n1 = q - p + 1;
            n2 = r - q;
            for (i = 1; i <= n1; i++)
            {
                L[i] = A[p + i - 1];
            }
            for (i = 1; i <= n2; i++)
            {
                R[i] = A[q + i];
            }
            L[n1 + 1] = double.MaxValue;
            R[n2 + 1] = double.MaxValue;
            i = j = 1;
            for (int k = p; k <= r; k++)
            {
                if (L[i] <= R[j])
                {
                    A[k] = L[i];
                    i++;
                }
                else
                {
                    A[k] = R[j];
                    j++;
                }
            }
        }


    }
}

Chef and Subsequences CodeChef Solution in GO

package main

import (
	"bufio"
	"fmt"
	"math/big"
	"os"
	"sort"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)
var wtr = bufio.NewWriter(os.Stdout)

/* ByBigInt implements sort.Interface for []*(big.Int) */
type ByBigInt []*(big.Int)

func (a ByBigInt) Len() int           { return len(a) }
func (a ByBigInt) Less(i, j int) bool { return a[i].Cmp(a[j]) == -1 }
func (a ByBigInt) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func meetInTheMiddle(v []uint64) []*(big.Int) {
	power := 1 << uint(len(v))
	result := make([]*big.Int, 0, power)

	for i := 0; i < power; i++ {
		var product = big.NewInt(1)
		for j := 0; j < len(v); j++ {
			if ((i >> uint(j)) & 1) == 1 {
				product = new(big.Int).Mul(product, big.NewInt(int64(v[j])))
			}
		}
		result = append(result, product)
	}

	// > Go 1.4
	// sort.Slice(result, func(i int, j int) bool {
	// 	return result[i].Cmp(result[j]) == -1
	// })
	sort.Sort(ByBigInt(result))

	return result

}
func exec() {
	var n int
	var k uint64
	fmt.Scanf("%d", &n)
	fmt.Scanf("%d", &k)
	a := make([]uint64, n)

	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &a[i])
	}

	if n == 1 {
		if a[0] <= k {
			fmt.Fprintln(wtr, 1)
		} else {
			fmt.Fprintln(wtr, 0)
		}
		_ = wtr.Flush()
		return
	}
	var firstHalfProducts = meetInTheMiddle(a[0 : len(a)/2])
	var lastHalfProducts = meetInTheMiddle(a[len(a)/2:])
	// for i := 0; i < len(firstHalfProducts); i++ {
	// 	fmt.Printf("first[%d] = %s\n", i, firstHalfProducts[i].String())
	// }
	// for i := 0; i < len(lastHalfProducts); i++ {
	// 	fmt.Printf("last[%d] = %s\n", i, lastHalfProducts[i].String())
	// }

	ans := big.NewInt(0)
	bigK := big.NewInt(int64(k))

	for i := 0; i < len(firstHalfProducts); i++ {
		threshold := new(big.Int).Div(bigK, firstHalfProducts[i])
		index := sort.Search(len(lastHalfProducts), func(j int) bool { return lastHalfProducts[j].Cmp(threshold) == 1 })
		// fmt.Printf("first[%d] = %s, threshold = %s, index = %d\n", i, firstHalfProducts[i].String(), threshold.String(), index)
		ans.Add(ans, big.NewInt(int64(index)))

	}
	// fmt.Printf("ans = %s\n", ans.String())
	fmt.Fprintln(wtr, ans.Sub(ans, big.NewInt(1)))
	_ = wtr.Flush()

}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	exec()
}
Chef and Subsequences CodeChef Solution Review:

In our experience, we suggest you solve this Chef and Subsequences 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 Chef and Subsequences CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Chef and Subsequences 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 *