We need to solve the problem: given an essay (list of words), we can replace any word by applying a series of allowed replacements: each rule says word xi can be replaced with yi (directed). So we have a directed graph where vertices are words (case insensitive? Actually problem says case doesn't matter, so we treat words case-insensitively for the purpose of replacements and counting R's? It says "please note that in this problem the case of letters doesn't matter. For example, if the synonym dictionary says that word cat can be replaced with word DOG, then it is allowed to replace the word Cat with the word doG." So we should treat words case-insensitively for both the dictionary and the essay. However, output is based on the resulting words? But we only care about the number of R's and total length of essay; these are computed on the words we choose (the actual strings, but case doesn't matter for counting R's? The problem says "as little letters «R» (the case doesn't matter) as possible." So both uppercase and lowercase 'r' count as 'R'. So when counting the number of 'R's in a word, we count both 'r' and 'R' characters. Length of word is number of characters. So we need to decide which word (string) to end up with for each initial word, by applying directed replacements possibly many times.
We can think of the graph of words (case-insensitive). But note: words are strings; we should treat them as case-insensitive for equality and replacements. So we can map each word to a canonical form (e.g., lowercased version) for graph construction. However, the R count and length of the word are based on the actual word string we use. But if we replace using a rule, the word we get is the target string as given in the dictionary (maybe with its original case). Actually, the dictionary entries are given as words (strings). The rule says: word xi can be replaced with word yi. That means if we have a word that equals xi (case-insensitively), we can replace it with the word yi (the actual string as given, but case doesn't matter for the operation; we can replace any case variation of xi with yi? The example: dictionary says "cat can be replaced with DOG". Then you can replace "Cat" with "doG". So yes, if the original word matches xi case-insensitively, you can replace it with yi (any case of yi? Actually yi is given as a specific string, but you can produce it exactly as given? The example shows that "Cat" (capital C, lower at) can be replaced with "doG" (lower d, o, capital G). So the replacement yields the word yi exactly as it appears in the dictionary. But then the case of yi matters for subsequent replacements? Since case doesn't matter for matching, the word "doG" can be considered for further replacements based on case-insensitive comparison. So the graph's vertices should be case-insensitive canonical forms. But note: the specific string we end up with for a canonical form may have different actual strings (different cases) that are considered the same word. However, the length and R count depend on the actual string, not just the canonical form. So if multiple strings map to the same canonical word (i.e., differing only in case), they are effectively the same vertex? But we may be able to transform between them because they are considered the same? Actually, if two strings differ only in case, they are considered the same word for replacement purposes (case doesn't matter). But the transformation: if we have a word "AbC" (canonical "abc"), can we replace it with "abc" if there is no explicit rule? Not directly; but if there is a rule "abc" -> "def", we can apply it to "AbC" because it matches the source word case-insensitively. However, the resulting word is "def". So the initial case of the word might not be preserved; we just match the source case-insensitively.
Thus, the graph's vertices should be the case-insensitive canonical representations of words (maybe lowercasing all letters). But each such canonical word could correspond to many actual strings (different cases). However, the dictionary provides specific strings; we need to know for each canonical word what is the best string we can achieve that is reachable from it in the graph, where each edge goes from a canonical source to a canonical target (both lowercased). But the edge's target is a specific string (with case). The length and R count of the target depend on its exact case. However, when we later apply further replacements from that target, we consider its canonical form. So the graph is on canonical nodes, but each node has possibly multiple "representations" (strings) that can be used as the word for that node, with different lengths and R counts. Actually, if we have a canonical node w (e.g., "abc") and there are multiple ways to arrive at that node (through different strings that map to the same canonical), we might be able to choose the best representation (the one with minimal R and length) among all strings that are associated with that node and are reachable from the start. But the representation is not independent: when we follow an edge from a node, we get the exact target string as given. That target string has its own canonical node (by lowercasing). So we can think of the graph as directed edges between canonical nodes, but each edge also has a "cost" (length and R count) associated with the specific target string that you land on. Actually, you start with a specific word string (from essay) with a canonical node s. You can apply a sequence of replacements: each step, if your current word string's canonical matches a source node with an outgoing edge to some target node (canonical), you can replace it with the exact target string given. That target string becomes your new current word string (which also yields a canonical node). So essentially, from the starting canonical node s and starting actual string w0, you can reach any node reachable in the directed graph from s, and the final word string you end with is some string that belongs to the final node. However, the final string's length and R count are determined by the actual string you get at the end, not just the node. But if you can reach a node, you might have multiple possible strings for that node, because there might be different paths that yield different strings (with different cases) that all lower-case to the same canonical. Among those, you want the one with minimal (R, length) lexicographically? Actually, we want to minimize number of R's first, then total length. So for each word we need to choose a reachable string that minimizes (R, length). Since we can apply arbitrary number of replacements, it's essentially we can reach any node in the transitive closure of the directed graph from the starting node. And for each node, there might be multiple possible strings (representations) that can be obtained as the final word when we stop at that node. But we can also decide to stop at any point. So we need for each starting node s (with initial word string w0), we need to find the minimal (R, length) among all strings that are reachable from s via directed edges (including possibly zero edges, i.e., the original word). However, note that the original word string w0 is a specific string; its canonical is s. So if we don't replace, we have the option of using w0. But maybe there is another string that maps to the same canonical s (different case) that we can get? Without any replacement, we cannot change the case of the word; we can only change it via replacements. Could we get a different case of the same canonical word? Suppose there is an edge from s to t, and then from t back to s? But edges are directed. If there's a cycle, we might be able to go around and come back to s, but the resulting string would be the specific string that appears as target of the edge that ends at s. That string might be different from the original w0, and might have a different case. So indeed, we may be able to change the representation of s by going around cycles. So for each canonical node, we can potentially have many possible strings (the ones that appear as target words on edges whose target canonical is that node, or as initial word for that node). So essentially, we have a directed graph where each node corresponds to a canonical word (lowercased string). Additionally, we have a set of "base strings" for each node: the initial occurrences from the essay (multiple words may share same canonical). Also, the dictionary provides edges, each with a source canonical and target canonical, and also provides a specific string (the yi) as a "target representation". That target representation is associated with the target node, but it's a specific string we can obtain when we follow that edge.
Thus, the problem reduces to: For each node (canonical word), we need to find the best (R, length) pair achievable by any string that can be "at" that node, i.e., that can be the current word after some sequence of replacements, starting from some initial word? Actually each word in essay is separate: we need to process each essay word independently; they may start from different nodes, but the graph is the same. So for each essay word (with given actual string), we can start at its canonical node s with initial representation w0. We can then traverse edges, each time replacing the current representation with the target string of the edge we take. At the end, we can stop at any node (including s) with the current representation. We want to minimize (R, length) overall. Since we can do any number of steps, the set of achievable representations is all strings that can be reached via paths from s, where the final representation is the target string of the last edge taken, or the initial representation if we take no edge. However, if we take a path of length k (k>=1), the representation is the string of the last edge's target (the one we applied last). Intermediate representations don't matter.
Thus, for each node, we need to know the best representation among: 1) the initial representation for that node (if we start there) - but this only applies to nodes that appear as essay words, and the representation is the given word. 2) representations that can be obtained by following an edge from some node that is reachable from s. But careful: The representation we end with is the target string of the last edge taken. That target string belongs to some node (its canonical). So the final node is that target node. So essentially, for each node t, we might be able to obtain some representation (string) that is either a base representation (if we start at t and take no edge) or we get to t via an edge from some node u. The representation we get is the specific string on that edge (the yi). So the set of possible representations for node t is: all edge strings whose target canonical is t, provided the source node of that edge is reachable from s (in the directed graph). Additionally, if t is s itself, we also have the initial representation (the essay word). Also, we could also use a representation that is obtained by a path that ends at t via multiple edges, but the representation is just the string of the last edge; the previous edges only affect which nodes we pass through, not the final representation. So the key is: For each node t, we can achieve the best representation among those edge strings that are "reachable" from s via a path that ends with that edge, i.e., the source node of that edge must be reachable from s. But also, we could potentially achieve a representation that is not directly from an edge but from the initial representation of t if t is reachable? Actually, to get to t without taking an edge, we must start at t and not move. That is only possible if s == t (starting node). If s != t, we need at least one edge to change node. So the possible final nodes are all nodes that are reachable from s via at least one edge? Actually, we can also stay at s with the initial representation (if we take no edge). So for s, we have that initial representation. For any other node t, we need to take at least one edge, so we need to find a path from s to some node u, and then take an edge from u to t, where the edge's target canonical is t (i.e., the edge goes to t). So the final representation is the string on that edge (the specific yi). That suggests that we need, for each edge (u->v) with string y (the target string as given), we can use that representation for node v if u is reachable from s. Also, we could also consider longer paths: but any path ending at v will have its last edge from some node u' to v, and as long as u' is reachable from s (by any path), then that edge is usable. So the condition for using an edge (u->v) is that u is reachable from s (including u = s possibly via zero-length? Actually, we can take a path of length 0 and then apply edge (s->v) if such edge exists. That's allowed: we can replace directly. So u must be reachable from s (including s itself). So essentially, for each starting node s, we want to compute the best pair (R, length) among:
- The initial word (if we don't move).
- For each edge (u->v) such that u is reachable from s, consider the string y of that edge as a candidate for node v. But note: we then stop; we don't need to further move from v. So the candidate is the string y itself, which yields R count and length. The final node is v, but that doesn't matter further. So we can choose any edge reachable from s and stop at its target.
Thus, the problem reduces to: We have a directed graph. For each node s (starting word), we need to find the minimal (R, length) among:
- base[s] (the specific string of the essay word for that s? but essay words may have different strings even for same canonical? Actually each essay word is independent; we treat each occurrence separately. For each occurrence of a word in the essay, we have a starting string w_i, with canonical s_i. We need to compute the best achievable (R, len) for that starting word. So for each occurrence, we need to compute the min over all reachable edges' target strings, plus its own string. Since the graph is the same for all, we can precompute for each node s the best achievable pair overall? But careful: The best candidate might be from an edge that is reachable from s, but that edge gives a string y, and that string has its own canonical v. However, if we can get to v, we could then possibly apply another edge from v to get an even better string? But that would be represented by using that later edge as the last edge. So the set of candidates is all strings y that appear on any edge (including possibly multiple edges) such that the source node of that edge is reachable from s. Additionally, we can also consider the initial string of s (which might be better than any edge reachable). But also, could we use a path of length 0 to stay at s and then consider the base string of s? Yes. So essentially, the set of candidate strings is: {initial string of s} ∪ {y | ∃ edge u->v with string y, and u is reachable from s}.
Now, could there be a scenario where we get to a node v and then, without taking any edge, we have the option to use a base representation of v? But to get to v, we must have taken at least one edge, which means we have replaced the word with the target string of that edge. After that, if we stop, we use that string. If we don't stop, we could apply further replacements. But we only care about the final string. If we end at v without taking an edge from v, that means we took a path that ended at v, and we are using the representation we had when we arrived at v. However, the representation we had when we arrived at v is exactly the target string of the last edge we took. So it's not the base representation of v (unless v==s and we took no edges). So there is no way to "land" on v and then use some other representation for v (like the best representation of v from its own base or from other edges) unless you apply an edge from v to somewhere else. But if you apply another edge, the final representation becomes the target of that edge. So you cannot directly convert to the base representation of v after arriving via an edge. The base representation of v is only available if you start at v (i.e., the essay word originally was v). For a different starting node, you cannot magically switch to the base representation of v; you can only get to v via an edge, and that gives you the specific string of that edge. So the base strings are only available for the starting node of each essay word (if we don't move). Therefore, for each essay word, we need to compute the minimal over: its own string, and all edge strings y such that the source node of that edge is reachable from s.
But wait: what if there is an edge u->v and later we could go v->w, and the string for w might be better. That is included by considering edges whose source is reachable from s; if u is reachable, then v is reachable (since there's an edge u->v). So v becomes reachable. Then edges from v are also considered because their source v is reachable from s. So indeed, the set of reachable sources is the set of nodes reachable from s (including s). And for each reachable source u, we can consider all outgoing edges from u and their target strings. So the set of candidate strings is: all edge strings whose source is in the reachable set from s, plus the initial string of s. That's it.
Thus, the problem for each starting node s is: find the minimal (R, length) over a set of strings that are associated with edges whose source is in the set of nodes reachable from s (including s itself through its own string). But note that the initial string of s is a particular string; for each occurrence of s in the essay, the initial string might differ in case, so the R count and length might vary for the same canonical s. So we need to handle each occurrence individually: we have a specific initial string w_i with its own R count and length. So for each occurrence, the candidate set is: {w_i} ∪ {y | ∃ edge u->v with string y, u ∈ Reach(s)}.
Now, we need to compute efficiently for many starting nodes (up to m <= 1e5). The total number of words (unique canonical words) might be up to something like total length of words in essay and dictionary pairs (which is up to 1e5 + 5e5 = 6e5 characters). But total distinct canonical words could be up to number of words in essay plus number of words in dictionary pairs: each word (source or target) can be unique. So maybe up to ~21e5 + something (since total length of pairs is 5e5, but number of words could be up to number of distinct words, which could be as many as number of entries, about 2n + m. n up to 1e5, m up to 1e5 => up to 3e5 words. That's manageable.
We have a directed graph with up to ~3e5 nodes and edges: each dictionary rule gives one directed edge. n up to 1e5, so edges up to 1e5.
We need for each node s (potentially up to 3e5, but only those appearing as essay words need to be answered), compute the minimal (R, length) among all edge strings whose source is in the reachable set from s.
This seems like a problem of computing "best reachable" values in a directed graph. But note: the edge strings have attributes (R count and length). The candidate set for s includes all edge strings from reachable sources. So essentially, for each node s, we need to know: among all nodes reachable from s (including s), what is the minimum (R, length) over the "best outgoing edge string" from each reachable node? But careful: For a given source node u, there may be multiple outgoing edges with different target strings; we can pick any of them as candidates. So from u we have a set of candidate strings (its outgoing edges). So for each node u, we can define a value best_out[u] = minimal (R, length) among all strings on edges outgoing from u. Additionally, for the node itself (if it is a starting node for an essay word), we have its own string w_i. But that's per occurrence, not per node. So for a given starting node s, we need to compare w_i with the minimal best_out[u] for all u in Reach(s). Because from any reachable source u, we can take its best outgoing edge and achieve that string. However, note: best_out[u] might be defined only if u has outgoing edges; if not, then no candidate from u (except maybe its own base string if u == s). So the candidate set from reachable sources is exactly the set of best_out[u] for all u in Reach(s) that have outgoing edges, plus possibly the base string for s itself.
But is it sufficient to take the minimal best_out among reachable nodes? Yes, because for each u, we can choose any outgoing edge, and we can always choose the best one (lowest (R, length)). So the minimal candidate from u is best_out[u]. Then overall minimal candidate from any reachable u is min_{u in Reach(s)} best_out[u]. And then compare with the initial string w_i.
Therefore, for each starting word (occurrence), the answer is min( (R_i, len_i) , best_reachable[s] ), where best_reachable[s] = minimal best_out[u] over all u reachable from s (including s? But s's own best_out is considered if it has outgoing edges, but we also have initial string. However, note that if we take an edge from s, we get the target string of that edge, not s's own string. So best_out[s] is a candidate as well, independent of the initial string. So indeed, best_reachable[s] should include s if it has outgoing edges. But if s has no outgoing edges, then the only candidates from other reachable nodes are those reachable via some path; but if there is no outgoing edge, the reachable set from s might be just {s} if no edges from s? Actually, if s has no outgoing edges, we cannot reach any other node. So reachable set is {s}. Then best_reachable[s] is not defined because there is no u with outgoing edges? But we also have initial string w_i. So answer would be just w_i. So we need to handle nodes with no outgoing edges as no candidate from edges.
Thus, we can compute for each node u its best_out[u] = min (R(y), len(y)) over all edges from u. If u has no outgoing edges, we can set best_out[u] = (INF, INF) or ignore.
Then, for each node s, we need to compute min_{u in Reach(s)} best_out[u], where Reach(s) includes nodes reachable from s via directed edges (including s). That's essentially a graph problem: for each node, compute the minimum of a value over all nodes reachable from it. This is like finding the minimum best_out in its reachable set. Since the graph is directed, we can think in terms of strongly connected components (SCC). Within a SCC, all nodes are mutually reachable (if the graph is strongly connected). Actually, reachability in directed graphs: if we have SCCs, then within a SCC, every node can reach every other node (if the component is strongly connected). So the set of reachable nodes from a node s includes its own SCC and any SCC reachable from it in the DAG of SCCs. So we can compress the graph to DAG. Then for each SCC, we can compute the minimum best_out among nodes in that SCC, and then propagate minima forward: for a SCC, the overall best reachable from any node in that SCC is the minimum of (the SCC's own min_best_out) and the minima from all SCCs reachable from it.
That is typical: compute the condensation DAG (which is acyclic). Then process in reverse topological order (or do DP) to compute for each SCC the minimum of its own min_best_out and the minima of its successors (since from any node in SCC you can reach successors). So for each SCC, define dp[SCC] = min( min_best_out_in_SCC, min_{successor SCC} dp[successor] ). Then for each node in that SCC, the best reachable value is dp[SCC].
But careful: The candidate set includes best_out[u] for nodes in the SCC itself and all nodes in reachable SCCs. The dp approach gives exactly that.
Now, we must also consider that the initial string w_i of a starting node s might be better than any reachable best_out (including possibly from s itself). So for each essay word occurrence, we compute ans_i = min( (R(w_i), len(w_i)) , dp[comp(s)] ), but we need to compare pairs lexicographically: first minimize number of R's, then length. So we need to implement comparison.
But is it always safe to take only the best_out per node? What if a node has multiple outgoing edges, and the best_out is not actually reachable because taking that edge might lead to a node with a better outgoing edge? But we are not forced to stop after taking that edge; we could continue, but we are only considering the final string as the target of some edge. If we take an edge from u to v, we stop. If we continue, we could get an even better string from some later edge. But that later edge's string would be considered as candidate because its source w is reachable from u (since u->v->...->w), so w is reachable from s, and its best_out would be considered. However, best_out[w] is the best among edges from w. So if continuing leads to a better string, then dp would capture that because dp[u] takes min over successors' dp values, which include the best from reachable nodes. So indeed, dp[SCC] computed as min(own min_best_out, min of dp[successors]) will give the global minimum best_out among all reachable nodes. So it's correct.
But wait: what about the possibility of using the initial string of some node reachable from s (other than s)? As argued, you cannot use the base string of a node unless you started at that node and took no edges. But if you reach node v via edges, you are forced to have used an edge to get there, so you are holding the target string of that edge, not v's base string. You cannot "reset" to v's base string. So base strings are only available for the starting node. So we shouldn't include base strings of other nodes. So our approach is correct.
Thus, the problem reduces to:
-
Parse input: m, list of essay words (strings). n, then n pairs (xi, yi). We need to treat words case-insensitively for graph nodes, but store the actual strings for R count and length for: each essay word (original string), each target string yi from dictionary (since those are the strings we can obtain). Also, we need to consider that there might be multiple essay words with the same canonical form but different original strings; we need to treat each occurrence separately.
-
Build graph: nodes are canonical words (lowercase). For each dictionary rule xi -> yi:
- Let u = canonical(xi), v = canonical(yi).
- Add directed edge from u to v.
- For this edge, we need to record the string yi (the target string) for its R count and length, because that's the string we get if we take this edge. So we need to compute (r_cnt, len) for yi. Then for node u, we want to track the minimum (r_cnt, len) among all its outgoing edges' target strings. So we can maintain for each node u a pair best_out[u] that is the minimum over all its outgoing edges.
-
However, there is a nuance: Could there be multiple edges from u to v with different yi strings? Yes. We take the min among them.
-
Also, what about self-loops? Possibly. If u == v, then taking the edge replaces the word with yi (which might be different case). That's allowed. So we include it as candidate.
-
Now, after building graph, we compute SCCs and condensation DAG.
-
For each SCC, compute min_best_out_in_SCC = minimum of best_out[u] for all nodes u in that SCC that have outgoing edges (i.e., best_out[u] not INF). Actually, best_out[u] might be INF if no outgoing edges. For the SCC's own min, we can consider only those that have outgoing edges; if none have, then the SCC's own min is INF? But then the dp would rely on successors. But if no node in the SCC has outgoing edges, then from this SCC you cannot get any edge candidate unless you move to successors (if any). But you can still move to successors if there are edges from some node in SCC to other SCCs. Even if the nodes themselves have no outgoing edges, but if any node has an outgoing edge, then best_out for that node is defined. So min_best_out_in_SCC should be the min over nodes' best_out values among those with outgoing edges. If none, set to INF.
-
Then compute dp[SCC] as described: dp[SCC] = min( min_best_out_in_SCC, min_{successor SCC} dp[successor] ). Since the DAG is acyclic, we can do topological sort and compute in reverse order (post-order) or do DFS.
-
Now for each essay word occurrence with original string w_i, canonical node s = canonical(w_i). We need to compute candidate pair from edges: cand = dp[comp(s)] (if dp[comp(s)] is INF, then no edge candidate). Then answer for this occurrence is min( (R(w_i), len(w_i)), cand ). Sum up the R counts and lengths over all occurrences.
But is there any additional nuance: What about using a path of zero edges? That's covered by the original word. What about using a path that ends at a node but we don't take any edge from that node? That would require that we arrived at that node via an edge and then stop. That final word is the target of the last edge taken. So indeed it's an edge candidate. So all possibilities are covered.
But wait: Could we use a path that uses multiple edges but then the final representation is not the target string of the last edge? Actually, the process is: each replacement replaces the entire word with the target word. So after applying an edge, we have the target word. If we then apply another edge, we replace it with the new target. So the final word is always the target of the last applied edge. So yes.
Thus, the solution seems straightforward.
Now, we must verify with examples.
Example 1:
Input:
3
AbRb r Zz
4
xR abRb
aA xr
zz Z
xr y
We need to parse case-insensitively.
Essay words: "AbRb", "r", "Zz". Let's compute canonical (lowercase): "abrb", "r", "zz". Their original strings: "AbRb" (R count: count 'R' and 'r': A, b, R, b => one 'R'? Actually, 'R' is uppercase R, counts; also lowercase 'r'? The string "AbRb": characters: A, b, R, b. R count = 1 (uppercase R). Length = 4. Next word "r": R count = 1 (lowercase r), length = 1. "Zz": R count = 0, length = 2.
Now dictionary rules (4 lines):
- xR abRb : source "xR" -> target "abRb". Canonical: "xr" -> "abrb". Edge from "xr" to "abrb" with target string "abRb".
- aA xr : source "aA" -> target "xr". Canonical: "aa" -> "xr". Edge from "aa" to "xr" with target "xr".
- zz Z : source "zz" -> target "Z". Canonical: "zz" -> "z". Edge from "zz" to "z" with target "Z". (Target string "Z", length 1, R=0)
- xr y : source "xr" -> target "y". Canonical: "xr" -> "y". Edge from "xr" to "y" with target "y".
We need to compute best_out for each node:
- Node "abrb": outgoing edges? None. So best_out = INF.
- Node "r": no outgoing edges (only appears in essay, not as source). best_out = INF.
- Node "zz": has edge to "z" (target "Z"). So best_out["zz"] = (R("Z"), len("Z")) = (0,1).
- Node "xr": has two outgoing edges: to "abrb" (target "abRb": R=1? "abRb": letters a,b,R,b => R count 1, length 4) and to "y" (target "y": R=0, len=1). So best_out["xr"] = min( (1,4), (0,1) ) = (0,1).
- Node "aa": has edge to "xr" (target "xr": string "xr" has R? x is not R, r is lowercase r -> R count 1? Actually 'r' counts as R, so "xr" has 1 R (the 'r'), length 2). So best_out["aa"] = (1,2).
- Node "z": no outgoing edges (maybe? "Z" is target, but as source? Not listed). best_out = INF.
- Node "y": no outgoing edges? Not as source. INF.
Now graph edges: "aa" -> "xr", "xr" -> "abrb", "xr" -> "y", "zz" -> "z".
Now compute SCCs: likely each node is its own SCC because no cycles? Check: any cycles? "aa"->"xr"->? not back to "aa". So all separate.
Now dp for each SCC is min(own best_out, min successor dp). Since successors might have dp.
We process DAG: nodes with no outgoing edges: "abrb", "r", "z", "y" have best_out INF and no successors => dp = INF (or treat as large). "xr": successors: "abrb" and "y". dp["abrb"]=INF, dp["y"]=INF, so min successor = INF, own best_out=(0,1) => dp["xr"]=(0,1). "aa": successor "xr". dp["xr"]=(0,1). own best_out=(1,2). So min = (0,1) (since 0<1). So dp["aa"]=(0,1). "zz": successor "z". dp["z"]=INF. own best_out=(0,1) => dp["zz"]=(0,1). "r" not in graph as source? Actually "r" is a node (from essay) but has no outgoing edges and no incoming? Not used in dictionary. So dp["r"] remains INF (or we don't compute because not in condensation? But we should handle all nodes). For nodes with no outgoing edges and not source of any edge, best_out is INF and no successors, dp = INF.
Now for each essay word:
-
"AbRb" -> canonical "abrb". comp = "abrb". dp[abrb] = INF. So only candidate is original word: (R=1? Wait original "AbRb": characters A,b,R,b => R count = 1? But we need to count both 'R' and 'r'. So 1 R, length 4) Actually check: "AbRb" has one uppercase R, so R count =1. So (1,4).
But maybe we can get better? Is "abrb" reachable from itself? It has no outgoing edges, so no edge candidate. So answer for this occurrence is (1,4).
-
"r" -> canonical "r". dp["r"] = INF. Original: (1,1). So (1,1).
-
"Zz" -> canonical "zz". dp["zz"] = (0,1). Original: "Zz": R count 0, length 2 => (0,2). Compare (0,1) vs (0,2): first compare R count: both 0, then length: 1 < 2, so (0,1) is better. So answer for this occurrence is (0,1).
Total R sum = 1+1+0 = 2. Total length = 4+1+1 = 6. Matches output: 2 6. Good.
Example 2:
Input:
2
RuruRu fedya
1
ruruRU fedor
Essay words: "RuruRu" and "fedya".
Canonical: "rururu" (since case-insensitive: R u r u R u -> all lowercase? Actually "RuruRu": letters R,u,r,u,R,u -> lowercasing gives "rururu".) and "fedya" -> "fedya".
Dictionary: "ruruRU" -> "fedor". Canonical: "rururu" -> "fedor". Edge from "rururu" to "fedor" with target string "fedor".
Now best_out: node "rururu" has outgoing edge to "fedor", target "fedor". Count R in "fedor": letters f,e,d,o,r => has 'r'? Actually 'r' is lowercase r -> counts as R. So "fedor" has 1 R (the last letter r). Length 5. So best_out["rururu"] = (1,5). Node "fedor": no outgoing edges. Others: "fedya" maybe no edges.
Now graph: "rururu" -> "fedor". No other edges.
SCCs: separate.
dp["rururu"] = min( own (1,5), successors: dp["fedor"] = INF ) = (1,5).
dp["fedya"] INF? Not in graph? Actually "fedya" is a node but no outgoing edges; best_out INF; successors none; dp=INF.
dp["fedor"] INF.
Now essay words:
- "RuruRu": canonical "rururu". original word "RuruRu": count R: letters R, u, r, u, R, u => uppercase R occurs twice? Also lowercase r? Actually the string: R u r u R u. Uppercase R at positions 1 and 5, lowercase r at position 3. But 'r' counts as R too. So total R's: positions 1 (R), 3 (r), 5 (R) => 3 R's. Length 6. So original (3,6). dp["rururu"] = (1,5). Compare: (1,5) better (since 1<3). So choose (1,5). So answer (1,5).
- "fedya": canonical "fedya". original: count R's? "fedya": f,e,d,y,a => no r, so 0 R, length 5 => (0,5). dp INF, so choose (0,5). So total R = 1+0=1, total length = 5+5=10. Output example says 1 10. Yes matches.
So algorithm works.
Now we need to consider potential complications.
Edge Cases:
-
n could be 0. Then there are no edges. best_out all INF. dp all INF. For each essay word, answer is just its own (R, len). So we need to compute sum.
-
Words may be repeated in dictionary, or multiple edges from same node, we take min.
-
Graph may have cycles. Example: a -> b, b -> a. Then from a, you can reach both a and b. Suppose best_out[a] = (1,2), best_out[b] = (0,3). Then from a, reachable nodes: a and b. The best candidate is min( (1,2), (0,3) ) = (0,3). Our SCC condensation will treat a and b in same SCC. min_best_out_in_SCC = min( (1,2), (0,3) ) = (0,3). Then dp for SCC = (0,3) because no successors beyond? If there are outgoing edges from SCC, then we consider them. So correct.
-
Also, there might be self-loops, handled as edges.
-
Important: The dp we compute for each SCC is the minimum best_out among all nodes reachable from that SCC (including itself). But we also need to consider that from a node we might be able to use an edge from a node that is reachable but not necessarily its best_out? We take min over best_out of reachable nodes, which is fine because for each reachable node, you can use its best outgoing edge. However, what if the best_out for a node is not actually achievable from the starting node due to the need to reach that node? To use an edge from node u, we must be able to get to u (starting from s) and then apply that edge. That's exactly our condition: u must be reachable. So yes.
-
But is there any scenario where we cannot take the best_out edge from u because the path to u may require using that edge earlier? Actually, to get to u, we apply a sequence of replacements. The final replacement is from some node w to some node v, and we stop. That's not interfering with using an edge from u. But to get to u, we need to follow a path from s to u. That path uses edges; we can always stop at u (i.e., not take further edges) and instead take its outgoing edge? Actually, when we arrive at u, we have a word that is the target of the last edge we took. That word is some string, and its canonical is u. Now we can apply any outgoing edge from u, regardless of how we got there. So we can indeed take any outgoing edge from u. So if u is reachable, we can use any of its outgoing edges. So best_out[u] is achievable.
-
But caution: The string we have when we are at u may not be the original representation of u; it's whatever we arrived with. However, to apply an outgoing edge from u, we only need that the current word matches the source word of the edge case-insensitively. Since the current word's canonical is u, it matches any source that canonical is u. So we can apply any outgoing edge from u regardless of the exact case of the current word. So it's fine.
-
So the algorithm stands.
Now we need to think about the graph's size and processing.
Steps:
-
Read m.
-
Read the essay line: list of m words (strings). We'll store them in array essay_words as they appear (case-sensitive). For each, compute its canonical lowercased version, also compute its R count and length.
-
Read n.
-
Build mapping from canonical word string to an integer node ID. We'll assign IDs as we encounter new words from essay and from dictionary (both sources and targets). Since the total number of distinct canonical words is at most number of words in essay + 2*n (since each rule provides two words). Upper bound ~ 3e5.
-
For each rule line: read two strings xi, yi. Compute their canonical forms: u = canonical(xi), v = canonical(yi). Ensure both have node IDs. Add an edge from u to v. For this edge, we need to consider the target string yi (actual string) for its R count and length. So we compute (r, len) for yi. Then we need to update best_out[u] = min( current best_out[u], (r, len) ). Also, we may need to store the graph adjacency for SCC later. So we need to record edges in a list for building graph. Since we need to compute SCC (Kosaraju or Tarjan), we need adjacency lists for original graph and reverse for Kosaraju. Or we can use Tarjan to compute SCC in one pass. We'll have up to 1e5 edges, so it's fine.
But note: There could be multiple edges from u to v, and we only care about the min target per edge for best_out[u]. So we can just update best_out[u] as we read edges.
-
After reading all edges, we have:
- Node count N.
- For each node, we have best_out[u] as the minimal (r, len) among outgoing edges. If node has no outgoing edges, best_out[u] = (INF, INF). We'll define INF as (large, large) e.g., (1e9, 1e9).
-
Build adjacency list for directed graph: for each edge (u, v), add v to adj[u]. Also need reverse adjacency for Kosaraju if using that.
-
Compute SCCs. Use Kosaraju or Tarjan. We'll get comp_id for each node.
-
Build condensation DAG: for each edge (u, v), if comp[u] != comp[v], add an edge from comp[u] to comp[v] in DAG. We'll need to avoid duplicate edges but not necessary if we just need to propagate minima; we can just gather successors list for each comp, maybe using set or we can process in topological order and for each edge, update dp for comp[u] from dp[comp[v]] later.
-
For each SCC, compute min_best_out[comp] = min over nodes u in comp of best_out[u] (but only if best_out[u] != INF; otherwise ignore? Actually we can take min including INF, but INF will dominate. So we can just take min over all nodes, but need to handle INF. We can initialize to INF and then min with each best_out[u]).
-
Now compute dp[comp] = min_best_out[comp] initially. Then process components in topological order (reverse). For each comp in reverse topological order, for each successor comp s (i.e., edge from comp to s), dp[comp] = min(dp[comp], dp[s]).
To get topological order, we can do a DFS on DAG or simply use the order of SCC from Kosaraju (the order of finishing times gives reverse topological order for the condensation graph if we do first DFS on original graph? Actually Kosaraju's second pass processes nodes in order of decreasing finishing times from first DFS; this yields SCCs in topological order (reverse) of the condensation DAG. So we can get an order for components. But we can also compute indegree and do Kahn.
Given up to 1e5 edges, we can compute a list of component edges and then do a simple DP using the order from Kosaraju: after second pass, we have comp for each node. Then we can sort components by their order? Actually in Kosaraju, the order of finishing times (postorder) on the first DFS gives a reverse topological order of the condensation DAG. Then the second DFS processes nodes in that order and assigns components. After that, we can process components in order of decreasing finishing times of their "representative"? Instead, we can just compute the condensation graph and then do a DFS on DAG in topological order.
Simplify: use Tarjan's algorithm which returns components in reverse topological order (the order of completion is a topological order of the condensation graph). Tarjan's algorithm pushes SCCs onto a stack and assigns lowlink; when a SCC is popped, it's in reverse topological order? Actually Tarjan's algorithm can produce components in reverse topological order (i.e., if we output each SCC when it is found, they are in topological order). But I'm not 100% sure. Safer: after computing comps, build DAG, compute indegree, do Kahn's topological sort, then process nodes in that order reversed (or process in reverse topological order: for DP we want to compute dp[comp] = min( own, min(dp[successor]) ), so we need successors' dp first. So we should process components in reverse topological order. So we can get a topological order list, then iterate it backwards.
Implementation details:
-
Mapping: We'll use unordered_map<string, int> or map to assign IDs. Since total length is up to 6e5, number of distinct words up to 3e5, unordered_map is fine (C++). We'll need to store for each node its canonical string? Not needed after mapping, but we might need for debugging.
-
For each node, we store best_out as a pair (r, len). We'll define a struct or use two integers. We'll need to compare pairs: (r1, len1) < (r2, len2) if r1 < r2 or (r1 == r2 && len1 < len2). For INF, we can use (large, large), e.g., (1e9, 1e9).
-
For each essay word, we store original pair (r, len) and node id.
-
Graph adjacency: vector<vector> adj(N). For Kosaraju, we also need radj.
Given n up to 1e5, N up to 3e5, adjacency lists are okay.
Memory: adjacency list of size N with total edges 1e5, plus reverse edges. That's fine.
Now compute SCC. I'll use Kosaraju: first DFS on original graph to get order, then DFS on reversed graph to assign comp. Or Tarjan. Both are linear.
After computing comp, we get compCount.
Now, we need to compute min_best_out for each comp. We'll create vector<pair<int,int>> comp_min(Ncomp, INF). For each node u, if best_out[u] < comp_min[comp[u]] (according to our comparison), update.
Now build condensation graph: For each edge (u, v) in original graph, if comp[u] != comp[v], add edge from comp[u] to comp[v] in dag_adj. To avoid duplicates, we could use set, but duplicates not harmful for DP if we just iterate over all edges and update dp? But for DP we need adjacency list for each comp to propagate minima. With duplicates, we might do extra work but that's okay. However, we also need to compute topological order, for which we need DAG without duplicates? Not necessary; duplicates just increase indegree count but that's okay; we can just increment indegree for each edge if comp[u]!=comp[v] and then add to adjacency. However, we need to be careful about multiple edges causing multiple increments of indegree: that's fine; we just need to ensure that when we process a node, we decrement indegree for each outgoing edge, even if duplicates, but that might cause indegree to go negative if we don't track properly? Actually in Kahn, we initialize indegree for each comp as count of incoming edges. If there are duplicate edges, we'll count them multiple times. Then when we process a comp, for each neighbor we decrement indegree; if there are duplicates, we decrement multiple times, but that's fine as long as we also iterate over duplicate adjacency entries. The indegree count will become zero after we have processed as many times as there were edges. That's correct because each edge contributes to indegree. However, we must ensure we add all edges to adjacency, including duplicates, to match indegree decrements. That's fine. But we can also deduplicate to improve performance, but not necessary given 1e5 edges.
So steps:
- vector<vector> dag_adj(compCount).
- vector indeg(compCount, 0).
- For each edge (u, v):
cu = comp[u], cv = comp[v];
if cu != cv:
dag_adj[cu].push_back(cv);
indeg[cv]++;
Now topological sort: queue (or vector) of nodes with indegree 0. Get order list.
Now dp array for components: vector<pair<int,int>> dp(compCount, INF). We'll initialize dp = comp_min (the min best_out within component). Then we need to process components in reverse topological order to propagate minima from successors to predecessors.
We can do: process topological order from source to sink (i.e., increasing order). But to compute dp[cu] = min(comp_min[cu], min over dp[cv] for each successor cv), we need dp[cv] already computed. So we should process in reverse topological order (sinks first). After topological sort, we have an array topo containing comps in topological order (i.e., edges from earlier to later). Then we iterate reverse: for i = topo.size()-1 down to 0: int c = topo[i]; for each succ in dag_adj[c]: dp[c] = min(dp[c], dp[succ]). This works because when we process c, all its successors (which appear later in topological order) have already been processed (since they are after c in topological order? Actually in topological order, if there is an edge c -> succ, then c appears before succ. So when we iterate reverse, we process succ before c. So dp[succ] is already computed. Good.
Now after dp computed, for each essay word with node id u, we get comp_id = comp[u]. candidate = dp[comp_id] (may be INF). Then we compare with the original pair (r_orig, len_orig). We'll take the min. Then sum up.
That's the algorithm.
But we should double-check: The dp[comp] includes min over all nodes reachable from any node in that component, including those in the component itself. That's exactly what we need.
Now, what about the possibility that there is a node with no outgoing edges but reachable from s? Then best_out for that node is INF, so it doesn't contribute a candidate. So it's fine.
Now we need to ensure that we handle the case where there are no outgoing edges from a component but it has successors? Actually if a component has no outgoing edges to other components, it's a sink. dp[comp] will be comp_min[comp] (since no successors). That's correct.
Now verify with more complex example with cycle:
Suppose graph: a->b, b->a. Edges:
a->b with target string "bb" (R=0,len=2)
b->a with target string "aa" (R=0,len=2) but maybe different.
But also maybe a has another edge to c with target "c" (R=0,len=1) and c has no outgoing. Then from a, reachable nodes: a,b,c. best_out[a] = min(edge to b, edge to c?) Actually a has edges: to b and to c? Let's define: a->b (target "bb") and a->c (target "c"). best_out[a] = min((0,2), (0,1)) = (0,1). best_out[b] = (0,2) (edge to a). So min among reachable best_out is (0,1). Our SCC for a and b will be one component (since they are cycle). min_best_out of component = min(best_out[a], best_out[b]) = (0,1). Then dp for component = min(comp_min, dp[successor]) where successor is c (since a->c goes to different component). dp[c] would be comp_min[c] = best_out[c] maybe INF if no outgoing? Actually c might have no outgoing edges, so comp_min[c] maybe INF if c has no edges? But c may have no outgoing edges, but we need to consider if there are any edges from c? If none, then dp[c] = INF. Then dp[component] = min((0,1), INF) = (0,1). Works.
Now what about scenario where a component has no outgoing edges, but within the component some nodes have outgoing edges to nodes inside the same component? That's covered by comp_min. So correct.
Thus algorithm seems solid.
Now consider corner cases with multiple edges and same target string but different case? Since we treat target strings as given, the R count and length are computed based on the actual string. So best_out[u] is min among these based on R and length.
Now, there is another nuance: The initial word's string might itself be reachable via some edge from another node? But we can't get it unless we start at that node. For the current occurrence, we only consider its own original string and all edge strings from reachable sources. But what if the original string of some other node is better? Can we get that? Only if there is an edge that directly yields that string? For example, suppose there is an edge from u to v with target string exactly equal to the original string of v (but the original string of v might be different case). But the original string of v is not considered unless we start at v. But if we start at s, we can reach u and then take edge to v, yielding the target string, which might be different from v's base string. So it's fine.
Now, what about the possibility that the original string of the starting node s is worse than some edge string from s itself? That is covered: we take min between original and dp[comp(s)], which includes best_out[s] (since s is reachable). So we will consider edges from s.
Now, what about the possibility that the best candidate is an edge from a node that is reachable only via a path that uses that same edge? That is fine; it's still reachable.
Now we must ensure we correctly handle INF for dp. For comparing pairs, we define INF as (1e9, 1e9). When taking min with original pair (which is <= 1e5 length, R <= length), INF won't be chosen.
Now, complexity: building graph O(N + E). SCC O(N+E). DP O(compCount + edges). All within limits.
Potential pitfalls:
-
Input reading: The essay line contains m words separated by spaces. The total length of words won't exceed 1e5. We can read the whole line and split.
-
The dictionary lines: total length of all pairs won't exceed 5e5. So reading as strings is fine.
-
Case insensitivity: We'll convert to lowercase for canonical form. But careful: The R count should count both uppercase and lowercase 'R' and 'r'. So for a string, we count number of characters where char == 'R' or char == 'r'. That's simple.
-
When converting to lowercase, we need to treat all letters? Yes.
-
We must consider that words may be repeated in dictionary; we need to handle multiple edges.
-
Nodes may have no outgoing edges; best_out set to INF.
-
There might be duplicate edges from same source to same target with different target strings; we need to consider min among them.
Now, is there any scenario where the best candidate is not from a best_out of some reachable node but from a combination? No, because each candidate corresponds to exactly one edge string. So min over best_out of reachable nodes gives the best.
But wait: Could we have a candidate that is not an edge string? For example, we might start at s and apply a sequence of replacements, but stop without applying any replacement? That's the original word. So that's covered. Could we stop after applying zero replacements? Already considered.
Thus answer is correct.
Now confirm with some more tricky cases:
Case: Starting word s has no outgoing edges, but can reach a node u that has outgoing edge with target string that is exactly the same as original word of s? Not needed.
Case: There may be self-loop edge that gives a string that is better than original. Then best_out[s] will be min among its outgoing edges, possibly including that self-loop. So candidate includes that string, and min with original will pick the better.
Case: Graph with many nodes, but we must ensure we include all nodes reachable from s, even those that are not in the same SCC. Our DP does that.
Now, consider scenario where a node u has best_out[u] with a very low R but high length, while another node v has best_out[v] with slightly higher R but much lower length. The min comparison uses R first then length. So dp will choose the best according to this ordering.
Now, we need to output two integers: total minimum number of R's, and total minimum length. So we sum over all words the chosen (R, len).
Edge Cases:
- The essay words might have words that are not present in any dictionary rule, but may still be reachable to other nodes via graph? They might still have outgoing edges? They could appear as source in dictionary? Possibly, but we only have mapping from dictionary sources and targets. The essay words themselves might not be nodes in the graph if they are not in the dictionary? But we need to assign them node IDs anyway because they are starting nodes. So we must ensure all essay words have node IDs, even if they never appear in dictionary as source or target. They will have best_out INF (if they don't appear as source). They might appear only as target in dictionary? That would give them an incoming edge but not necessarily outgoing. If they appear as target only, they still are nodes (since we add when we process dictionary). So all good.
Now, we need to store best_out for all nodes, initializing to INF, then for each dictionary rule, if source node exists (or we create it), update best_out[src] = min(best_out[src], (r,len) of target string).
But note: If a node appears only as target and not as source, its best_out remains INF.
Now, what about nodes that appear as source but have no outgoing edges? Actually they will have at least the edges we add, so they will have best_out updated. So fine.
Now, we also need to handle multiple edges from the same source to different targets; we update min accordingly.
Now, complexity wise, we also need to compute SCC for all nodes, including those with no edges (isolated). Those will be separate components with no outgoing edges. For such components, min_best_out might be INF, and dp remains INF.
Now, Implementation details in C++:
- Use
unordered_map<string, int> idMap to map canonical string to node index (0-based).
- We'll also need to store for each node its canonical? Not needed.
- We'll have vectors:
vector<vector> adj; // adjacency for original graph
vector<vector> radj; for Kosaraju
- We'll have vector<pair<int,int>> best_out; // (r, len) per node, initialized to INF.
- We'll have vectors for essay: vector essay_nodes; (node id) and vector<pair<int,int>> essay_orig; (r,len) for original word.
Reading:
Read integer m.
Then read the line with m words. Since m can be up to 1e5 and total length <= 1e5, we can use getline after reading m? But careful: after reading m with cin, there might be newline. Better to read the next line using getline, but we need to handle that there may be leading/trailing spaces? Actually we can just read m words using cin in a loop because they are separated by spaces and newline, and total characters is small. That's simpler: for (int i=0; i<m; i++) { string w; cin >> w; essay_words.push_back(w); } That will work: after reading m, the next tokens are the words. So we can just read them directly.
Similarly for n, then n lines each with two strings. We'll read each pair with cin >> xi >> yi.
But note: The input lines might contain leading/trailing spaces but using cin >> is fine.
Now, for each word (essay and dictionary), we need to compute its canonical lowercased version. Write function to lower a string and also compute R count? We'll compute R count and length separately.
For canonical, we can just lower the string.
Now, we need to assign IDs:
-
For each essay word, we get its canonical string. If not in map, assign new ID. We'll also store original (r,len) for that occurrence. But careful: The same canonical word may appear multiple times in essay; each occurrence is independent, but they share the same node ID. That's fine.
-
For each dictionary rule, we have two words: xi and yi. For each, we get canonical and assign ID if not exist. Also we need to store the edge from u to v. Also update best_out[u] with the (r,len) of yi (the target string, not its canonical). Important: The target string yi is the actual string as given (case-sensitive). Its R count and length are based on