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

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

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 →