CCCGuide

Problem S3: Searching for Strings

2020 · S3 · Original problem · DMOJ

Problem Description

You’re given a string NN, called the needle, and a string HH, called the haystack, both of which contain only lowercase letters “a"..“z".

Write a program to count the number of distinct permutations of NN which appear as a substring of HH at least once. Note that NN can have anywhere between 1 and ∣N∣!|N|! distinct permutations in total – for example, the string “aab" has 3 distinct permutations (“aab", “aba", and “baa").

Input Specification

The first line contains NN (1≤∣N∣≤200 000)(1 \le |N| \le 200\ 000), the needle string.

The second line contains HH (1≤∣H∣≤200 000)(1 \le |H| \le 200\ 000), the haystack string.

For 3 of the 15 available marks, ∣N∣≤8|N| \le 8 and ∣H∣≤200|H| \le 200.

For an additional 2 of the 15 available marks, ∣N∣≤200|N| \le 200 and ∣H∣≤200|H| \le 200.

For an additional 2 of the 15 available marks, ∣N∣≤2000|N| \le 2000 and ∣H∣≤2000|H| \le 2000.

Output Specification

Output consists of one integer, the number of distinct permutations of NN which appear as a substring of HH.

Sample Input

aab
abacabaa

Output for Sample Input

2

Explanation of Output for Sample Input

The permutations “aba" and “baa" each appear as substrings of HH (the former appears twice), while the permutation “aab" does not appear.