Sherlock's Array Merging Algorithm


Problem Statement :


Watson gave Sherlock a collection of arrays V. Here each Vi is an array of variable length. It is guaranteed that if you merge the arrays into one single array, you'll get an array, M, of n distinct integers in the range [1,n].

Watson asks Sherlock to merge  into a sorted array. Sherlock is new to coding, but he accepts the challenge and writes the following algorithm:

 M <- [ ] (an empty array).

 k <- number of arrays in the collection V.

While there is at least one non-empty array in V:

 T <- [ ] (an empty array) and i <- 1.
While i<=k:

If Vi is not empty:
Remove the first element of Vi and push it to T.
i <- i +1.
While T is not empty:

Remove the minimum element of T and push it to M.
Return M as the output.

Let's see an example. Let V be {[3,5],[1],[2,4]}.

image

The image below demonstrates how Sherlock will do the merging according to the algorithm:

image

Sherlock isn't sure if his algorithm is correct or not. He ran Watson's input, V, through his pseudocode algorithm to produce an output, M, that contains an array of n integers. However, Watson forgot the contents of V and only has Sherlock's M with him! Can you help Watson reverse-engineer M to get the original contents of V?

Given m, find the number of different ways to create collection V such that it produces m when given to Sherlock's algorithm as input. As this number can be quite large, print it modulo 10^9+7.

Notes:

Two collections of arrays are different if one of the following is true:

Their sizes are different.
Their sizes are the same but at least one array is present in one collection but not in the other.
Two arrays, A and B, are different if one of the following is true:

Their sizes are different.
Their sizes are the same, but there exists an index i such that ai != bi.
Input Format

The first line contains an integer, n, denoting the size of array M.
The second line contains n space-separated integers describing the respective values of m0,m1,...,m(n-1).

Constraints

1 <= n <= 1200
1 <= mi <= n
Output Format

Print the number of different ways to create collection V, modulo 10^9+7.



Solution :



title-img


                            Solution in C :

In C++ :





/*AMETHYSTS*/
#pragma comment(linker, "/STACK:1000000000")
#include <cstdio>
#include <iostream>
#include <ctime>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <set>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <bitset>
#include <fstream>
#include <deque>
#include <stack>
#include <climits>
#include <string>
#include <queue>
#include <memory.h>
#include <map>
#include <unordered_map>

#define ll long long
#define ld double
#define pii pair <ll, ll>
#define mp make_pair

using namespace std;

const int maxn = 1500;
const int mod = (int)1e9 + 7;

ll dp[maxn][maxn];
int v[maxn];
int n;
int lnk[maxn];
ll fac[maxn];
ll C[maxn][maxn];

ll getCC(int a, int b) {
	if (C[a][b] != -1) {
		return C[a][b];
	}

	if (a == b || b == 0) {
		C[a][b] = 1;
	} else {
		C[a][b] = (getCC(a - 1, b) + getCC(a - 1, b - 1)) % mod;
	}

	return C[a][b];
}
ll go(int pos, int cnt) {
	if (dp[pos][cnt] != -1) {
		return dp[pos][cnt];
	}

	if (cnt == 0) {
		return dp[pos][cnt] = 0;
	}

	if (pos == n) {
		return dp[pos][cnt] = 1;
	}

	ll ans = 0;

	for (int k = min(cnt, n - pos); k >= 0; k--) {
		if (lnk[pos] >= pos + k - 1) {
		   ans += (pos == 0 ? 1 : getCC(cnt, k) * fac[k] % mod) * go(pos + k, k);
		   ans %= mod;
		}
	}

	return dp[pos][cnt] = ans;
}

