Find the numbers of strings that can be formed after processing Q queries
Given a number N(1<=N<=2000)., The task is to find the number strings of size N that can be obtained after using characters from 'a' to 'z' and by processing the given q(1<=q<=200000) queries.
For each query given two integers L, R (0<=L<=R<=N) such that substring [L, R] of the generated string of size N must be a palindrome. The task is to process all queries and generate a string of size N such that the substrings of this string defined by all queries are palindrome.
The answer can be very large. So, output answer modulo 1000000007.
Note: 1-based indexing is considered for the string.
Examples:
Input : N = 3 query 1: (1, 2) query 2: (2, 3) Output : 26 Explanation : Substring 1 to 2 should be palindrome and substring 2 to 3 should be palindrome. so, all three characters should be same. so, we can obtain 26 such strings. Input : N = 4 query 1: (1, 3) query 2: (2, 4) Output : 676 Explanation : substring 1 to 3 should be palindrome and substring 2 to 4 should be a palindrome. So, a first and third character should be the same and second and the fourth should be the same. So, we can obtain 26*26 such strings.
Approach : An efficient solution is to use union-find algorithm.
- Find the mid-point of each range (query) and if there are many queries having the same mid-point then only retain that query whose length is max, i.e (where r – l is max).
- This would have reduced the number of queries to 2*N at max since there is a 2*N number of mid-points in a string of length N.
- Now for each query do union of element l with r, (l + 1) with (r – 1), (l + 2) with (r – 2) and so on. We do this because the character which would be put on the index l would be the same as the one we put on index r. Extending this logic to all queries we need to maintain disjoint-set data structure. So basically all the elements of one component of disjoint-set should have the same letter on them.
- After processing all the queries, let the number of disjoint-set components be x, then the answer is 26^x
.
Below is the implementation of the above approach :
C++
// C++ program to implement above approach#include <bits/stdc++.h>usingnamespacestd;#define N 2005#define mod (int)(1e9 + 7)// To store the size of string and// number of queriesintn, q;// To store parent and rank of ith placeintpar[N], Rank[N];// To store maximum intervalmap<int,int> m;// Function for initializationvoidinitialize(){for(inti = 0; i <= n; i++) {par[i] = i;Rank[i] = 0;}}// Function to find parentintfind(intx){if(par[x] != x)par[x] = find(par[x]);returnpar[x];}// Function to make unionvoidUnion(intx,inty){intxpar = find(x);intypar = find(y);if(Rank[xpar] < Rank[ypar])par[xpar] = ypar;elseif(Rank[xpar] > Rank[ypar])par[ypar] = xpar;else{par[ypar] = xpar;Rank[xpar]++;}}// Power function to calculate a raised to m1// under modulo 10000007intpower(longlonga,longlongm1){if(m1 == 0)return1;elseif(m1 == 1)returna;elseif(m1 == 2)return(1LL * a * a) % mod;elseif(m1 & 1)return(1LL * a * power(power(a, m1 / 2), 2)) % mod;elsereturnpower(power(a, m1 / 2), 2) % mod;}// Function to take maxmium intervalvoidquery(intl,intr){m[l + r] = max(m[l + r], r);}// Function to find different possible stringsintpossiblestrings(){initialize();for(autoi = m.begin(); i != m.end(); i++) {intx = i->first - i->second;inty = i->second;// make union of all chracters which// are meant to be samewhile(x < y) {Union(x, y);x++;y--;}}// find number of different sets formedintans = 0;for(inti = 1; i <= n; i++)if(par[i] == i)ans++;// return the required answerreturnpower(26, ans) % mod;}// Driver Codeintmain(){n = 4;// queriesquery(1, 3);query(2, 4);cout << possiblestrings();return0;}Java
// Java program to implement above approachimportjava.util.*;classGFG{staticfinalintN =2005;staticfinalintmod =1000000007;// To store the size of string and// number of queriesstaticintn, q;// To store parent and rank of ith placestaticint[] par =newint[N], Rank =newint[N];// To store maximum intervalstaticHashMap<Integer,Integer> m =newHashMap<>();// Function for initializationstaticvoidinitialize(){for(inti =0; i <= n; i++){par[i] = i;Rank[i] =0;}}// Function to find parentstaticintfind(intx){if(par[x] != x)par[x] = find(par[x]);returnpar[x];}// Function to make unionstaticvoidUnion(intx,inty){intxpar = find(x);intypar = find(y);if(Rank[xpar] < Rank[ypar])par[xpar] = ypar;elseif(Rank[xpar] > Rank[ypar])par[ypar] = xpar;else{par[ypar] = xpar;Rank[xpar]++;}}// Power function to calculate a raised to m1// under modulo 10000007staticlongpower(longa,longm1){if(m1 ==0)return1;elseif(m1 ==1)returna;elseif(m1 ==2)return(1L * a * a) % mod;elseif(m1 %2==1)return(1L * a * power(power(a, m1 /2),2)) % mod;elsereturnpower(power(a, m1 /2),2) % mod;}// Function to take maxmium intervalstaticvoidquery(intl,intr){if(m.containsKey(l + r))m.put(l + r, Math.max(m.get(l + r), r));elsem.put(l + r, r);}// Function to find different possible stringsstaticlongpossiblestrings(){initialize();for(Integer i : m.keySet()){intx = i - m.get(i);inty = m.get(i);// make union of all chracters which// are meant to be samewhile(x < y){Union(x, y);x++;y--;}}// find number of different sets formedintans =0;for(inti =1; i <= n; i++)if(par[i] == i)ans++;// return the required answerreturnpower(26, ans) % mod;}// Driver Codepublicstaticvoidmain(String[] args){n =4;// queriesquery(1,3);query(2,4);System.out.println(possiblestrings());}}// This code is contributed by// sanjeev2552Python3
# Python3 program to implement above approachN=2005mod=10**9+7# To store the size of string and# number of queriesn, q=0,0# To store parent and rank of ith placepar=[0foriinrange(N)]Rank=[0foriinrange(N)]# To store maximum intervalm=dict()# Function for initializationdefinitialize():foriinrange(n+1):Rank[i], par[i]=0, i# Function to find parentdeffind(x):if(par[x] !=x):par[x]=find(par[x])returnpar[x]# Function to make uniondefUnion(x, y):xpar=find(x)ypar=find(y)if(Rank[xpar] < Rank[ypar]):par[xpar]=yparelif(Rank[xpar] > Rank[ypar]):par[ypar]=xparelse:par[ypar]=xparRank[xpar]+=1# Power function to calculate a raised to m1# under modulo 10000007defpower(a, m1):if(m1==0):return1elif(m1==1):returnaelif(m1==2):return(a*a)%modelif(m1 &1):return(a*power(power(a, m1//2),2))%modelse:returnpower(power(a, m1//2),2)%mod# Function to take maxmium intervaldefquery(l, r):ifl+rinm.keys():m[l+r]=max(m[l+r], r)else:m[l+r]=max(0, r)# Function to find different possible stringsdefpossiblestrings():initialize()foriinm:x=i-m[i]y=m[i]# make union of all chracters which# are meant to be samewhile(x < y):Union(x, y)x+=1y-=1# find number of different sets formedans=0foriinrange(1, n+1):if(par[i]==i):ans+=1# return the required answerreturnpower(26, ans)%mod# Driver Coden=4# queriesquery(1,3)query(2,4)print(possiblestrings())# This code is contributed by Mohit KumarC#
// C# program to implement above approachusingSystem;usingSystem.Collections.Generic;classGFG{constintN = 2005;constintmod = 1000000007;// To store the size of string and// number of queriesstaticintn;//static int q;// To store parent and rank of ith placestaticint[]par =newint[N];staticint[]Rank =newint[N];// To store maximum intervalstaticDictionary<int,int> m =newDictionary<int,int>();// Function for initializationstaticvoidinitialize(){for(inti = 0; i <= n; i++){par[i] = i;Rank[i] = 0;}}// Function to find parentstaticintfind(intx){if(par[x] != x)par[x] = find(par[x]);returnpar[x];}// Function to make unionstaticvoidUnion(intx,inty){intxpar = find(x);intypar = find(y);if(Rank[xpar] < Rank[ypar])par[xpar] = ypar;elseif(Rank[xpar] > Rank[ypar])par[ypar] = xpar;else{par[ypar] = xpar;Rank[xpar]++;}}// Power function to calculate a raised to m1// under modulo 10000007staticlongpower(longa,longm1){if(m1 == 0)return1;elseif(m1 == 1)returna;elseif(m1 == 2)return(1L * a * a) % mod;elseif(m1 % 2 == 1)return(1L * a * power(power(a, m1 / 2), 2)) % mod;elsereturnpower(power(a, m1 / 2), 2) % mod;}// Function to take maxmium intervalstaticvoidquery(intl,intr){if(m.ContainsKey(l + r))m[l + r] = Math.Max(m[l + r], r);elsem[l + r] = r;}// Function to find different possible stringsstaticlongpossiblestrings(){initialize();foreach(KeyValuePair<int,int> iinm){intx = i.Key - m[i.Key];inty = m[i.Key];// Make union of all chracters// which are meant to be samewhile(x < y){Union(x, y);x++;y--;}}// Find number of different sets formedintans = 0;for(inti = 1; i <= n; i++)if(par[i] == i)ans++;// Return the required answerreturnpower(26, ans) % mod;}// Driver CodepublicstaticvoidMain(string[] args){n = 4;// Queriesquery(1, 3);query(2, 4);Console.Write(possiblestrings());}}// This code is contributed by rutvik_56Output:676



