PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#GL0000317. Chuỗi dịch chuyển (Shifting String)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Chuỗi dịch chuyển (Shifting String)

Shifting String

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a string ss of nn lowercase English letters and a permutation p1,…,pnp_1,\ldots,p_n of the integers from 11 to nn. One operation simultaneously replaces all characters according to

si′=spi(1≤i≤n).s'_i=s_{p_i}\quad(1\le i\le n).

The new string replaces the previous one after each operation. Find the smallest positive number of operations needed to recover the original string. Such a number always exists and may require 64-bit arithmetic.

Input

Line 1 contains nn. Line 2 contains ss, a string of exactly nn lowercase Latin letters. Line 3 contains nn integers p1,…,pnp_1,\ldots,p_n, which form a permutation of 1,…,n1,\ldots,n.

Output

Print the minimum positive number of operations needed to restore the original string.

Subtasks

  • Subtask 1 (20 points): 1≤n≤101\le n\le10; ss consists of nn lowercase letters; pp is a permutation.
  • Subtask 2 (30 points): 1≤n≤801\le n\le80; ss consists of nn lowercase letters; pp is a permutation.
  • Subtask 3 (50 points): 1≤n≤2001\le n\le200; ss consists of nn lowercase letters; pp is a permutation.

Examples

Example 1

Input

5
ababa
3 4 5 2 1

Output

1

Explanation

After one operation, the characters at positions 3,4,5,2,13,4,5,2,1 again form ababa, so the minimum positive answer is 11.

Example 2

Input

5
ababa
2 1 4 5 3

Output

6

Explanation

Positions 1,21,2 have period 22 (ab), while the cycle on positions 3,4,53,4,5 has period 33 (aba). Both return simultaneously after lcm⁡(2,3)=6\operatorname{lcm}(2,3)=6 operations.