#P5284. Maximum Chain Length from Dominated Substrings

    ID: 18517 Type: Default 1000ms 256MiB

Maximum Chain Length from Dominated Substrings

Maximum Chain Length from Dominated Substrings

Consider a string SS. Tiffany extracts nan_a substrings of SS, denoted as Ai=S(lai,rai)A_i = S(la_i, ra_i) for 1ina1\le i \le n_a. Similarly, Yazid extracts nbn_b substrings from SS, denoted as Bi=S(lbi,rbi)B_i = S(lb_i, rb_i) for 1inb1 \le i \le n_b. Additionally, there are mm dominance relations. Each relation is given in the form (x,y)(x, y) and means that the xx-th AA string dominates the yy-th BB string.

We call a string TT a valid target string if there exists a segmentation: [ T = t_1 + t_2 + \cdots + t_k \quad (k \ge 0), ] where each segment tit_i exactly equals one of the AA strings (i.e. ti=Aidit_i = A_{id_i} for some valid index) and for every pair of consecutive segments tit_i and ti+1t_{i+1} (for 1i<k1 \le i < k) there exists a BB string dominated by AidiA_{id_i} that is a prefix of Aidi+1A_{id_{i+1}}.

Let Ai|A_i| denote the length of the substring AiA_i (i.e. railai+1ra_i - la_i + 1). The goal is to compute the maximum possible total length (i.e. i=1kAidi\sum_{i=1}^{k}|A_{id_i}|) of a valid target string TT. If there exist valid chains of arbitrarily large length, output (-1).

The relation between substrings is defined with the notation:

  • Ai=S(lai,rai)A_i = S(la_i, ra_i) is the substring of SS between indices laila_i and raira_i, inclusive.
  • Bi=S(lbi,rbi)B_i = S(lb_i, rb_i) is defined similarly.
  • A relation (x,y)(x, y) means that AxA_x dominates ByB_y.
  • The condition that ByB_y is a prefix of AjA_j means that the string corresponding to ByB_y exactly matches the starting characters of AjA_j.

Your task is to compute and output a single integer representing the maximum length of the target string TT as described above, or (-1) if the length can be made arbitrarily large.

inputFormat

The input is given as follows:

  1. A line containing the string $S$.
  2. A line containing three integers $n_a$, $n_b$, and $m$, denoting the number of $A$ strings, $B$ strings, and the number of dominance relations, respectively.
  3. $n_a$ lines follow, each containing two integers $la_i$ and $ra_i$ describing the $i$-th $A$ string as the substring of $S$ from index $la_i$ to $ra_i$ (1-indexed).
  4. $n_b$ lines follow, each containing two integers $lb_i$ and $rb_i$ describing the $i$-th $B$ string.
  5. $m$ lines follow, each containing two integers $x$ and $y$, representing a dominance relation where $A_x$ dominates $B_y$.

You can assume that indices are 1-indexed and that the substrings are valid segments within $S$.

outputFormat

Output a single integer: the maximum possible length of a valid target string $T$, or \(-1\) if the length can be made arbitrarily large.

sample

abcde
2 2 1
1 3
3 5
1 2
3 4
1 1
6