luogu#P8062. [BalkanOI 2012] handsome

[BalkanOI 2012] handsome

Background

You are the most handsome among OIers, so you have to solve a problem related to being handsome.

Problem Description

An NN-digit number is handsome if and only if every digit is one of 1,2,31,2,3. Also, the ordered pair formed by any two adjacent digits is not a “dangerous pair”.

  • An NN-digit number XX is lexicographically smaller than an NN-digit number YY under the permutation pp if and only if there exists a kk such that $X_{p_1}=Y_{p_1},X_{p_2}=Y_{p_2},\dots,X_{p_{k}}<Y_{p_{k}}$.

  • An NN-digit number XX is lexicographically equal to an NN-digit number YY under the permutation pp if and only if $X_{p_1}=Y_{p_1},X_{p_2}=Y_{p_2},\dots,X_{p_{N}}=Y_{p_{N}}$.

  • An NN-digit number XX is lexicographically greater than an NN-digit number YY under the permutation pp if and only if there exists a kk such that $X_{p_1}=Y_{p_1},X_{p_2}=Y_{p_2},\dots,X_{p_{k}}>Y_{p_{k}}$.

Please output the number of handsome numbers that are B\le B under the permutation pp, modulo 109+710^9+7.

Input Format

The first line contains an integer NN, the number of digits.

The second line contains NN space-separated integers, representing the permutation pp. The ii-th integer on this line is pip_i.

The third line contains an integer MM, the number of dangerous pairs.

The fourth line contains MM space-separated two-digit integers. The ii-th two-digit integer aibi\overline{a_ib_i} indicates that (ai,bi)(a_i,b_i) is a dangerous pair.

The fifth line contains a positive integer BB, the given handsome number.

Output Format

Output one line: the number of handsome numbers that are B\le B under the permutation pp, modulo 109+710^9+7.

3
2 1 3
2
22 13
321
9

Hint

Constraints

Subtask#0 is the sample.

1N4×1051\le N\le4\times10^5, M>0M>0, ai,bi{1,2,3}a_i,b_i\in\{1,2,3\}.

It is guaranteed that BB is a handsome number.

Sample Explanation

113,122,131,132,133,213,221,222,223,313,322113,122,131,132,133,213,221,222,223,313,322 are not handsome numbers, because the dangerous pair (2,2)(2,2) or (1,3)(1,3) appears.

So, all handsome 33-digit numbers are: $111,112,121,123, 211,212,231,232,233, 311,312,321,323,331,332,333$.

Under the permutation 2,1,32,1,3, the handsome numbers that are 321\le 321 are: 111,112,121,123,211,212,311,312,321111,112,121,123,211,212,311,312,321.

For example, compare 323323 and 321321 under the permutation 2,1,32,1,3 (let 323323 be XX and 321321 be YY):

  • First compare the 22-nd digit: X2=Y2=2X_2=Y_2=2.
  • Then compare the 11-st digit: X1=Y1=3X_1=Y_1=3.
  • Finally compare the 33-rd digit: X3=3>Y3=1X_3=3>Y_3=1.

So 323323 is greater than 321321 under the permutation 2,1,32,1,3, and it is not a valid handsome number.

Translated by ChatGPT 5