Build a String

Problem Statement :

Greg wants to build a string, S of length N. Starting with an empty string, he can perform 2 operations:

1. Add a character to the end of S for A dollars.
2. Copy any substring of S, and then add it to the end of S for B dollars.

Calculate minimum amount of money Greg needs to build S.

Input Format

The first line contains number of testcases T.

The 2 x T  subsequent lines each describe a test case over 2 lines:
The first contains 3 space-separated integers, , N , A and B, respectively.
The second contains  S (the string Greg wishes to build).


1   <=   T  <=   3
1   <=   N  <=   3 x 10^4
1  <=   A,  B  <=  10000

S is composed of lowercase letters only.

Output Format

On a single line for each test case, print the minimum cost (as an integer) to build S.

Solution :


                            Solution in C :

In  C++  :

#include <cstdio>
#include <algorithm>

using namespace std;

const int inf=1000000000;
struct suffix
    int s1,s2,poz;
    bool operator <(const suffix &aux) const
        if(s1==aux.s1) return s2<aux.s2;
        else return s1<aux.s1;
    bool operator ==(const suffix &aux) const
        return s1==aux.s1 && s2==aux.s2;
struct arbint
    int minn,lazy;
int p[17][30010],logg[30010],pas[30010];
int poz[30010],st[30010],dr[30010],rmq[17][30010],n,sol;
char sir[30010];

int LCP(int x,int y)
    int rez=0;
    for(int i=logg[n];i>=0 && x<=n && y<=n;i--)
        if(p[i][x]==p[i][y]) {rez+=1<<i;x+=1<<i;y+=1<<i;}
    return rez;

void arbint_init(int nod,int st,int dr)
    if(st==dr) return;
    int mid=(st+dr)/2;

void update(int nod,int st,int dr)

void arbint_update(int nod,int st,int dr,int left,int right,int val)
    if(left<=st && dr<=right)
    int mid=(st+dr)/2;
    if(left<=mid) arbint_update(nod*2,st,mid,left,right,val);
    else update(nod*2,st,mid);
    if(mid<right) arbint_update(nod*2+1,mid+1,dr,left,right,val);
    else update(nod*2+1,mid+1,dr);

void arbint_query(int nod,int st,int dr,int poz)
    int mid=(st+dr)/2;
    if(poz<=mid) arbint_query(nod*2,st,mid,poz);
    else arbint_query(nod*2+1,mid+1,dr,poz);

int get_min(int x,int y)
    int lim=logg[y-x+1];
    return min(rmq[lim][x],rmq[lim][y-(1<<lim)+1]);

int main()
    //freopen("", "r", stdin);
    //freopen("file.out", "w", stdout);
    int t;
        int cost1,cost2;
        for(int i=2;i<=n;i++) logg[i]=logg[i/2]+1;
        for(int i=1;i<=n;i++)
        for(int i=1;i<=logg[n]+1;i++)
            for(int j=1;j<=n;j++)
                if(s[j].poz+(1<<(i-1))<=n) s[j].s2=p[i-1][s[j].poz+(1<<(i-1))];
                else s[j].s2=-1;
            for(int j=1;j<=n;j++)
                if(j>1 && s[j]==s[j-1]) p[i][s[j].poz]=p[i][s[j-1].poz];
                else p[i][s[j].poz]=j;
        for(int i=1;i<=n;i++) rmq[0][i]=s[i].poz;
        for(int i=1;i<=logg[n];i++)
            int lim=n-(1<<(i-1))+1;
            for(int j=1;j<=lim;j++) rmq[i][j]=min(rmq[i-1][j],rmq[i-1][j+(1<<(i-1))]);
        for(int i=1;i<=n;i++)
            int st=1,dr=min(n-s[i].poz+1,s[i].poz-1);
                int mid=(st+dr)/2,ok=0;
                int l=1,r=i-1;
                    int m=(l+r)/2;
                    if(get_min(m,i)<=s[i].poz-mid) l=m+1;
                    else r=m-1;
                int a=r;
                    int m=(l+r)/2;
                    if(get_min(i,m)<=s[i].poz-mid) r=m-1;
                    else l=m+1;
                int b=l;
                if(1<=a && LCP(s[a].poz,s[i].poz)>=mid) ok=1;
                if(b<=n && LCP(s[b].poz,s[i].poz)>=mid) ok=1;
                if(ok) st=mid+1;
                else dr=mid-1;
        for(int i=1;i<n;i++)
            if(pas[i+1]) arbint_update(1,1,n,i+1,i+pas[i+1],sol+cost2);
    return 0;

In    Java  :

import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        int T = sc.nextInt();
        for(int t=0;t<T;t++){
            int N = sc.nextInt();
            int A = sc.nextInt();
            int B = sc.nextInt();
            String S =;
            System.out.println( buildStringCost(N,A,B,S) );
    public static int buildStringCost(int N, int A, int B, String S){
        int[] dp = new int[N];
        dp[0] = A;
        int lastL = 0;
        for(int k=1;k<N;++k){
        	dp[k] = dp[k-1]+A;
            int L = lastL+1;
            	String cur = S.substring(k-L+1, k+1);
            	int idx = S.substring(0, k-L+1).indexOf(cur);
            	if( -1==idx )
            		dp[k] = Math.min(dp[k], dp[k-L]+B);
            lastL = L;
        return dp[N-1];

In   C   :

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

char s[30001];
int sublens[30001] = { 0 };

void longestsubstr(int pos) {
    int i, max = 0;
    for (i = 0; i < pos; i++) {
        if (s[i] != s[pos]) sublens[i] = 0;
        else {
            sublens[i] = sublens[i+1] + 1;
            if (i + sublens[i] > pos) sublens[i] = pos - i;
            if (sublens[i] > max) max = sublens[i];
    sublens[pos] = max;

int main() {
    int t, t1;
    scanf("%d", &t);
    for (t1 = 0; t1 < t; t1++) {
        int n, a, b, sublen, i, j, temp;
        scanf("%d %d %d", &n, &a, &b);
        scanf("%s", s);
        int ar[30001];
        for (i = 0; i < n; i++) {
            ar[i] = 0x7FFFFFFF;
            sublens[i] = 0;
        for (i = n - 1; i >= 1; i--) longestsubstr(i);
        ar[0] = a;
        for (i = 1; i < n; i++) {
            if (ar[i-1] + a < ar[i]) ar[i] = ar[i-1] + a;
            sublen = sublens[i];
            temp = ar[i-1] + b;
            for (j = 0; j < sublen; j++) if (temp < ar[i+j]) ar[i+j] = temp;
        printf("%d\n", ar[n-1]);
    return 0;

In   Python3  :

rep = int(input())
for r in range(rep):
    l, a, b = map(int, input().split(' '))
    s = input().strip()
    i = 1
    cost = 0
    cost = [float('inf')] * (l + 1)
    cost[0] = 0
    k = 0
    while i <= l: # i is the number of char finished, s[i-1] finished
        # find the maximun substring
        j = max(i, k)
        while j<=l and (s[i-1:j] in s[:i-1]):
            j += 1
        # s[i-1:j-1] in s
        if j-1 != i:
            cost[j-1] = min(cost[i-1] + b, cost[j-1])
            k = j
        cost[i] = min(cost[i-1] + a, cost[i])
        #print(s[i], a)
        i += 1

View More Similar Problems

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →


This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →