Square Subsequences


Problem Statement :


Square Subsequences

A string is called a square string if it can be obtained by concatenating two copies of the same string. For example, "abab", "aa" are square strings, while "aaa", "abba" are not. Given a string, how many (non-empty) subsequences of the string are square strings? A subsequence of a string can be obtained by deleting zero or more characters from it, and maintaining the relative order of the remaining characters.

Input Format

The first line contains the number of test cases, T.
T test cases follow. Each case contains a string, S.

Output Format

Output T lines, one for each test case, containing the required answer modulo 1000000007.

Constraints:
1 <= T <= 20
S will have at most 200 lowercase characters ('a' - 'z').



Solution :



title-img


                            Solution in C :

In C++ :






#include<iostream>
#include<set>
#include<map>
#include<string>
#include<stdio.h>
#include<sstream>
#include<algorithm>
#include<queue>
#include<cmath>
#include<string.h>
using namespace std ;
#define MAXN 305
#define INF (int)1e9
#define MOD 1000000007

int brute(string s)
{
 int n = s.size() ;
 int ret = 0 ;
 for(int i = 1;i < 1 << n;i++)
 {
  string t ;
  for(int j = 0;j < n;j++)
   if(i & 1 << j)
    t.push_back(s[j]) ;
  if(t.size() % 2 == 1) continue ;
  int tt = t.size() ;
  bool valid = true ;
  for(int j = 0;j < tt / 2;j++)
   if(t[j] != t[tt / 2 + j])
    valid = false ;
  if(valid) ret++ ;
 }
 return ret ;
}

string s ;
int n ;
int start1,start2 ;

int memo[MAXN][MAXN] ;
int solve(int k1,int k2)
{
 if(k1 == start2 || k2 == n) return 0 ;
 int ret = s[k1] == s[k2] ? 1 : 0 ;
 if(memo[k1][k2] != -1) return memo[k1][k2] ;
 ret += solve(k1 + 1,k2) ;
 ret += solve(k1,k2 + 1) ;
 if(ret >= MOD) ret -= MOD ; 
 ret -= solve(k1 + 1,k2 + 1) ;
 if(ret < 0) ret += MOD ;
 if(s[k1] == s[k2]) ret += solve(k1 + 1,k2 + 1) ;
 if(ret >= MOD) ret -= MOD ; 
 return memo[k1][k2] = ret ;
}

int solve(string _s)
{
 s = _s ;
 n = s.size() ;
 int ret = 0 ;
 for(start2 = 0;start2 < n;start2++)
 {
  memset(memo,255,sizeof memo) ;
  for(start1 = 0;start1 < start2;start1++)
   if(s[start1] == s[start2])
   {
    int cret = 1 + solve(start1 + 1,start2 + 1) ;
    ret += cret ;
    if(ret >= MOD) ret -= MOD ;
   }
 }
 return ret ;
}

void test()
{
 for(int test = 0;test < 10000;test++)
 {
  int n = rand() % 10 + 1 ;
  string t ;
  for(int j = 0;j < n;j++) t.push_back('a' + rand() % 2) ;
  int ret1 = brute(t) ;
  int ret2 = solve(t) ;
  cout << ret1 << " " << ret2 << endl ;
  if(ret1 != ret2)
  {
   cout << "Failed on: " << test << endl ;
   cout << t << endl ;
   while(1) ;
  }
 }
}

void generate()
{
 char in[10] = "in .txt" ;
 for(int test = 0;test < 10;test++)
 {
  in[2] = test + '0' ;
  FILE * fout = fopen(in,"w") ;
  
  int runs = 20 ;
  fprintf(fout,"%d\n",runs) ;
  for(int t = 0;t < runs;t++)
  {
   string c ;
   int n = rand() % 200 + 1 ;
   if(test < 2) n = rand() % 20 + 1 ;
   
   if(test < 4) for(int i = 0;i < n;i++) c.push_back(rand() % 26 + 'a') ;
   else if(test < 7) for(int i = 0;i < n;i++) c.push_back(rand() % 3 + 'a') ;
   else if(test < 10) for(int i = 0;i < n;i++) c.push_back(rand() % 2 + 'a') ;

   fprintf(fout,"%s\n",c.c_str()) ;
  }
 }
}


int main()
{
// test() ; return 0 ;
// generate() ; return 0 ;

 int runs ;
 cin >> runs ;
 while(runs--)
 {
  string s ;
  cin >> s ;
  int ret = solve(s) ;
  cout << ret << endl ;
 }
 return 0 ;
}








In Java :





import java.io.*;
import java.util.*;

public class Solution implements Runnable {
    final static int MOD = 1000000007;

    int count(String a, String b) {
        int n = a.length();
        int m = b.length();
        int dp[][] = new int[n + 1][m + 1];
        int sum[][] = new int[n + 1][m + 1];
        for (int i = 0; i <= n; ++ i) {
            sum[i][m] = 1;
        }
        for (int j = 0; j <= m; ++ j) {
            sum[n][j] = 1;
        }
        for (int i = n - 1; i >= 0; -- i) {
            for (int j = m - 1; j >= 0; -- j) {
                if (a.charAt(i) == b.charAt(j)) {
                    dp[i][j] = sum[i + 1][j + 1];
                } 
                sum[i][j] = (sum[i + 1][j] + sum[i][j + 1]
                    - sum[i + 1][j + 1] + dp[i][j]) % MOD;
            }
        }
        int result = 0;
        for (int i = 0; i < n; ++ i) {
            result += dp[i][0];
            result %= MOD;
        }
        return result;
    }

    int count(String s) {
        int n = s.length();
        int result = 0;
        for (int i = 1; i < n; ++ i) {
            result += count(s.substring(0, i), s.substring(i, n));
            result %= MOD;
        }
        return (result + MOD) % MOD;
    }

    public void run() {
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(System.in));
            int testCount = Integer.parseInt(reader.readLine());
            while (testCount > 0) {
                testCount --;
                System.out.println(count(reader.readLine()));
            }
        } catch (Exception e) {
        }
    }

    public static void main(String args[]) {
        new Thread(new Solution()).run();
    }
}








In C :





#include <stdio.h>

#define P 1000000007

char s[500];
long long i,j,k,l,m,n,t,kk;
//a[210][210][210],
long long b[210][210][210];

int main()
{

scanf("%lld\n",&t);
while(t--)
{
scanf("%s\n",s);

//printf("%s %lld",s,n);

n=0;
while(s[n]) n++;

//printf("%s %lld\n",s,n);

for(j=0;j<=n;j++)
 for(i=j;i<=n;i++) 
  for(k=i;k<=n;k++) b[j][i][k]=0;

m=0;

for(k=n-1;k>=0;k--)
 for(i=k-1;i>=0;i--)
  for(j=i;j>=0;j--)
   {
     b[j][i][k] = 0;
     //b[j+1][i][k];
     
     if(s[j]==s[k])
           {
          // a[j][i][k] = (1+b[j+1][i][k+1])%P; 
           if(i+1==k) m = (m+1+b[j+1][i][k+1])%P;
           
           b[j][i][k] = (b[j][i][k] +1 + b[j+1][i][k+1])%P;
//           printf("%c %lld %lld b=%lld\n",s[j],j,k,b[j][i][k]);
           } 
    b[j][i][k] = (b[j][i][k]+b[j][i][k+1]+b[j+1][i][k]-b[j+1][i][k+1]);
   
   l++;
   }

//printf("%lld=l\n",l);

//m=0;

//for(i=0;i<n;i++) 
// for(k=i+1;k<n;k++) m+= a[i][k-1][k];

printf("%lld\n",m);

//printf("%lld %lld=n\n",b[0][13][14],n);
//printf("%lld %lld=n\n",b[4][14][15],n);

}


return 0;
}








In Python3 :





from sys import stderr

def dp(a,b):
    c = [[0 for j in range(len(b))] for i in range(len(a))]
    for i in range(len(b)):
        if a[0] == b[i]:
            c[0][i] = 1
        if i:
            c[0][i] += c[0][i-1]
            c[0][i] %= mod
    for i in range(1,len(a)):
        c[i][0] = c[i-1][0]
        for j in range(1,len(b)):
            c[i][j] = c[i-1][j] + c[i][j-1] - c[i-1][j-1]
            if a[i] == b[j]:
                c[i][j] += c[i-1][j-1]
                c[i][j] %= mod
    return c[len(a)-1][len(b)-1]
    

def backtrack(c,a,b,i,j):
    if i == 0 or j == 0:
        return ''
    elif a[i-1] == b[j-1]:
        return backtrack(c,a,b,i-1,j-1) + a[i-1]
    else:
        if c[i][j-1] > c[i-1][j]:
            return backtrack(c,a,b,i,j-1)
        else:
            return backtrack(c,a,b,i-1,j)

mod = 1000000007
    
t = int(input().strip())

for _ in ' '*t:
    s = list(input().strip())
    s = ''.join(x for x in s if s.count(x) > 1)
    c = 0
    
    for k in range(1,len(s)):
        d = dp(s[k:],s[:k])
        print(s[:k],s[k:],file=stderr)
        print(d,file=stderr)
        c += d
        c %= mod
            
    print(c)
                        








View More Similar Problems

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →