luogu#P5231. [JSOI2012] 玄武密码

    ID: 4198 远端评测题 2000ms 512MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>字符串2012各省省选江苏后缀自动机 SAMO2优化AC 自动机后缀数组 SA

[JSOI2012] 玄武密码

Background

By the beautiful Xuanwu Lake, beside Jiming Temple and in front of Jilong Mountain, there is a rich and beautiful land called Jinxiang River. It is said that one day, a trace of purple aura came down from the sky, and in an instant it disappeared into the Jinxiang River. The elders said that this was the Xuanwu spirit hiding the heavenly book here.

Many years later, people finally found writings with the Xuanwu cipher in the Jinxiang River area. Even more amazingly, these writings with the Xuanwu cipher have a subtle connection with the structure of Taicheng on the south bank of Xuanwu Lake. Thus, the long work of deciphering began.

Problem Description

After analysis, we can use the four directions east, south, west, and north to describe how the Taicheng bricks are arranged. Let a sequence ss of length nn describe it, where the elements are E, S, W, N, representing the four directions east, south, west, and north. We call this the main string.

The mysterious Xuanwu cipher is mm segments of text described by the patterns of the Four Symbols. The Four Symbols are the Azure Dragon of the east, the White Tiger of the west, the Vermilion Bird of the south, and the Xuanwu of the north, corresponding to the four directions east, south, west, and north.

Now the archaeologists have met a difficult problem. For each text segment tt, find its longest prefix pp such that pp is a substring of ss.

Input Format

The first line contains two integers, representing the length nn of the main string and the number mm of text segments.

The second line contains a string of length nn, representing the main string ss.

The next mm lines each contain a string, representing a text segment tt with the Xuanwu cipher.

Output Format

For each text segment, output one integer per line, representing the length of the longest pp.

7 3
SNNSSNS
NNSS
NNN
WSEE

4
2
0

Hint

Constraints

  • For 20%20\% of the data, n100n \leq 100, m50m \leq 50.
  • For 40%40\% of the data, n2×104n \leq 2 \times 10^4, m2×103m \leq 2 \times 10^3.
  • For 70%70\% of the data, n106n \leq 10^6, m2×104m \leq 2 \times 10^4.
  • For 100%100\% of the data, 1n1071 \leq n \leq 10^7, 1m1051 \leq m \leq 10^5, 1t1001 \leq |t| \leq 100, and both ss and tt contain only the letters E S W N.

Translated by ChatGPT 5