#P8277. [USACO22OPEN] Up Down Subsequence P

    ID: 9357 远端评测题 2000ms 256MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>动态规划 DPUSACO树状数组2022动态规划优化

[USACO22OPEN] Up Down Subsequence P

Problem Description

Farmer John has NN cows (2N31052 \leq N \leq 3\cdot 10^5), numbered 1N1 \ldots N, arranged into a permutation p1,p2,,pNp_1,p_2,\ldots,p_N of 1N1\ldots N. You are also given a string of length N1N-1 consisting of the letters U and D. Find the largest KN1K\le N-1 such that there exists a subsequence a0,a1,,aKa_0,a_1,\ldots,a_{K} of pp satisfying, for all 1jK1\le j\le K, if the jj-th character of the string is U then aj1<aja_{j - 1} < a_j, and if the jj-th character is D then aj1>aja_{j - 1} > a_j.

Input Format

The first line contains NN.

The second line contains p1,p2,,pNp_1,p_2,\ldots,p_N.

The last line contains the given string.

Output Format

Output the maximum possible value of KK.

5
1 5 3 4 2
UDUD
4
5
1 5 3 4 2
UUDD
3

Hint

【Sample Explanation 1】

We can choose [a0,a1,a2,a3,a4]=[p1,p2,p3,p4,p5][a_0,a_1,a_2,a_3,a_4]=[p_1,p_2,p_3,p_4,p_5]; the entire permutation matches the given string.

【Sample Explanation 2】

We can choose [a0,a1,a2,a3]=[p1,p3,p4,p5][a_0,a_1,a_2,a_3]=[p_1,p_3,p_4,p_5].

【Test Point Properties】

  • Test points 3-4 satisfy N500N\le 500.
  • Test points 5-8 satisfy N5000N\le 5000.
  • In test points 9-12, all U in the string appear before all D.
  • Test points 13-22 have no additional constraints.

Translated by ChatGPT 5