We need to understand the problem: We have a list of n abbreviated names (strings of lowercase letters). These are names of kings/relatives, ordered by time. We need to find the maximum length of a dynasty name that could have existed. A dynasty is a sequence of kings (in order of ruling) such that:
-
The first name of the heir should be the same as the last name of his predecessor. In terms of abbreviated names (the whole string): The first letter of the heir's abbreviated name equals the last letter of the predecessor's abbreviated name.
-
Additionally, for the dynasty as a whole: The first letter of the abbreviated name of the first king equals the last letter of the abbreviated name of the last king.
-
The dynasty name is formed by concatenating the abbreviated names of the kings in order.
We need to select a subsequence of the list (preserving order) that satisfies these constraints? Or is it a contiguous subsequence? The problem says: "help Vasya to find the maximally long name of the dynasty that could have existed in Berland." and "Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B." This indicates that the dynasty would be some subsequence of the list (maybe not necessarily contiguous?) Because they say "maximally long name of the dynasty" meaning concatenated length. And they note that order matters and that if A appears before B in list, then if both were kings, A ruled before B. So we can pick any subset of the names (preserving order) to form a dynasty, as long as the dynasty constraints are satisfied.
But we must consider that the list contains names of kings and relatives. So not all names are necessarily kings; we can choose a subsequence that could represent the actual kings of a dynasty. There's no restriction that we must use all names. So we want to find a sequence of indices i1 < i2 < ... < ik such that:
For each j from 1 to k-1: first letter of s_{i_{j+1}} equals last letter of s_{i_j}.
And also first letter of s_{i1} equals last letter of s_{ik}.
The dynasty name length is sum of lengths of s_{i_j}.
We need to maximize that total length.
If no such sequence (with at least 1 king) possible, print 0.
But is it allowed to have a single king? The constraints: For a single king, the condition "first name of the first king coincides with the last name of the last king" would be that first letter equals last letter of the same name. So for a single king to be a valid dynasty, we need its first letter = last letter? Actually the condition: "the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king)." For a dynasty of one king, first king = last king, so condition becomes first letter of that king equals last letter of that same king. So only kings whose abbreviated name has first letter equal to last letter can be a dynasty of length 1? Let's examine examples: Example 3: Input: 3, names: ab, c, def. Output: 1. So they consider a dynasty of length 1 with name "c"? c has first letter 'c' and last letter 'c', so condition holds. Also "ab" has a != b, so not valid alone. "def" has d != f, so not. So indeed, single king must have first=last.
But also they output 1 as dynasty name length: the concatenated length of the dynasty names is just length of "c" which is 1. So they treat a single valid king as dynasty.
Now, for sequences longer than 1, the condition between consecutive kings is about first letter of successor equals last letter of predecessor. And the circular condition: first of first = last of last. But note: If we have a sequence satisfying consecutive constraints, does the circular condition automatically hold? Not necessarily. For a sequence of length >1, we need first letter of first = last letter of last separately. But it may or may not hold. So we need to enforce both.
Thus we need to find a sequence (subsequence) maximizing total length, satisfying:
Let s_i be strings. For chosen indices i1..ik, let a_j = first character of s_{i_j}, b_j = last character of s_{i_j}.
Constraints: For j=1..k-1: a_{j+1} = b_j.
Additionally: a_1 = b_k.
Goal: maximize sum of lengths.
This is reminiscent of a longest path problem in a directed graph where nodes represent strings? But n up to 5e5, strings length up to 10. We need efficient.
Observation: The constraints only involve the first and last characters of strings. The internal characters just contribute to length. So each string can be represented as an edge from its first character to its last character, with a weight equal to its length. Additionally, for a single string (k=1), we need first=last (so a loop on that character) and it's allowed.
For a sequence of strings, we need a path: start at some character (the first character of first string), then each edge goes from its first to its last, and we require that the first character of the next string equals the last character of the previous. So essentially, if we consider the concatenated string of the dynasty, it is formed by string1 + string2 + ... + stringk. The condition between strings ensures that the concatenation is smooth? Actually the condition is that the last letter of previous equals first letter of next, but that does not guarantee anything about the internal letters. So the concatenated string may have overlapping letters? No, because we just concatenate the full strings; the condition doesn't create overlap; it's just a constraint on letters at the junction. So if we treat each string as an edge from its first to last character, then a sequence of such edges forms a walk in a directed graph on 26 letters (lowercase). The walk is: start at a1, take edge1 -> b1, but the next edge must start at a2 = b1, so it's like walking: a1 -> (edge1) -> b1 (which is also a2) -> (edge2) -> b2, etc. So indeed the sequence corresponds to a walk in a directed multigraph where vertices are letters a-z. The walk's vertices: start = a1, after first edge we are at b1; second edge start at that vertex, etc. So the walk's vertex sequence is: v0 = a1, v1 = b1 (= a2), v2 = b2, ..., vk = b_k. The constraints additionally require a1 = b_k, i.e., v0 = v_k. So the walk must be a closed walk (cycle) that starts and ends at the same vertex. But note: It could be a single edge that loops: if a1 = b1, then v0 = a1, v1 = b1 = a1, so closed. So essentially we are looking for a closed walk (possibly with repeated vertices/edges) using the given strings (in order of time) such that the edges are taken in increasing order of their original indices (since we must choose a subsequence of the list). So the edges have a fixed order (time), and we need to pick a subsequence forming a closed walk. The total weight (sum of lengths) to maximize.
So we have a sequence of edges (directed, from first char to last char) with weights (length). We need to find a subsequence (preserving order) that forms a closed walk (i.e., start vertex = end vertex) and maximize sum of weights.
We can think of DP. Let n up to 5e5, alphabet size 26.
This looks like a variation of longest path in a DAG? But the graph is not a DAG necessarily, but the order is linear by time. We can only go forward in time. So we can model DP states: For each vertex (letter) v, we want the maximum total weight of a valid walk (subsequence) that ends at vertex v (i.e., the last edge ends at v). But we also need to ensure that eventually we close the loop, but we can incorporate closure by considering that we want a closed walk, which is a walk that starts and ends at same vertex. Equivalent to a sequence where the start vertex equals the end vertex. So we could treat it as: find maximum over v of (the best walk that starts at v and ends at v). However, because the start vertex is determined by the first edge's first character, we might need to keep track of the start vertex as well.
But maybe we can consider DP that builds partial walks, and then when we see an edge that can close the walk (i.e., its last character equals the start vertex of the walk), we can complete. But the start vertex is not fixed beforehand; it's determined by the first edge chosen. So one approach: treat it as a longest path in a graph where we have two types of states: (current vertex, start vertex) perhaps. But that would be 26*26 = 676 states, which is manageable. However, we need to process n edges sequentially, updating DP values.
We want to maximize total length. Let’s define dp[v] as the maximum total length of a walk (subsequence) that ends at vertex v, but without any constraint on start? That would be the classic longest path in a sequence of edges: we can take edges in order, and when we see an edge from f to l with weight w, we can extend any walk that ends at f to now end at l, with total length dp_start[f] + w. Also we can start a new walk with this edge alone (if we consider single edge as a walk that starts at f and ends at l). However, for a single edge to be valid as a closed walk, we need f == l; but in the DP for open walks, we don't enforce that. Later we can close.
But our final dynasty must be a closed walk. How to incorporate? Perhaps we can treat it as: we want a walk that starts and ends at the same vertex. That is equivalent to an open walk that ends at some vertex v, and we have recorded that it started at some vertex s, and we need s=v at the end. So we need to keep track of the start vertex for each partial walk. However, we can compress: The total walk length is sum of edges. For any walk, the start vertex is determined by the first edge's first character. So if we maintain DP[s][v] = maximum total length of a walk that starts at s and ends at v (using a subsequence of processed edges). Then when we process an edge (f -> l, w), we can update:
-
Start a new walk consisting of only this edge: then start = f, end = l. So DP[f][l] = max(DP[f][l], w). However, for a single edge to be considered a closed walk only if f == l; but DP[f][l] with f != l is an open walk that could later be closed by adding more edges to bring back to f. So it's okay.
-
Extend an existing walk that ends at f to now end at l: For any start s, we have DP[s][f] (some value), then we can extend to DP[s][l] = max(DP[s][l], DP[s][f] + w). Note that the walk must respect order; since we process edges in order, when we extend, we are using the new edge after the previous ones, so it's fine.
But n up to 5e5, and we have 26*26 = 676 states. That seems very manageable. We can update DP for each edge in O(26) time (since for each edge, to extend we need to consider all s such that DP[s][f] is defined). Actually, for each edge (f->l,w), we need to:
-
For all start s (26 possibilities), we can try to extend from DP[s][f] to DP[s][l] using this edge.
-
Also, we can start a new walk with this edge: DP[f][l] = max(DP[f][l], w).
-
Additionally, we might consider using the edge to extend walks that end at f and also maybe update DP[f][something]? Already covered.
Complexity: For each edge, we loop over s=0..25 (26) to check DP[s][f] and update DP[s][l]. That's 26 per edge, total 5e5 * 26 = 13e6, which is fine.
But is there any issue with using the same edge multiple times? No, each edge can be used at most once because we are picking a subsequence, so we process each edge in order and we have the option to either take it or not. Our DP updates consider taking the edge as the next edge in a walk. Since we are scanning sequentially, we should be careful not to use the same edge to extend a walk that already includes this edge? We process one edge at a time and update DP based on existing DP states that were built from earlier edges. So we are effectively considering including the current edge in the walk. However, we must also consider that we might start a new walk with this edge, and then later extend it using later edges. That's captured.
But what about the case where we have multiple walks with same start and end? DP stores the maximum total length for each (s,v). Since we process edges in order, we are effectively building walks in order; the DP values represent the best (max length) walk that ends at v with start s using some subsequence of processed edges. That's correct.
Finally, the answer is max over v of DP[v][v] (i.e., closed walks) at the end (since start = end). Also we need to consider that a dynasty can be empty? No, must have at least one king; but DP[v][v] for a self-loop edge (f=l) might be w; also a longer closed walk could have DP[v][v] from extensions. So answer = max_{v} DP[v][v]. If none > 0? Could be 0 if no valid dynasty. But note: if there is no valid dynasty, we output 0. DP[v][v] might be 0 if not initialized. But maybe a walk of length 0? Not allowed. So we initialize DP with -inf (or 0 as sentinel but careful). However, we need to ensure that DP[s][v] represents a valid walk; we can initialize all to -inf, then after processing edges, DP[v][v] might be negative if not reachable. But since lengths are positive (string length >=1), DP values for reachable states are at least 1. So we can take max over DP[v][v] and if none positive, output 0.
But is the DP update order correct? For each edge, we need to compute new DP values based on previous DP before including this edge. If we update in-place, we might use the same edge multiple times in a chain within the same iteration? For example, consider we have DP[s][f] that we just updated from this same edge (by starting a new walk) and then we extend it to DP[s][l] using the same edge? That would be using the edge twice, which is not allowed. So we must ensure that when processing an edge, we use DP values from before considering this edge to compute extensions. So we need to compute the updates based on old DP, then apply them. Also starting a new walk is independent. So we can compute temporary array.
Simplest: For each edge (f,l,w), we:
-
For each s, compute candidate = old_DP[s][f] + w if old_DP[s][f] > -inf. Then new_DP[s][l] = max(old_DP[s][l], candidate).
-
Also, new_DP[f][l] = max(old_DP[f][l], w).
But we must be careful: old_DP[s][f] might have been updated earlier in this iteration if we had considered another s? No, because we are iterating over all s, we need to refer to the same old DP for all. So we can do:
Initialize DP as 26x26 array with -inf (or 0? Not good because we need to differentiate unreachable from zero length? But lengths are positive, so 0 could be used as "no walk"? But then we could incorrectly treat zero as a valid walk and extend from it. Actually, if we initialize DP[s][v]=0 for s==v? That would represent an empty walk of length 0 that starts and ends at s? However, an empty walk (no kings) is not allowed as a dynasty, but could we start from an empty walk and then add edges? In terms of subsequence, we can always start a new walk with the first edge; we don't need an empty walk. But if we allow DP[s][s]=0, we could then extend from that using an edge from s to l: DP[s][l] = 0 + w. That would represent a walk that starts at s and ends at l, with first edge having first character s (so indeed that's valid). But we must be careful: If we allow empty walks, then DP[s][s]=0 for all s, we can start any walk from s by taking an edge whose first character = s. That's convenient. However, does that correspond to a valid dynasty? The dynasty would be just that edge, but we need the start vertex to equal the end vertex only at the end; but we can start from empty and then add edges, but the empty walk doesn't count towards the total. That seems fine, as long as we eventually close. However, the empty walk itself is not a valid dynasty, but it serves as a starting point. But we need to ensure that we don't consider a closed walk that is just empty (length 0) as a dynasty. So final answer will be max over DP[v][v] but we should exclude the empty ones (i.e., those that came from DP[v][v]=0). Since lengths are positive, DP[v][v] from a non-empty closed walk will be >=1. So we can treat DP[v][v]=0 as not valid and output 0 if all DP[v][v] <= 0.
But initializing DP[s][s]=0 for all s is plausible: it means we can start a walk at any vertex without having taken any edge. Then when we take an edge from f to l, we can extend from DP[f][f] = 0 to DP[f][l] = w. That's a clean way to handle starting a new walk. Also, we don't need the separate start-new-walk update DP[f][l] = max(DP[f][l], w) because that is covered by extending from DP[f][f]=0, provided we allow extending from DP[f][f] (which is 0). However, we must be careful: The empty walk DP[f][f] = 0 means we can "start" at f. But then using the edge (f->l) we get a walk that starts at f and ends at l. That's correct. But we must ensure that the edge itself is considered; we don't need a separate start update. However, we need to make sure that we only extend from walks that have at least one edge? Actually, extending from DP[f][f] = 0 is valid: the resulting walk consists solely of this edge, starting at f and ending at l. So that's fine.
But what about a single edge that is a self-loop (f=l)? Then extending from DP[f][f]=0 gives DP[f][f] = max( existing DP[f][f], 0 + w ) = w. So that gives a closed walk of length w. That's correct. So we can unify.
Thus, we can initialize DP[s][v] = -inf for all, but set DP[s][s] = 0 for all s. Then process each edge (f,l,w). For each start s, we can do: if DP[s][f] is not -inf, then DP[s][l] = max(DP[s][l], DP[s][f] + w). Since we process sequentially, we must use the DP values from before this edge to compute new updates. However, note that we might also want to consider using the edge to start a walk that begins at f; that is covered by s=f because DP[f][f] = 0, so DP[f][l] gets updated.
But careful: When we process an edge, we should not allow using the same edge multiple times in a chain within the same iteration. However, by using old DP values, we are safe as long as we do not update DP in-place during the iteration for the same edge. For each edge, we need to compute all possible extensions based on the DP before processing this edge, and then apply all updates (including possibly updating DP[f][l] from DP[f][f] etc). Since we have DP[s][f] values that might be updated by this same edge earlier? Not if we use old snapshot. So we need to either:
- Keep a copy of DP before processing the edge, and then for each s compute candidate from that copy, and then update the actual DP with the max. Or we can process updates in a way that doesn't interfere: The updates only affect DP[s][l] for various s. Since we are reading DP[s][f] for all s, and f is fixed for this edge, and we are writing to DP[s][l]. There's no overlap because the read indices (s,f) are different from write indices (s,l) unless f == l. If f == l (self-loop), then the write indices DP[s][f] would be updated from reading DP[s][f] (since l = f). That could cause using the same edge multiple times if we update in-place: after updating DP[s][f] for some s, later for another s (or same) we might read the new DP[s][f] and use it again for extension, effectively using the same edge twice. That is not allowed. So we must avoid that. So we need to use old DP values before any updates from this edge.
Thus, for each edge, we should compute an array of updates based on the current DP (prior to this edge). The simplest: For each s, compute candidate = DP[s][f] + w (if DP[s][f] > -inf). Then after computing all candidates, we apply: for each s, if candidate > DP[s][l], set DP[s][l] = candidate. This is okay because we are updating DP[s][l] based on old DP[s][f]. Even if l == f, we are updating DP[s][f] based on old DP[s][f], but that is okay as long as we don't use the updated value within the same edge. Since we compute all candidates before any update, it's fine. However, if we do it in-place sequentially over s, and l == f, then after we update DP[s][f] for s=0, then when we process s=1, we would read DP[1][f] which is still old because we haven't updated DP[1][f] yet? Actually DP[1][f] is separate from DP[0][f]; they are different rows. So updating DP[0][f] doesn't affect DP[1][f]. So we could loop over s and update DP[s][l] immediately as long as we only read DP[s][f] and write DP[s][l]. Since we are not reading DP[s'][f] for other s', it's okay. But if l == f, for each s we are reading DP[s][f] (old) and then writing DP[s][f] (new). This is safe because we are not reading other s's DP[s][f] after writing it for the same s? Actually, the reading and writing for a given s are independent of other s. The potential issue is if we would later read DP[s][f] again for the same s within the same edge (e.g., if we had a nested loop that might use updated DP[s][f] for another extension). But we don't. So it's safe to update in place for each s individually. However, to avoid subtle bugs, we can just compute a temporary array of updates for each s and then apply after, but that's O(26) extra space which is trivial.
Thus, algorithm:
Initialize DP[26][26] with -inf (or a large negative). For each c from 0 to 25: DP[c][c] = 0.
For each string s in input order:
let f = first char index, l = last char index, w = len(s).
For each start c in 0..25:
if DP[c][f] != -inf:
new_val = DP[c][f] + w
if new_val > DP[c][l]:
DP[c][l] = new_val
After processing all strings, answer = max_{c} DP[c][c] (over all c). If answer <= 0 (or == 0?), then output 0 else output answer.
But is this correct? Let's test on examples.
Example1:
3
abc: f='a', l='c', w=3
ca: f='c', l='a', w=2
cba: f='c', l='a'? Actually cba: first 'c', last 'a', w=3
Let's simulate:
DP initialized: DP[i][i]=0.
Edge1: abc (a->c,3)
For each start c (I'll use s as start):
- s='a': DP['a']['a']=0 => DP['a']['c'] = max(-inf, 0+3)=3.
- s='b': DP['b']['a']? -inf -> skip.
- s='c': DP['c']['a']? -inf.
- etc.
So after, DP['a']['c']=3.
Edge2: ca (c->a,2)
For each start s:
- s='a': DP['a']['c']=3 => new = 3+2=5 -> DP['a']['a']=max(0,5)=5 (since DP['a']['a'] was 0). Now DP['a']['a']=5.
- s='b': no.
- s='c': DP['c']['c']=0 => new = 0+2=2 -> DP['c']['a']=2.
- other s: no.
Also other s like 'a'? already did.
Now DP['a']['a']=5 gives a closed walk from a to a: path a->c (abc) then c->a (ca). Length=5? But example says dynasty "abcca" length? Let's compute: abc + ca = abc ca = "abcca" which is length 5? abc length3, ca length2 => total5. But example says "abcca" length? Actually the string "abcca" has length 5? Let's count: a b c c a = 5. Yes. But example output is 6. They said "abcca" (first and second kings) gives length 5? Wait: they said "abcca" (with first and second kings) and "abccba" (with first and third kings). Let's recalc: first king "abc" (len3), second king "ca" (len2) => concatenated "abcca" len5. Third king "cba" (len3). First + third: "abc"+"cba" = "abccba" len6. So maximum is 6. Our DP after edge2 gave DP['a']['a']=5. Then edge3: cba (c->a,3). Process:
Edge3: f='c', l='a', w=3.
For each start s:
- s='a': DP['a']['c']? what is DP['a']['c'] after edge2? It remained 3 (we didn't update it). So DP['a']['c']=3 => new = 3+3=6 -> DP['a']['a'] = max(5,6) =6.
- s='b': none.
- s='c': DP['c']['c']=0 => new = 0+3=3 -> DP['c']['a'] = max(2,3)=3.
- s='a' also DP['a']['c'] used.
Now DP['a']['a']=6. So answer = max DP[c][c] = max( DP['a']['a']=6, DP['b']['b']=0, etc ) =6. Good.
Example2:
4
vvp: f='v', l='p', w=3
vvp: same
dam: f='d', l='m', w=3
vvp: same
Let's simulate quickly:
Initialize.
After first vvp: DP['v']['p']=3.
Second vvp: Process: f='v', l='p', w=3.
For each s:
- s='v': DP['v']['v']=0 => new = 3 -> DP['v']['p'] = max(3,3)=3 (unchanged).
- other s? s='p'? DP['p']['v']? -inf.
- s='v'? already did.
Also DP from other starts? If some other start had DP[s]['v']? Not yet.
So DP['v']['p'] stays 3.
Third: dam (d->m,3)
- s='d': DP['d']['d']=0 => DP['d']['m']=3.
- s='v': DP['v']['d']? -inf.
- other.
Fourth: vvp again.
Process: f='v', l='p', w=3.
- s='v': DP['v']['v']=0 => DP['v']['p'] = max(3,3)=3.
- s='d': DP['d']['v']? -inf.
- s='p': DP['p']['v']? -inf.
- s='v'? done.
- Also s='a'? etc.
No closed loops. DP[c][c] remains 0 for all c (except maybe some self-loop? none). So answer 0. Works.
Example3:
3
ab: f='a', l='b', w=2
c: f='c', l='c', w=1
def: f='d', l='f', w=3
Process:
Edge1: ab (a->b,2)
- s='a': DP['a']['b']=2.
Edge2: c (c->c,1)
- s='c': DP['c']['c'] = max(0,0+1)=1.
Edge3: def (d->f,3)
- s='d': DP['d']['f']=3.
After processing, DP['c']['c']=1, others 0. answer=1. Works.
Thus, DP works.
Now consider some edge cases.
What about sequences that use more than two edges? The DP extends any walk that ends at f to l. Since we maintain for each start s and current end v, we can chain arbitrarily many edges. And we only require order: edges must be taken in increasing order; our DP processes edges sequentially, and updates only from previous DP states (which represent subsequences using earlier edges). So it respects order.
Thus the solution seems straightforward.
But we should double-check correctness: Is it allowed for a dynasty to start from any vertex? Yes, the first king's first letter determines start. We initialize DP[s][s]=0 to represent an empty walk starting at s. This ensures we can start with any edge whose first letter = s. That's correct because we can choose any first king from the list. There is no constraint that the dynasty must start at a particular vertex. So DP works.
Now, is there any nuance about using multiple edges that share the same start? For instance, we might have two walks with same start s but different end v; we keep only max length. That's fine because we aim for maximum total length. Since we only care about maximum, and all weights are positive, keeping only the maximum for each (s,v) is safe for future extensions because if we have two walks with same start s and same current end v, the longer one will always be at least as good for any future extensions (since we add positive weight). So DP keeping max is fine.
Complexity: O(n * 26). n up to 5e5 => about 13 million operations, well within limits.
Now, we must be careful about integer overflow? Length sum: each string length <=10, n up to 5e5, so maximum possible total length is 5e6. That fits in 32-bit int. Use 64-bit for safety.
Implementation details:
- Use 0-index for letters: ord(ch)-'a'.
- DP: 26x26 array of long long, initialized to -INF (e.g., -1e18 or something). Set DP[i][i] = 0.
Processing each string:
read str
f = str[0] - 'a'
l = str.back() - 'a'
w = str.length()
For c in range(26):
if DP[c][f] > -INF:
new_val = DP[c][f] + w
if new_val > DP[c][l]:
DP[c][l] = new_val
But note: DP[c][f] might have been updated earlier in this iteration? Since we loop over c, and we are updating DP[c][l] inside the same loop, but reading DP[c][f] which is not being updated for the same c in this loop (unless l == f and we update DP[c][f] later in the same c? Actually if l == f, then for that c we read DP[c][f], compute new_val, and then we set DP[c][l] (which is DP[c][f]) to new_val. That means we are overwriting DP[c][f] for that same c within the same iteration. Is that safe? Let's consider: For a given edge (f->f), we are reading DP[c][f] and then updating DP[c][f] to a possibly larger value. But we are using the old value to compute the new value; that's fine because we are not reading the updated value in the same iteration for the same c. However, what about subsequent c'? For other starts c' (c' != c), DP[c'][f] is not affected by the update for c. So it's fine. But what if for the same c, we might later, in the same loop, read DP[c][f] again? No, because the loop processes each c only once. So it's safe.
But there is a subtlety: When we update DP[c][l] to a higher value, we might then later, for the same edge, use that updated DP[c][l] to extend further? Not because the only extension we consider for this edge is from f to l. We only use DP[c][f] as the source. So DP[c][l] is not used as source in this edge because the edge's start is f, not l. So updating DP[c][l] does not affect the source side of this edge. So it's safe.
Thus, we can update in-place in the same loop.
But caution: What about the case where f==l and we update DP[c][f] inside the loop; then for another start c' where DP[c'][f] is read later, we must ensure we read the old value, not the updated one. Since we read DP[c'][f] separately, and DP[c'][f] hasn't been updated yet if c' != c. So that's fine. But what if we have two starts c1 and c2, and we update DP[c1][f] (since f==l) before reading DP[c2][f]. That would cause DP[c2][f] to still be the old value because DP[c2][f] is a different cell; updating DP[c1][f] doesn't affect DP[c2][f]. So that's fine. So in-place update is safe.
One more nuance: When we process an edge, we might also want to consider the possibility of not taking the edge. But that is automatically handled because we only update if we take it; DP values from not taking remain as they were.
Thus the algorithm is correct.
Now, is there any case where we might need to consider using an edge to start a new walk even though DP[f][f] is 0? Yes, we already handle via DP[f][f] = 0. So we don't need separate start.
Thus answer = max(DP[i][i]) over i, but we must ensure that DP[i][i] > 0? Actually DP[i][i] can be 0 from initialization, which corresponds to empty walk. So we need to output 0 if all DP[i][i] <= 0 (i.e., no positive closed walk). But maybe there is a closed walk with total length 0? Not possible, as each edge adds positive length.
Edge Cases:
-
All strings have length >=1. So positive.
-
If we have a self-loop string (first==last) but also longer paths, DP will capture them.
-
What about using multiple edges that eventually return to start? DP tracks start and current end, so DP[s][v] holds best sum for start s and end v. When we process an edge from v to u, we update DP[s][u] from DP[s][v]. This is akin to shortest path but with max. It works because the graph is acyclic? Not necessarily, but the order of processing edges ensures we don't create cycles that violate the time order? Actually we can have cycles in the sense of returning to same vertex later, but we process edges in order, so any walk is in increasing order of edge indices. Our DP does not enforce that we don't revisit vertices? It's allowed. So it's fine.
-
Could there be a scenario where using a certain edge earlier might lead to a better DP[s][v] that then later leads to better DP[s][v']? Since we process sequentially, we are effectively considering all possible subsequences. The DP state DP[s][v] after processing some prefix of edges stores the maximum total length of a walk (subsequence) from the processed edges that starts at s and ends at v. This is correct because the DP transition is: when we encounter a new edge (f,l,w), we can either ignore it or take it to extend any walk that ends at f (and start s) to now end at l. This is classic DP for longest path in a sequence of edges with constraints on start and end, which is exactly what we need.
-
However, one nuance: The order of updates within the same edge: we update DP[s][l] based on DP[s][f] from the same prefix. Since we update multiple s, it's fine.
But wait: Is it correct to only store the maximum length for each (s,v)? Suppose we have two walks with same start s and end v but with different lengths. The longer one is always better for future extensions because all weights are positive. However, there is a twist: What if later we need to consider a walk that ends at v but the path length might affect the ability to combine with some other constraints? No, because the only thing that matters for future extensions is that we have a walk ending at v and we know its start s. The future extensions only depend on the length (we are maximizing total length). So the longer one dominates. So DP storing max is safe.
Now, we have 26*26 = 676 states. That's trivial.
But we need to double-check that the problem constraints: n up to 5e5, each string length up to 10, so reading input is okay.
Potential pitfalls: Input might have strings of length 1? Then first=last. Works.
Now, confirm that the dynasty must be non-empty. So answer 0 if none.
Now, test more scenarios:
Case: n=1, string "ab". f='a', l='b'. DP after: DP['a']['b']=2. DP['a']['a']=0, DP['b']['b']=0. max DP[i][i]=0 -> answer 0. Because a single king must have first=last to be valid. So output 0. That's correct.
Case: n=1, string "aa". f='a', l='a', w=2. DP after: process edge (a->a). For s='a': DP['a']['a'] = max(0, 0+2)=2. So answer=2. That's correct.
Case: n=2, "ab", "ba". f1='a',l1='b', w1=2; f2='b',l2='a', w2=2.
Process first: DP['a']['b']=2.
Second: for s='a': DP['a']['b']=2 -> new = 2+2=4 -> DP['a']['a']=4; also s='b': DP['b']['b']=0 -> DP['b']['a']=2. Answer max DP[i][i] = 4. That corresponds to dynasty "abba" length 4.
Now, consider if there are multiple ways to get from s to v; DP keeps max.
Now, consider a scenario where we might want to skip an edge even if it improves DP[s][l] for some s, but later we might need a smaller DP[s][l] to allow something else? Since we are maximizing total length, a larger DP[s][l] is always better or equal for any future extension. Because future extensions add positive lengths, so a larger base yields larger total. So no need to keep smaller values.
Thus DP works.
Now, the answer is simply the maximum closed walk length.
But wait: Are there any constraints about the dynasty being a contiguous sequence? The problem says: "the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor)." This implies a direct succession, so the kings in the dynasty are consecutive in time (no gaps). But does the dynasty have to consist of consecutive kings? The phrase "the first name of the heir should be the same as the last name his predecessor" refers to the actual succession. The list contains all kings and relatives in chronological order. A dynasty is a sequence of kings (rulers). They must be consecutive in the sense that there cannot be any other king between them? In a dynasty, the kings succeed each other directly; there is no gap where someone else rules. However, the list includes relatives (non-rulers). So the dynasty sequence would be a subsequence of the list where the selected names correspond to the actual kings. But could there be other names (relatives) between them? The list contains all kings and relatives in chronological order. If there is a relative between two kings, that does not interrupt the dynasty because the relative is not a king. So the dynasty's kings need not be contiguous in the list; they can have other names (relatives) in between, as long as the kings themselves appear in the correct order. Thus, we can pick any subsequence of the list to be the kings of a dynasty, as long as the constraints hold. So our subsequence approach is correct.
Now, are there any additional constraints like the dynasty must be maximal? No, we are to find the maximum possible concatenated length.
Thus DP is valid.
But could there be a case where a dynasty uses a king more than once? The list contains distinct entries, but we cannot reuse a name because each king appears only once in history. So each name can be used at most once; our subsequence uses each at most once and in order. So DP respects that.
Now, is there any need to consider that the dynasty might be empty? No.
Thus the solution is straightforward.
Now we should consider memory: DP 26x26 = 676 entries; we can use long long.
Implementation:
- Read n.
- Initialize dp[26][26] to -inf (e.g., -1e18). For i in 0..25: dp[i][i] = 0.
- Loop i from 0 to n-1:
read s (maybe use string, but careful about large input, use fast IO).
if s empty? not possible.
f = s[0] - 'a';
l = s.back() - 'a';
len = s.length();
for c in 0..25:
if dp[c][f] != -inf:
val = dp[c][f] + len;
if val > dp[c][l]:
dp[c][l] = val;
- After loop, ans = max(dp[i][i] for i in 0..25). If ans <= 0: print 0 else print ans.
But wait: What about the case where there is a dynasty with multiple kings but the first and last condition is automatically satisfied because of the path? For a walk where start s and end v, we need s=v for closed. Our DP tracks start s, so DP[s][s] gives maximum length of closed walk that starts and ends at s. So that's fine.
Now, what about the possibility that a dynasty could consist of a single king with first != last? That would not satisfy the circular condition, so it's invalid. Our DP won't count it because DP[s][s] for that edge would not be updated unless first=last (self-loop). For a non-self-loop edge, we can have DP[f][l] but not DP[f][f] or DP[l][l] unless later closed. So that matches.
Thus solution seems correct.
But before finalizing, think about whether we might need to handle the fact that a dynasty could be formed by selecting a subset of names that is not necessarily increasing? The problem says the list is ordered by time, so we must preserve order. Our DP processes in order and only extends from previous states, so it respects the order.
Now, think about time complexity: For each string, we iterate over 26 starts. That's 5e5*26=13 million, fine.
Potential optimization: Since each string length <=10, we can read quickly.
Now, think about negative values: We initialize dp with -inf. Use something like -1e18. We can also use -1e15.
Now, but there is a catch: If we initialize dp[i][i] = 0, then for a start s, we can extend from dp[s][s] (0) to any edge starting with s. However, this implies we can start a walk from s without any previous edge. That's fine. But what about the possibility of starting a walk from a vertex that never appears as first character of any edge? That's okay, it just won't produce any walk.
Now, what about the scenario where there is a walk that uses no edges? Not allowed. So dp[i][i] = 0 is just a sentinel; we must not count it as a valid dynasty. So final answer we take max of dp[i][i] but ignore the 0 sentinel. So if the best closed walk has length 0 (i.e., only sentinel), answer 0. Since lengths are positive, any valid closed walk yields >0.
Now, is there any possibility that dp[i][i] could be updated to 0 from some edge? For a self-loop edge with length w, we get dp[i][i] = max(0, 0+w) = w >0. So 0 only appears from initialization. So it's safe.
Thus answer computed as described.
But we need to double-check the DP transition for edges that are self-loops. In the loop, for each start c, if dp[c][f] is not -inf, we compute dp[c][l] = max(dp[c][l], dp[c][f] + w). For self-loop f=l, this updates dp[c][f] using dp[c][f] from before. That is correct: it means we can add the self-loop to the walk, increasing length. This can be done multiple times if multiple self-loops occur. That's fine.
Now, does the DP correctly handle multiple edges that lead to the same (s,v) but with different lengths? We keep max.
Now, think about potential overflow: sum length up to 5e6, safe.
Now, test with more complex scenario: Suppose we have edges: a->b (len10), b->c (len1), c->a (len1). In order: a->b, b->c, c->a. The best closed walk from a is take all three: length 12. DP should compute.
Initialize dp[i][i]=0.
Edge1: a->b,10: updates dp[a][b]=10, also others? For start b? dp[b][a]? No.
Edge2: b->c,1: For each c (start):
- start a: dp[a][b]=10 => new 11 -> dp[a][c]=11.
- start b: dp[b][b]=0 => new 1 -> dp[b][c]=1.
- start c: dp[c][b]? -inf.
Edge3: c->a,1: For each start:
- start a: dp[a][c]=11 => new 12 -> dp[a][a]=12.
- start b: dp[b][c]=1 => new 2 -> dp[b][a]=2.
- start c: dp[c][c]=0 => new 1 -> dp[c][a]=1.
Also start a? done.
Answer dp[a][a]=12. Works.
Now, consider a case where there are multiple starts; the DP will keep best.
Now, consider case where there is a better closed walk that does not start at the same start as the first edge? Actually, the start is determined by the first edge's first character. So DP tracks that.
Now, is there any scenario where the DP might double count edges? It shouldn't.
Now, is there any scenario where the DP might produce a closed walk that is not actually possible because the order of edges violates the time constraint when considering the start being something else? Since DP always builds in order, it's fine.
Now, one more nuance: The condition "the first name of the heir should be the same as the last name his predecessor" implies that the first letter of the next king equals the last letter of the previous king. This is exactly the transition condition we used. However, is there any requirement about the last name of the heir? No.
Now, about the dynasty name: It is the concatenation of the abbreviated names in order. That's the sum of lengths.
Now, the problem might also allow a dynasty of zero kings? No, that would be meaningless; we need at least one.
Now, check if there is any trick: For a dynasty of length 1, the condition is that first=last. So that's a self-loop. That's handled.
Now, does the DP need to consider that the first and last condition must hold? Since we only take dp[s][s] at the end, we enforce it.
Now, think about potential improvements: The DP is O(26*n). That's fine.
Now, verify with a more complex example where the optimal dynasty might skip some edges. The DP will consider all subsequences because at each edge we can either take or skip. So that's fine.
Now, consider if there is a long sequence that returns to start after many edges, but there might be a better path that does not use some edges that would otherwise be beneficial but we skip them. DP handles that.
Now, consider the possibility of using an edge to update dp[s][l] for multiple s simultaneously. That's fine.
Now, think about initialization: dp[s][s]=0 ensures we can start at any vertex. However, what about the case where the dynasty must start with a king that is the first in the list? Not necessarily; the dynasty can start at any index. So it's fine.
Now, but there is a subtlety: When we start a walk using an edge, we rely on dp[s][s]=0 for s equal to first letter of that edge. But what about starting a walk with an edge that has first letter f, but we haven't set dp[f][f] to 0? We do set all dp[i][i]=0. So it's fine.
Now, what about starting a walk from a vertex that is not the first letter of any edge? That's irrelevant.
Now, confirm that the DP correctly ensures that we cannot use an edge before we have a walk that ends at its first letter. That's done.
Now, think about the possibility of using an edge to extend a walk that has never been started? No, because dp[c][f] would be -inf unless we have a walk ending at f with start c. That's correct.
Now, ensure that the DP doesn't allow using an edge twice. Since we process each edge only once, we only have the option to take it at most once.
Now, one more thing: The list includes all names of kings and relatives. But if a name appears multiple times, can we use both occurrences? They are distinct entries, yes. So we can take both if they are in order.
Now, check example 1: works.
Now, we should test with random small cases to ensure correctness. But given reasoning, it's likely correct.
Now, consider edge case where there are many edges and we have to compute large sums; use 64-bit.
Now, potential pitfalls: Input reading might be large, so use fast I/O (e.g., cin with sync false, or scanf). Since we are using C++, we can use ios_base::sync_with_stdio(false); cin.tie(0);.
Now, let's think about alternative interpretations: Could the dynasty be required to be a contiguous segment of the list? The problem statement: "Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland." It doesn't explicitly say that the dynasty must be a subsequence; it says "all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B." That implies that if we select a set of names as kings, they must preserve the order of the list. That's exactly a subsequence. It does not say they must be consecutive. So subsequence is correct.
But could the dynasty be required to be a set of kings that ruled consecutively without any other kings in between? The list includes relatives, but not necessarily other kings.