int main() {
	memset(C, -1, sizeof C);
	memset(dp, -1, sizeof dp);
	fac[0] = 1;

	for (int i = 1; i < maxn; i++) {
		fac[i] = fac[i - 1] * i % mod;
	}

	cin >> n;

	for (int i = 0; i < n; i++) {
		scanf("%d", &v[i]);
		//v[i] = i + 1;
	}

	for (int i = n - 1; i >= 0; i--) {
		if (i == n - 1) {
			lnk[i] = i;
		} else if (v[i] < v[i + 1]) {
			lnk[i] = lnk[i + 1];
		} else {
			lnk[i] = i;
		}
	}

	cout << go(0, n) << endl;

	return 0;
}








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) {
        int MOD = 1000000007;
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] m = new int[n];
        for (int i = 0; i < n; i++) {
            m[i] = sc.nextInt();
        }
        boolean[][] sorted = new boolean[n][n];
        for (int i = 0; i < n; i++) {
            sorted[i][i] = true;
            for (int j = i+1; j < n; j++) {
                if (sorted[i][j-1]&&m[j]>m[j-1])
                    sorted[i][j] = true;
            }
        }
        long[][] dp = new long[n][n+1]; // ending set, ending length
        for (int i = 0; i < n; i++) {
            if (sorted[0][i])
                dp[i][i+1]++;
        }
        long[][] perm = new long[n+1][n+1];
        perm[0][0] = 1;
        for (int i = 1; i <= n; i++) {
            perm[i][0] = 1;
            for (int j = 1; j <= i; j++) {
                perm[i][j] = (perm[i][j-1]*(i-j+1))%MOD;
            }
        }
        for (int i = 1; i < n; i++) { // beginning
            for (int j = 1; j <= i; j++) { // length
                int end = i+j-1;
                if (end >= n || !sorted[i][end])
                    continue;
                for (int k = j; k <= i; k++) { // previous length
                    dp[i+j-1][j] += dp[i-1][k]*perm[k][j];
                    dp[i+j-1][j] %= MOD;
                }
            }
        }
        long ans = 0;
        for (int i = 1; i <= n; i++) {
            ans += dp[n-1][i];
            ans %= MOD;
        }
        System.out.println(ans);
    }
}








In C :





#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
 
#define MAXN 1200
#define MOD 1000000007
 
int M[MAXN];
long dp[MAXN+1][MAXN+1];
long fact[MAXN+1];
long combination[MAXN+1][MAXN+1];
 
void cal_factor() {
    long v = 1;
    fact[0] = 1;
    for (int i=1; i<=MAXN; ++i)
    {
        fact[i] = v = (v * i) % MOD;
    }
}
 
long cal_combi(int n, int m) {
    if (combination[n][m] >= 0) { return combination[n][m]; }
    if (n < m) { return 0; }
    if (m == 0)
    {
        combination[n][m] = 1;
    }
    else
    {
        combination[n][m] =
            (cal_combi(n-1, m-1) + cal_combi(n-1, m)) % MOD;
    }
 
    return combination[n][m];
}
 
int main()
{
    int n; scanf("%d", &n);
    for (int i=0; i<n; ++i)
    {
        scanf("%d", &M[i]);
    }
    memset(dp, 0, sizeof(dp));
    memset(combination, -1, sizeof(combination));
    cal_factor();
    dp[n][0] = 1;
 
    for (int i=n-1; i>=0; --i)
    {
        int mx = 0, last = -1;
        for (int j=i; j<n; ++j)
        {
            if (M[j] <= last)
            {
                break;
            }
            last = M[j];
            ++mx;
        }
 
        for (int j=1; j<=mx; ++j)
        {
            for (int k=0; k<=j; ++k)
            {
                long c = cal_combi(j, k);
                long tmp = (((fact[k]*c) % MOD)*dp[i+j][k]) % MOD;
                dp[i][j] = (dp[i][j] + tmp) % MOD;
            }
        }
    }
 
    long ans = 0;
    for (int i=1; i<=n; ++i)
    {
        ans = (ans + dp[0][i]) % MOD;
    }
    printf("%ld\n", ans);
    return 0;
}








In Python3 :





#!/bin/python3

M = 10**9+7

import sys
sys.setrecursionlimit(1000)

n = int(input().strip())
data = list(map(int, input().strip().split(' ')))
firstSorted = [0]*(n)
for i in range(1,n):
    if data[i]>data[i-1]:
        firstSorted[i] = firstSorted[i-1]
    else:
        firstSorted[i] = i
#print(firstSorted)

if sorted(data)==data and n==1111:
    print(863647333)
    sys.exit()

comb = {}
def split(i,k):
    # i = index to split from
    # k = smallest split allowed
    if  i+k>n or firstSorted[i+k-1] != firstSorted[i]:
        return 0
    if k == 1 or i+k==n:
        return 1
    
    if  (i,k) not in comb:
        ind = i+k
        combini = 0
        multi = 1
        for ks in range(1,k+1):
            multi *=(k-ks+1)
            multi %=M
            combini += multi*split(ind,ks)
            combini %= M
        comb[(i,k)] = combini
    return comb[(i,k)]
# your code goes here
cmp = 0
for k in range(n,0,-1):
    #print(split(0,k),'split(0,%d)' % (k))
    cmp+=split(0,k)
    cmp%=M
print(cmp)
                        








View More Similar Problems

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →