CodeForces 547E:Mike and Friends(AC自动机+DFS序+主席树)

Posted hua-dong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CodeForces 547E:Mike and Friends(AC自动机+DFS序+主席树)相关的知识,希望对你有一定的参考价值。

What-The-Fatherland is a strange country! All phone numbers there are strings consisting of lowercase English letters. What is double strange that a phone number can be associated with several bears!

In that country there is a rock band called CF consisting of n bears (including Mike) numbered from 1 to n.

技术分享图片

Phone number of i-th member of CF is si. May 17th is a holiday named Phone Calls day. In the last Phone Calls day, everyone called all the numbers that are substrings of his/her number (one may call some number several times). In particular, everyone called himself (that was really strange country).

Denote as call(i, j) the number of times that i-th member of CF called the j-th member of CF.

The geek Mike has q questions that he wants to ask you. In each question he gives you numbers l, r and k and you should tell him the number

技术分享图片

Input

The first line of input contains integers n and q (1 ≤ n ≤ 2 × 105 and 1 ≤ q ≤ 5 × 105).

The next n lines contain the phone numbers, i-th line contains a string siconsisting of lowercase English letters (技术分享图片).

The next q lines contain the information about the questions, each of them contains integers l, r and k (1 ≤ l ≤ r ≤ n and 1 ≤ k ≤ n).

Output

Print the answer for each question in a separate line.

Examples

Input
5 5
a
ab
abab
ababab
b
1 5 1
3 5 1
1 5 2
1 5 3
1 4 5
Output
7
5
6
3
6

题意:给定N个串,M次询问,每次询问[L,R]里含多少个X。

思路:(第一次做,结合主席树那里还是不太好想)。对N个串建立AC自动机,建立Fail树,然后得到DFS序。那么,对于每个串S,假设其长度为L,S在AC自动机上面跑,其每个前缀Si在AC自动机上面得到最大深度,对应的Fail树位置,贡献加1,保证这个贡献在Si的后缀的子树里(比如abcdef,那么跑到abcd时,在fail树上面对应的位置贡献加1 ,对于后缀abcd,bcd,cd,d的子树都含这个贡献)。 

        关键是如何出现子树来自于[L,R]的贡献。开始我以为以dfs序为X轴,以来自的串为Y轴建立主席树,查询的时候查询区间[in[u],out[u]],即子树里关键字在[L,R]里的个数。但是发现没有转移关系。所以想不走了。

看了其他人的代码,是以每个串,以来自的串为X轴(从长的前缀到短的前缀),以dfs序为X轴,保证了前缀和的正确性,查询的时候查询区间[L-1,R]的区间在[in[[u],out[u]]的数量。

 

以上是关于CodeForces 547E:Mike and Friends(AC自动机+DFS序+主席树)的主要内容,如果未能解决你的问题,请参考以下文章

CF547E Mike and Friends

Codeforces 798D Mike and distribution - 贪心

Codeforces 798D:Mike and distribution

codeforces #305 B Mike and Feet

codeforces #305 A Mike and Frog

codeforces #305 D Mike and Fish