Yet Another KMP Problem


Problem Statement :


This challenge uses the famous KMP algorithm. It isn't really important to understand how KMP works, but you should understand what it calculates.

A KMP algorithm takes a string, S, of length N as input. Let's assume that the characters in S are indexed from 1 to N; for every prefix of S, the algorithm calculates the length of its longest valid border in linear complexity. In other words, for every i (where 1 <= i <= N) it calculates the largest l (where 0 <= l <= i-1) such that for every p (where 1 <= p <= l) there is S[p] = S[i-l+p].

Here is an implementation example of KMP:

kmp[1] = 0;
for (i = 2; i <= N; i = i + 1){
    l = kmp[i - 1];
    while (l > 0 && S[i] != S[l + 1]){
        l = kmp[l];
    }
    if (S[i] == S[l + 1]){
        kmp[i] = l + 1;
    }
    else{
        kmp[i] = 0;
    }
}
Given a sequence x1,x2,...,x26, construct a string, S, that meets the following conditions:

1.The frequency of letter 'a' in S is exactly x1, the frequency of letter 'b' in S is exactly x2, and so on.
Let's assume characters of S are numbered from 1 to N, where Σxi = N. We apply the KMP algorithm to S and get a table, kmp[i], of size N. You must ensure that the sum of kmp[i] for all i is minimal.
If there are multiple strings which fulfill the above conditions, print the lexicographically smallest one.

Input Format

A single line containing 26 space-separated integers describing sequence x.

Constraints

The sum of all xi will be a positive integer <= 10^6.



Solution :



title-img


                            Solution in C :

In C++ :





#include<bits/stdc++.h>
#define mp make_pair
#define PII pair<int,int>
#define fi first
#define se second
using namespace std;

const int NMAX=1000005;

int n,fr[30];
char s[NMAX];

int main()
{
    int i,j,mn,poz,cnt=0,ok;
  //  freopen("date.in","r",stdin);
   // freopen("date.out","w",stdout);
    cin.sync_with_stdio(false);
    mn=1<<30;
    for (i=1;i<=26;i++)
    {
        cin>>fr[i];
        n+=fr[i];
        if (fr[i]<mn && fr[i]>0)
        {
            mn=min(mn,fr[i]);
            poz=i;
        }
        if (fr[i]>0) cnt++;
    }

    if (cnt==1)
    {
        for (i=1;i<=n;i++) s[i]=poz+'a'-1;
        cout<<(s+1)<<"\n";
        return 0;
    }
    for (i=1;i<=n;i++) s[i]='>';
    s[1]=poz+'a'-1;
    fr[poz]--;

    ok=0;
    for (j=1;j<=26 && !ok;j++)
        if (fr[j]>0)
        {
            fr[j]--;
            s[2]=j+'a'-1;
            ok=1;
        }
    i=3;
    if (s[1]==s[2])//a 3-a neaparat diferita
    {
        i=4;
        while (fr[poz])
        {
            s[i]=poz+'a'-1;
            fr[poz]--;
            i+=2;
        }
        cnt=0;
        for (i=1;i<=26;i++) cnt+=fr[i];
        i=1;j=1;
        while (cnt)
            {
                while (s[i]!='>') i++;
                while (fr[j]==0) j++;
                s[i]=j+'a'-1;fr[j]--;
                cnt--;
            }
    }
    else
    {
        i=3;
        for (j=1;j<=26;j++)
            while (fr[j])
            {
                s[i]=j+'a'-1;
                fr[j]--;
                i++;
            }
    }
    cout<<(s+1)<<"\n";
    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 int[] readIntArray3(Scanner in, int size) {
        int[] arr = new int[size];
        for (int i = 0; i < size; i++) {
            arr[i] = in.nextInt();
        }
        return arr;
    }



    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        int cases = 1;//in.nextInt();
        for (int testcase = 0; testcase < cases; testcase++) {
            int[] arr = readIntArray3(in, 26);
            kmpproblem(arr);
        }
    }

    public static void kmpproblem(int[] arr) {
        int least = Integer.MAX_VALUE;
        int leastIndex = -1;
        int smallestIndex = -1;
        for (int i = 0; i < 26; i++) {
            if (arr[i] < least && arr[i] > 0) {
                least = arr[i];
                leastIndex = i;
            }
            if (smallestIndex == -1 && arr[i] > 0) {
                smallestIndex = i;
            }
        }
//        System.out.println(leastIndex + ": " + least);
//        System.out.println(smallestIndex);
        if (leastIndex == -1)  {
            System.out.println("");
            return;
        }
        if (smallestIndex != leastIndex) {
            System.out.print((char)(leastIndex+'a'));
            arr[leastIndex]--;
            for (int i = 0; i < 26; i++) {
                for (int j = 0; j < arr[i]; j++) {
                    System.out.print((char)(i+'a'));
                }
            }
            return;
        }
        System.out.print((char)(leastIndex+'a'));
        arr[leastIndex]--;
        for (int i = leastIndex+1; i < 26; i++) {
            for (int j = 0; j < arr[i]; j++) {
                if (arr[leastIndex] > 0) {
                    System.out.print((char)(leastIndex+'a'));
                    arr[leastIndex]--;
                }
                System.out.print((char)(i+'a'));
            }
        }
        while (arr[leastIndex] > 0) {
            System.out.print((char)(leastIndex+'a'));
            arr[leastIndex]--;
        }

    }
}










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

int main() {
    int letter = 0, min=26, first = -1;
    int data[27];
    data[26]=1000001;
    for(int i = 0; i < 26; i++){
        scanf("%d",data+i);
        if(data[i]) {
            if (first<0) first = i;
            letter++;
            if(data[i]<data[min]) min = i;
        }
    }
    if(letter == 1) {
        for(int i = 0; i < data[min]; i++) {
            putchar('a'+min);
        }
        return 0;
    }
    if (min==first) {
        putchar('a'+min);
        int index_m = 1;
        for (int l = first + 1; l < 26; l++) {
            for (int i = 0; i<data[l]; i++) {
                if(index_m++ < data[min]) putchar('a'+min);
                putchar('a'+l);
            }
        }
    } else {
        putchar('a'+min);
        data[min]--;
        for (int l = first; l < 26; l++) {
            for (int i = 0; i<data[l]; i++) {
                putchar('a'+l);
            }
        }
    }
    
    return 0;
}









In Python3 :





from string import ascii_lowercase as A
import sys
x = list(map(int, input().split()))
used = [i for i in range(26) if x[i]]
if len(used) == 0:
    sys.exit()
if len(used) == 1:
    print(A[used[0]] * x[used[0]])
else:
    f = min(used, key=lambda a: (x[a], a))
    used = [a for a in used if a != f]
    if x[f] == 1:
        print(A[f] + ''.join(A[c]*x[c] for c in used))
    elif f > used[0]:
        x[f] -= 1
        print(A[f] + ''.join(A[c]*x[c] for c in range(26)))
    elif 2*(x[f]-2) <= sum(x)-2:
        res = 2*A[f]
        b = ''.join(A[c]*x[c] for c in used)
        x[f] -= 2
        i = 0
        while x[f]:
            res += b[i] + A[f]
            i += 1
            x[f] -= 1
        res += b[i:]
        print(res)
    else:
        x[f] -= 1
        x[used[0]] -= 1
        print(A[f] + A[used[0]] + A[f]*x[f] + ''.join(A[c]*x[c] for c in used))
                        








View More Similar Problems

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →