#P5284. Maximum Chain Length from Dominated Substrings
Maximum Chain Length from Dominated Substrings
Maximum Chain Length from Dominated Substrings
Consider a string . Tiffany extracts substrings of , denoted as for . Similarly, Yazid extracts substrings from , denoted as for . Additionally, there are dominance relations. Each relation is given in the form and means that the -th string dominates the -th string.
We call a string a valid target string if there exists a segmentation: [ T = t_1 + t_2 + \cdots + t_k \quad (k \ge 0), ] where each segment exactly equals one of the strings (i.e. for some valid index) and for every pair of consecutive segments and (for ) there exists a string dominated by that is a prefix of .
Let denote the length of the substring (i.e. ). The goal is to compute the maximum possible total length (i.e. ) of a valid target string . If there exist valid chains of arbitrarily large length, output (-1).
The relation between substrings is defined with the notation:
- is the substring of between indices and , inclusive.
- is defined similarly.
- A relation means that dominates .
- The condition that is a prefix of means that the string corresponding to exactly matches the starting characters of .
Your task is to compute and output a single integer representing the maximum length of the target string as described above, or (-1) if the length can be made arbitrarily large.
inputFormat
The input is given as follows:
- A line containing the string $S$.
- 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.
- $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).
- $n_b$ lines follow, each containing two integers $lb_i$ and $rb_i$ describing the $i$-th $B$ string.
- $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