using
System;
using
System.Collections.Generic;
namespace
ConsoleApp
{
class
Gfg
{
static
long
p = 31, m = 1000000007;
static
int
power(
int
x,
int
y,
int
mod)
{
int
res = 1;
while
(y > 0)
{
if
(y % 2 == 1)
res = (
int
)((res * (
long
)x) % mod);
y = y >> 1;
x = (
int
)((x * (
long
)x) % mod);
}
return
res % mod;
}
static
int
get_hash(
string
s)
{
long
hash = 0;
long
p_pow = 1;
int
n = s.Length;
for
(
int
i = 0; i < n; i++)
{
hash = ((hash + (s[i] -
'a'
+ 1) * p_pow) % m);
p_pow = (p_pow * p) % m;
}
return
(
int
)hash;
}
static
List<
int
> hashing(
string
s)
{
int
n = s.Length;
List<
int
> hash =
new
List<
int
>(n);
hash.Add(s[0] -
'a'
+ 1);
long
p_pow = p;
for
(
int
i = 1; i < n; i++)
{
hash.Add((
int
)((hash[i - 1] + (s[i] -
'a'
+ 1) * p_pow) % m));
p_pow = (p_pow * p) % m;
}
return
hash;
}
static
int
waysOfFormingString(
string
s, List<
string
> dic)
{
int
n = s.Length;
int
k = dic.Count;
Dictionary<
int
, HashSet<
int
>> hashGrp =
new
Dictionary<
int
, HashSet<
int
>>();
for
(
int
i = 0; i < k; i++)
{
int
p = get_hash(dic[i]);
if
(!hashGrp.ContainsKey(dic[i].Length))
hashGrp[dic[i].Length] =
new
HashSet<
int
>();
hashGrp[dic[i].Length].Add(p);
}
List<
int
> hashedArr = hashing(s);
List<
int
> count =
new
List<
int
>(
new
int
[n]);
for
(
int
i = 0; i < n; i++)
{
foreach
(KeyValuePair<
int
, HashSet<
int
>> x
in
hashGrp)
{
int
len = x.Key;
if
(i + 1 < len)
break
;
int
p_pow = power((
int
)p, i - len + 1, (
int
)m);
int
hashedValue = (i + 1 != len) ?
((hashedArr[i] - hashedArr[i - len]) / p_pow) :
(hashedArr[i] / p_pow);
if
(x.Value.Contains(hashedValue))
count[i] += (i + 1 != len) ? count[i - len] : 1;
}
}
return
count[n - 1];
}
static
void
Main(
string
[] args)
{
string
str =
"abab"
;
List<
string
> dictionary =
new
List<
string
> {
"a"
,
"b"
,
"ab"
};
Console.WriteLine(waysOfFormingString(str, dictionary));
}
}
}