Longest Palindromic Subsequence


Problem Statement :


Steve loves playing with palindromes. He has a string, s, consisting of n lowercase English alphabetic characters (i.e., a through z). He wants to calculate the number of ways to insert exactly 1 lowercase character into string s such that the length of the longest palindromic subsequence of s increases by at least k. Two ways are considered to be different if either of the following conditions are satisfied:

The positions of insertion are different.
The inserted characters are different.
This means there are at most 26*(n+1) different ways to insert exactly  1character into a string of length n.

Given q queries consisting of n, k, and s, print the number of different ways of inserting exactly 1 new lowercase letter into string s such that the length of the longest palindromic subsequence of s increases by at least k.

Input Format

The first line contains a single integer, q, denoting the number of queries. The 2q subsequent lines describe each query over two lines:

1.The first line of a query contains two space-separated integers denoting the respective values of n and k.
2.The second line contains a single string denoting s.
Constraints
1 <= q <= 10
1 <= n <= 3000
0 <= k <= 50
It is guaranteed that s consists of lowercase English alphabetic letters (i.e., a to z) only.



Solution :



title-img


                            Solution in C :

In C++ :





#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define PII pair<int,int>
#define VI vector<int>
#define VPII vector<pair<int,int> >
#define PLL pair<long long,long long>
#define VPLL vector<pair<long long,long long> >
#define F first
#define S second
typedef long long LL;
using namespace std;
const int MOD = 1e9+7;
const int SIZE = 3005;
int dp[SIZE][SIZE];
int dp2[SIZE][SIZE];
char s[SIZE];
int main(){
    CASET{
        DRII(n,K);
        RS(s+1);
        if(K>2)puts("0");
        else if(K==0){
            printf("%d\n",n*26+26);
        }
        else{
            MS0(dp);
            MS0(dp2);
            REPP(i,1,n+1)dp2[i][i]=1;
            REPP(j,1,n){
                for(int k=1;k+j<=n;k++){
                    int ll=k,rr=k+j;
                    if(s[ll]==s[rr])dp2[ll][rr]=max(dp2[ll][rr],dp2[ll+1][rr-1]+2);
                    dp2[ll][rr]=max(dp2[ll][rr],dp2[ll+1][rr]);
                    dp2[ll][rr]=max(dp2[ll][rr],dp2[ll][rr-1]);
                }
            }
            int ma=0;
            for(int i=1;i<n;i++){
                for(int j=n;j>i;j--){
                    if(s[i]==s[j])dp[i][j]=dp[i-1][j+1]+2;
                    else dp[i][j]=max(dp[i-1][j],dp[i][j+1]);
                    ma=max(ma,dp[i][j]);
                }
            }
            REPP(i,1,n+1)ma=max(ma,dp[i-1][i+1]+1);
            int an=0;
            REP(i,n+1){
                int me=0;
                me=dp[i][i+1]+1;
                if(me>=ma+K){
                    an+=26;
                    continue;
                }
                bool used[26]={};
                REPP(j,1,n+1){
                    if(j<=i){
                        if(dp2[j+1][i]+dp[j-1][i+1]+2>=ma+K)used[s[j]-'a']=1;
                    }
                    else{
                        if(dp2[i+1][j-1]+dp[i][j+1]+2>=ma+K)used[s[j]-'a']=1;
                    }
                }
                REP(j,26)
                    if(used[j]){
                        an++;
                    }
            }
            printf("%d\n",an);
        }
    }
    return 0;
}








In Java :





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

public class Solution {

    static int longestPalindromicSubsequence(String s, int k)
    {
        int n = s.length();
        
        if (k == 0)
        {
            return (n + 1) * 26;
        }
        
        if (k > 2)
        {
            return 0;
        }
        
        if (n == 1)
        {
            if (k == 1)
            {
                return 2;
            }
            
            return 0;
        }
        
        short pal[][] = computePal(s);
        short rightEnds[][] = computeRightEnds(s);
        short leftEnds[][] = computeLeftEnds(s);
        int sMax = pal[0][n - 1];
        
        boolean ok[][] = new boolean[n + 1][26];
        
        for (int i = 0; i <= n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                char c = s.charAt(j);
                int min;
                int max;
                int middle = 0;
                
                if (i <= j)
                {
                    if (i < j)
                    {
                        middle = pal[i][j - 1];
                    }
                    
                    min = i;
                    max = j;
                }
                else
                {
                    if (j + 1 <= i - 1)
                    {
                        middle = pal[j + 1][i - 1];
                    }
                    
                    min = j;
                    max = i - 1;
                }
                
                int need = sMax + k - middle - 2;
                
                if (need % 2 == 1)
                {
                    need++;
                }
                
                if (rightEnds[min][need / 2] > max + 1 ||
                   leftEnds[max + 1][need / 2] <  min)
                {
                    ok[i][c - 'a'] = true;
                    //System.out.println("ok " + i + " " + c);
                }
            }
        }
        
        /*for (int i = 0; i <= n; i++)
        {
            for (int j = n - 1; j > i; j--)
            {
                int midLength = sMax - pal[i][j - 1];

                if (midLength % 2 == 0 &&
                    rightEnds[i][midLength / 2] > j)
                {
                    ok[i][s.charAt(j) - 'a'] = true;
                }
            }
        }
        
        for (int i = n; i >= 0; i--)
        {
            for (int j = 0; j < i - 1; j++)
            {
                int midLength = sMax - pal[j + 1][i - 1];

                if (midLength % 2 == 0 &&
                    leftEnds[i][midLength / 2] < j)
                {
                    ok[i][s.charAt(j) - 'a'] = true;
                }
            }
        }*/
        
        if (k == 1)
        {
            if (sMax % 2 == 0)
            {
                for (int i = sMax / 2; i < n; i++)
                {
                    if (rightEnds[i][sMax / 2] >= i)
                    {
                        for (int j = 0; j < 26; j++)
                        {
                            ok[i][j] = true;
                        }
                    }
                }
            }
            else
            {
                /*int half = sMax / 2;
                
                for (int i = 0; i < n; i++)
                {
                    int ch = s.charAt(i) - 'a';
                    
                    for (int j = i; j >= half; j--)
                    {
                        if (rightEnds[j][half] > i)
                        {
                            ok[j][ch] = true;
                        }
                        else
                        {
                            break;
                        }
                    }
                    
                    for (int j = i + 1; j <= n - half; j++)
                    {
                        if (leftEnds[j][half] < i)
                        {
                            ok[j][ch] = true;
                        }
                        else
                        {
                            break;
                        }
                    }
                }*/
            }
        }
        
        int total = 0;
        
        for (int i = 0; i <= n; i++)
        {
            for (int j = 0; j < 26; j++)
            {
                if (ok[i][j])
                {
                    total++;
                }
            }
        }
        
        return total;
    }
    
    private static short[][] computeRightEnds(String s)
    {
        short n = (short) s.length();
        short ends[][] = new short[n + 1][n / 2 + 1];

        for (int i = 0; i < ends.length; i++)
        {
            for (int j = 0; j < ends[i].length; j++)
            {
                ends[i][j] = -1;
            }
        }

        ends[0][0] = n;
        
        for (int len = 1; len <= n; len++)
        {
            ends[len][0] = n;
            
            int i = n - 1;
                
            while (i >= 0 && s.charAt(i) != s.charAt(len - 1))
            {
                i--;
            }
            
            for (int c = 1; c <= n / 2 && c <= len; c++)
            {
                ends[len][c] = (short) Math.max(-1, ends[len - 1][c]);
                
                while (i >= ends[len - 1][c - 1])
                {
                    i--;
                    
                    while (i >= 0 && s.charAt(i) != s.charAt(len - 1))
                    {
                        i--;
                    }
                }
                
                if (i >= len)
                {
                    ends[len][c] = (short) Math.max(ends[len][c], i);
                }
            }
        }
        
        return ends;
    }
    
    private static short[][] computeLeftEnds(String s)
    {
        short n = (short) s.length();
        short ends[][] = new short[n + 1][n / 2 + 1];
        
        for (int i = 0; i < ends.length; i++)
        {
            for (int j = 0; j < ends[i].length; j++)
            {
                ends[i][j] = n;
            }
        }
        
        ends[n][0] = -1;
            
        for (int k = n - 1; k >= 0; k--)
        {
            ends[k][0] = -1;

            int i = 0;
                
            while (i < n && s.charAt(i) != s.charAt(k))
            {
                i++;
            }
            
            for (int c = 1; c <= n / 2 && c <= n - k; c++)
            {
                ends[k][c] = (short) Math.min(n, ends[k + 1][c]);
                
                while (i <= ends[k + 1][c - 1])
                {
                    i++;
                    
                    while (i < n && s.charAt(i) != s.charAt(k))
                    {
                        i++;
                    }
                }
                
                if (i < k)
                {
                    ends[k][c] = (short) Math.min(ends[k][c], i);
                }
            }
        }
        
        return ends;
    }
    
    private static short[][] computePal(String s)
    {
        int n = s.length();
        short pal[][] = new short[n][n];
        
        for (int i = 0; i < n; i++)
        {
            pal[i][i] = 1;
        }
        
        for (int d = 1; d < n; d++)
        {
            for (int i = 0, j = d; j < n; i++, j++)
            {
                if (s.charAt(i) == s.charAt(j))
                {
                    if (d == 1)
                    {
                        pal[i][j] = 2;
                    }
                    else
                    {
                        pal[i][j] = (short) (pal[i + 1][j - 1] + 2);
                    }
                }
                else
                {
                    pal[i][j] = (short) Math.max(pal[i][j - 1], pal[i + 1][j]);
                }
            }
        }

        return pal;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            int n = in.nextInt();
            int k = in.nextInt();
            String s = in.next();
            int result = longestPalindromicSubsequence(s, k);
            System.out.println(result);
        }
        in.close();
    }
}








In C :





#include<stdio.h>
#define M 3005
int q, n, k;
char s[M];
int in[M][M], out[M][M];
int max(int a, int b)
{
    return a > b ? a : b;
}
int main()
{
    scanf("%d", &q);
    while(q--)
    {
        scanf("%d %d", &n, &k);
        scanf("%s", s);
        if( k == 0 )
        {
            printf("%d\n", ( n + 1 ) * 26);
            continue;
        }
        if( k > 2 )
        {
            printf("0\n");
            continue;
        }
        for( int l = 0 ; l < n ; l++ )
        {
            for( int i = 0 ; i + l < n ; i++ )
            {
                int j = i + l;
                if( i == j )
                {
                    in[i][j] = 1;
                }
                else if( s[i] == s[j] )
                {
                    if( i + 1 < j )
                    {
                        in[i][j] = 2 + in[i+1][j-1];
                    }
                    else
                    {
                        in[i][j] = 2;
                    }
                }
                else
                {
                    in[i][j] = max(in[i+1][j], in[i][j-1]);
                }
            }
        }
        for( int l = n - 1 ; l >= 0 ; l-- )
        {
            for( int i = 0 ; i + l < n ; i++ )
            {
                int j = i + l;
                if( i == j )
                {
                    if( 0 < i && j + 1 < n )
                    {
                        out[i][j] = 1 + out[i-1][j+1];
                    }
                    else
                    {
                        out[i][j] = 1;
                    }
                }
                else if( s[i] == s[j] )
                {
                    if( 0 < i && j + 1 < n )
                    {
                        out[i][j] = 2 + out[i-1][j+1];
                    }
                    else
                    {
                        out[i][j] = 2;
                    }
                }
                else
                {
                    out[i][j] = 0;
                    if( 0 < i )
                    {
                        out[i][j] = max(out[i][j], out[i-1][j]);
                    }
                    if( j + 1 < n )
                    {
                        out[i][j] = max(out[i][j], out[i][j+1]);
                    }
                }
            }
        }
        int cur = in[0][n-1], res = 0;
        for( int i = 0 ; i <= n ; i++ )
        {
            for( char ch = 'a' ; ch <= 'z' ; ch++ )
            {
                int my = ( i == 0 || i == n ) ? 1 : 1 + out[i-1][i];
                for( int j = 0 ; j < i && my < cur + k ; j++ )
                {
                    if( s[j] == ch )
                    {
                        int cand = 2;
                        if( 0 < j && i < n )
                        {
                            cand += out[j-1][i];
                        }
                        if( j + 1 <= i - 1 )
                        {
                            cand += in[j+1][i-1];
                        }
                        my = max(my, cand);
                    }
                }
                for( int j = i ; j < n && my < cur + k ; j++ )
                {
                    if( s[j] == ch )
                    {
                        int cand = 2;
                        if( 0 < i && j + 1 < n )
                        {
                            cand += out[i-1][j+1];
                        }
                        if( i <= j - 1 )
                        {
                            cand += in[i][j-1];
                        }
                        my = max(my, cand);
                    }
                }
                if( my >= cur + k )
                {
                    res++;
                }
            }
        }
        printf("%d\n", res);
    }
    return 0;
}
                        








View More Similar Problems

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 →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →