Ivan wants to play a game with you. He picked some string s of length n consisting only of lowercase Latin letters.
You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from 1 to n-1), but he didn't tell you which strings are prefixes and which are suffixes.
Ivan wants you to guess which of the given 2n-2 strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!
Input
The first line of the input contains one integer number n (2 ≤ n ≤ 100) — the length of the guessed string s.
The next 2n-2 lines are contain prefixes and suffixes, one per line. Each of them is the string of length from 1 to n-1 consisting only of lowercase Latin letters. They can be given in arbitrary order.
It is guaranteed that there are exactly 2 strings of each length from 1 to n-1. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length n.
Output
Print one string of length 2n-2 — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The i-th character of this string should be 'P' if the i-th of the input strings is the prefix and 'S' otherwise.
If there are several possible answers, you can print any.
Examples
Input
5
ba
a
abab
a
aba
baba
ab
aba
Output
SPPSPSPS
Input
3
a
aa
aa
a
Output
PPSS
Input
2
a
c
Output
PS
Note
The only string which Ivan can guess in the first example is "ababa".
The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.
In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are given a problem: We have a string s of length n, unknown. We are given 2n-2 strings, each of length from 1 to n-1. These are exactly all the proper prefixes and proper suffixes of s, but not labeled. There are exactly two strings for each length L (1 <= L <= n-1). One of them is the prefix of length L and the other is the suffix of length L (the suffix of length L is the last L characters of s). The given strings are in arbitrary order.
We need to output an assignment of each of the 2n-2 strings as either prefix (P) or suffix (S), such that there exists some string s of length n that is consistent with this assignment (i.e., for each length L, the string assigned as prefix of length L must equal the first L characters of s; the string assigned as suffix of length L must equal the last L characters of s). Also the number of P's and S's should each be n-1 (since exactly one prefix per length and one suffix per length). But the problem says the number of P's equals number of S's (since total strings = 2n-2 => n-1 each). So any valid assignment will automatically satisfy that.
If multiple assignments possible, any is acceptable.
We need to output a string of length 2n-2, with 'P' or 'S' for each input line in order.
Essentially, we need to assign each given string to either prefix or suffix, consistent with some string s.
Observations: For each length L, there are exactly two strings of that length. One must be prefix, the other suffix. So the assignment essentially decides which one is which for each length. However, there may be constraints across lengths: The prefix of length L must be a prefix of the prefix of length L+1. Similarly, the suffix of length L must be a suffix of the suffix of length L+1 (i.e., the suffix of length L is the last L characters of s, and suffix of length L+1 is the last L+1 characters, so the suffix of length L is the suffix of length L+1 without its first character? Actually careful: For suffixes, if we have suffix of length L (call it suf(L)), it is the substring s[n-L+1..n]. For suffix of length L+1, it is s[n-L..n]. So suf(L) should be a suffix of suf(L+1) (i.e., the last L characters of suf(L+1) equal suf(L)). Also, the prefix of length L must be a prefix of prefix of length L+1. So these hierarchical constraints can be used.
Given we have two strings per length, we need to label them P and S. The assignment must satisfy the prefix chain and suffix chain. Also, the whole string s can be deduced as: the prefix of length n is the full string, but we are not given that. However, we have both prefix of length n-1 and suffix of length n-1. The full string s must be consistent: i.e., the prefix of length n-1 plus the last character equals s, and the first character plus suffix of length n-1 equals s. So we must have that the prefix of length n-1 and suffix of length n-1 overlap appropriately. More precisely, if we denote p(L) as the prefix of length L, and s(L) as the suffix of length L, then for any L, we have that p(L) = first L of s, and s(L) = last L of s. In particular, for any k from 1 to n-1, we have that p(L) must match the first L characters of s; s(L) must match the last L characters of s. So for any L1 and L2, there are overlapping constraints: For example, the first L characters of s (p(L)) must match the first L characters of p(L+1) (which is p(L+1) without its last character). That is the prefix chain: p(L) is prefix of p(L+1). Similarly, s(L) is suffix of s(L+1). And also, the whole string s must satisfy that p(L) and s(L) are consistent: For any i + j = n? Actually we need that the string formed by prefix and suffix glue: For length n, we have s = p(n) (not given) but can be derived: p(n-1) plus something; also something plus s(n-1). Specifically, the string s must be such that its prefix of length n-1 equals p(n-1) and its suffix of length n-1 equals s(n-1). So s must be of the form p(n-1) + x, and also y + s(n-1), where x is a character and y is a character. Since both represent the same s of length n, we have:
p(n-1) + x = y + s(n-1) (as strings of length n)
Thus, the overlapping of p(n-1) and s(n-1) must be consistent: The last n-2 characters of p(n-1) should equal the first n-2 characters of s(n-1) if we align them? Let's derive:
Let s = s1 s2 ... sn.
p(n-1) = s1...s_{n-1}
s(n-1) = s2...s_n
Thus, the condition is that the suffix of p(n-1) of length n-2 equals the prefix of s(n-1) of length n-2. That is: s2...s_{n-1} must match. So the overlapping region of length n-2 must be consistent. And then x = s_n, y = s1.
Thus, given p(n-1) and s(n-1) we can check compatibility: p(n-1)[2..n-1] == s(n-1)[1..n-2] (1-indexed). And then s = p(n-1) + s(n-1)[n-1] (the last character) or equivalently p(n-1)[1] + s(n-1).
Hence, one way to solve: For each possible labeling of the strings per length (assign which of the two strings of each length is prefix and which is suffix), we can check the consistency constraints: For each L from 1 to n-2, the prefix of length L must be a prefix of the prefix of length L+1; similarly for suffixes. And also the final compatibility between p(n-1) and s(n-1) must hold. If so, we have a valid s.
Since n <= 100, the number of lengths is n-1 up to 99. For each length, we have 2 choices (which string is prefix). That gives 2^(n-1) possibilities, which is too large for n=100. However, we may not need to try all; we can use some combinatorial reasoning.
Observation: The prefix strings must all be consistent in that each is a prefix of the next longer one. Similarly for suffixes.
Given we have two strings per length, but we don't know which is which. However, the set of prefixes themselves must form a chain, and the set of suffixes must form a chain. So we could try to determine which of the two strings for each length could be the prefix based on compatibility with possible chains.
Alternative approach: Since there always exists at least one valid string s (the problem guarantee: these strings are prefixes and suffixes of some existing string), there must be at least one assignment that works. We need to output any assignment.
We could try to reconstruct s from the given strings, and then assign accordingly.
Given we have all proper prefixes and suffixes, but not labeled. Could we uniquely determine s? Not always; there may be multiple possible s as in example 3 ("ac" or "ca").
But we need to assign P/S labels such that there exists at least one s. In other words, the assignment does not have to correspond to a unique s; it just must be consistent with some s.
Thus, we could attempt to construct a candidate s that is consistent with the given strings, and then assign labels based on that candidate. Since the input guarantees that the set of strings are prefixes and suffixes of some string (maybe more than one), we can find one such string and then the labels will be determined: For each given string, if it equals the prefix of that length for candidate s, label P; else if it equals suffix, label S (must be). But caution: There might be a scenario where both strings of a given length equal the prefix and suffix of candidate s? That can't happen because the prefix and suffix of the same length are generally different (but could be same, e.g., palindrome). If they are identical, then both strings are the same? But the problem says "exactly 2 strings of each length from 1 to n-1". It does not say they are distinct. So they could be the same string if the prefix and suffix of that length are equal. In such case, the labeling of the two occurrences (there are two identical strings) can be ambiguous: one should be P, the other S. But the problem might require assignment: we have two lines with same string; we need to assign one as P and one as S (order matters). So using a candidate s we can assign: for that length, the prefix equals some string; both given strings may equal it; but we need to decide which of the two input lines gets P and which gets S. Since they are identical, we can arbitrarily assign one as P and the other as S as long as counts match. In the output, we need to assign for each input line. So we can just assign based on order: e.g., the first occurrence (in input order) as P, second as S, if both strings are identical and match both roles. That would be consistent because s has both prefix and suffix equal to that string, so either assignment works.
But careful: Could it happen that for some length, the two given strings are different, but candidate s's prefix equals one, and suffix equals the other, then assignment is forced (the one matching prefix gets P, the other S). However, if candidate s's prefix and suffix are swapped relative to some length? That would not be consistent because then both assignments would be invalid? Actually if we pick a candidate s, then the prefixes and suffixes are determined: for each length L, there is exactly one prefix string (the first L chars of s) and one suffix string (the last L chars). Among the given two strings of length L, one must equal that prefix and the other must equal that suffix. So the assignment is determined up to swapping if they are equal. So indeed, if we can find any s consistent with all given strings (i.e., such that for each length L, the two given strings of length L are exactly the set {prefix(L), suffix(L)}), then we can label accordingly. And since the input guarantees existence of some string, we just need to find one such s.
Thus, the problem reduces to: Given the multiset of strings (but we have order, but we ignore order), each length L appears twice, and they are known to be the set of prefixes and suffixes of some unknown string of length n. Find any string s of length n such that for each L, the two strings of length L are exactly the first L and last L characters of s (order unspecified). Then assign labels accordingly.
Now, how to find s?
We have two strings of each length. For each length L, let's denote the two strings as a_L and b_L (maybe unordered). We need to decide which is prefix p(L) and which is suffix s(L). Then we need that:
For L=1,..., n-2: p(L) is a prefix of p(L+1) and s(L) is a suffix of s(L+1).
Also, the full string s = p(n-1) + last_char = first_char + s(n-1) with overlap condition.
Alternatively, we can think of constructing s by combining the longest prefix and longest suffix (length n-1). The two strings of length n-1 are among the given. Let's call them X and Y (the two strings of length n-1). One of them is the prefix of length n-1, the other is the suffix of length n-1.
For any candidate s, s must be such that its length n-1 prefix is X or Y, and length n-1 suffix is the other.
We can try both possibilities: Suppose we set p = X, s = Y (suffix of length n-1). Then the full string s_candidate = X + Y[n-1] (since adding last char from suffix), but also must equal X[1] + Y (first char from prefix + suffix). For consistency, we need X[2..n-1] == Y[1..n-2]. If this holds, then s_candidate = X + Y[n-1] is consistent.
Alternatively, if we set p = Y, s = X, then need Y[2..n-1] == X[1..n-2]. If both hold, then there might be two possible s.
If only one holds, we have unique assignment.
But we also need to ensure that for all other lengths L, the prefix/suffix strings derived from s_candidate match the given strings (i.e., the set of two strings of each length equals {p(L), s(L)}). But if we derived s from the n-1 strings only, we need to verify consistency with all other lengths. However, maybe if the overlapping condition holds and we also ensure that the chain constraints for the chosen assignment (p(L) derived from s) match the given strings, it's okay. But can it be that the overlapping condition holds but the other lengths don't match? Possibly yes. For instance, suppose given strings come from a particular s, but if we swap the labeling of the two n-1 strings (p and s) we might get a candidate s' that does not have the correct prefixes/suffixes for other lengths. But we can check.
Given the input is guaranteed to come from some s, at least one of the assignments for n-1 should work (maybe both). So we can try both possibilities for the n-1 strings. For each, we can deduce the full string s (as above), then verify that for each length L, the two given strings are exactly the prefix and suffix of s of that length. If verification passes, then we can output labels based on that s.
Given n <= 100, this is efficient: O(n^2) per trial.
But we also need to handle the case where the two n-1 strings are identical. Then both assignments are the same, but we need to verify that other lengths match. That would be fine.
Now, we need to decide which of the two n-1 strings to use as prefix. So we try both:
Case 1: Let A be one of the length n-1 strings, B be the other. Check if A[1..n-2] == B[0..n-3]? Actually careful: For s of length n, we have s[1..n-1] = A, s[2..n] = B (if A is prefix and B is suffix). Then we need A[2..n-1] == B[1..n-2] (0-indexed: A[1:]== B[:-1]). If true, then we can construct s = A + B[-1] (or A[0] + B). Then compute all prefixes and suffixes of s, and compare with given strings. But we have to consider that the given strings may appear in any order, but we need to check that for each length L, the set of two given strings exactly matches {prefix(L), suffix(L)}. This includes lengths from 1 to n-1. If yes, then we can assign labels accordingly. For each input string, we check if it equals prefix of its length -> label P; else suffix -> label S.
However, there's a nuance: For a given length L, it's possible that prefix(L) == suffix(L) (palindrome). Then the two given strings might both be equal to that same string. In our candidate s, both prefix(L) and suffix(L) are equal. When comparing the given strings, we need to ensure that we have exactly two copies of that string (in the input). Since it's given that there are exactly 2 strings of that length, they could be identical. So our verification should check that the multiset of given strings for each L equals the multiset {prefix(L), suffix(L)}. That is, count occurrences.
Since we have the list of input strings with lengths, we can group them by length and have an array of strings for each length L (two strings). We can then for candidate s, for each L compute pref = s[0:L], suff = s[n-L:n]. Then we need to see that the multiset of given strings of length L matches {pref, suff}. If so, candidate is consistent.
Now, we try both assignments for n-1. At least one will work. But is it possible that both work? Yes, as in example 2, both assignments could work? Actually example 2: n=3, strings: a, aa, aa, a. The two strings of length 2 are both "aa". The two strings of length 1 are both "a". So for candidate s = "aaa", prefix1 = "a", suffix1 = "a"; prefix2 = "aa", suffix2 = "aa". So both assignments for length 2 are the same (both "aa"). For length 1, both "a". So both assignments for n-1 (which is length 2) result in same s = "aaa". So both checks pass. Then we can assign arbitrarily. That's fine.
What about example 3: n=2, strings: a, c. Two length 1 strings: "a" and "c". For candidate s = "ac": prefix1 = "a", suffix1 = "c". For s = "ca": prefix1 = "c", suffix1 = "a". Both possible. So both assignments for length 1 (which is n-1 because n=2, length 1) produce different s. Both are consistent with the input? Check: Input strings: "a" and "c". For s="ac", the set of length 1 prefix/suffix is {a,c} matches. For s="ca", also {a,c}. So both work. So we can pick either. The output may be "PS" or "SP". Both acceptable. So our algorithm would try one assignment: A="a", B="c"? Actually the two strings length1 are "a" and "c". So we have two possibilities: consider A="a", B="c". Check overlap condition? For n=2, we have p(1) and s(1). Overlap condition? The condition for n=2 is: if A is prefix of length1, B is suffix of length1, then we need A[2..1]? There is no overlapping region (n-2 = 0). So the condition is vacuously true. So we can construct s = A + B? Actually s = prefix1 + suffix1? But careful: For n=2, the full string s = prefix1 + last_char? Actually suffix1 is the last 1 character. If prefix1 = s[1], suffix1 = s[2]. So s = prefix1 + suffix1. That yields "ac". For the other assignment, s = "c"+"a" = "ca". So both are valid. Our verification will check that the computed s's prefixes/suffixes match given strings. Both will pass. So we can choose either.
Thus the algorithm seems straightforward:
Read n.
Read all 2n-2 lines into an array input_strs preserving order.
Group strings by length. Since lengths range 1..n-1, for each length L we maintain a list of strings (should be exactly 2). We'll store them as list_by_len[L] = [str1, str2] (the order they appear? Not needed for verification but we need to output per input order). For verification, we need to compare sets/multisets.
Better: we can also store for each length the two strings and also keep mapping from each input index to its length. Then later, for a candidate s, we compute for each length L the expected prefix and suffix strings. Then we need to check that the multiset of given strings of length L matches the multiset of these two expected strings. That is, we can count occurrences: For each length L, we have two given strings (maybe equal). We can compare: If the two given strings are both equal to expected prefix and both equal to expected suffix? Actually we need that the two given strings are exactly the two expected strings, considering duplicates. So we can simply check: for each length L, let exp = [pref(L), suff(L)]. Sort or compare counts:
If pref(L) != suff(L): then we need that the two given strings are one equal to pref and the other equal to suff.
If pref(L) == suff(L): then both given strings must be equal to that string.
This can be done by, for each L, count occurrences of pref(L) among the two given strings; it should be exactly 1 if they differ, or 2 if they are equal. Similarly for suff(L). Equivalent: create a multiset of the two given strings, compare with multiset of exp strings.
If for all L, the condition holds, then candidate s works.
Determine the two strings of length n-1. Let's denote them as A and B (the two strings from list_by_len[n-1]). We will try both assignments:
Assignment 1: prefix = A, suffix = B.
Check if overlapping condition holds: A[1:] == B[:-1] (since A[2..n-1] vs B[1..n-2] 0-indexed). Actually careful: For length n, s = A + B[-1] (since B is suffix of length n-1, so s = s1..s_{n-1} + s_n where s1..s_{n-1}=A, s_n = B[-1]). For consistency, we also must have that the last n-1 characters of s equal B. That implies that s[2..n] = B? Wait, s = A + B[-1] => s[0..n-2]=A, s[n-1]=B[-1]. Then suffix of length n-1 is s[1..n-1] = A[1:] + B[-1] (since s[1..n-1] = A[1:] concatenated with B[-1]). That must equal B. So condition: B = A[1:] + B[-1]? Actually let's do formally:
Let s = A (length n-1) concatenated with x, where x is a character. So s = A + x.
The suffix of length n-1 is s[1..n] = s[1:] = (A without first character) + x = A[1:] + x.
We require that this equals B (the assumed suffix). So condition: B = A[1:] + x, where x is the last character, but x is also the last character of B? Actually from B = A[1:] + x, we can solve: x must be the last character of B, and A[1:] must be B without its last character. So condition: A[1:] == B[0:-1]? Let's index: A = a1 a2 ... a_{n-1} (1-index). s = a1 a2 ... a_{n-1} x. Then suffix = a2 ... a_{n-1} x. So B must equal a2 ... a_{n-1} x. So B's first n-2 characters = a2 ... a_{n-1} = A[2..] (i.e., A from index 2 to end). And B's last character = x. So condition: A[2..] == B[1..n-2]? Wait, B's first n-2 characters (indices 1..n-2) should equal A's last n-2 characters (indices 2..n-1). So A[1:]? Actually A[1:] (starting from index 2 if 1-index?) Let's use 0-index to avoid confusion:
0-index: s indices 0..n-1.
Let A = s[0..n-2] (length n-1)
Let B = s[1..n-1] (suffix length n-1)
So s = A + s[n-1] = s[0] + B.
Thus, we have:
B = s[1..n-1] = A[1:] + s[n-1]? Actually A[1:] = s[1..n-2], length n-2. Then B = s[1..n-1] = s[1..n-2] + s[n-1] = A[1:] + last_char. So B = A[1:] + last_char.
Similarly, A = s[0] + B[0..n-2]? Actually B[0..n-2] = s[1..n-2] = A[1:]. So A = s[0] + A[1:] = s[0] + (B without last char). So A = s[0] + B[0:-1].
So the necessary condition for A and B to be consistent as prefix and suffix is: A[1:] == B[0:-1] (i.e., B without its last character) and also B[-1] is the extra char, and A[0] is the first char. So we can check: A[1:] == B[:-1]. Equivalent to A without first char equals B without last char. That's the overlapping condition. And also we can derive s = A + B[-1] (or A[0] + B). So to test, we can compute s_candidate = A + B[-1]. Then compute its prefixes and suffixes and verify against all given strings.
Alternatively, we can compute s_candidate = A[0] + B.
Both should give same string if condition holds. If condition does not hold, then the candidate s constructed by concatenating A + B[-1] will not have suffix B. Actually if condition fails, then either A[1:] != B[:-1], then the constructed string s = A + B[-1] will have suffix B? Let's check: If we force s = A + B[-1], then its suffix of length n-1 is s[1:] = A[1:] + B[-1]. That equals (A[1:]) + B[-1]. For this to equal B, we need A[1:] == B[:-1]. So if condition fails, then s will not have suffix B; it would have some other string. So verification will fail because the suffixes computed from s won't match the given B. So we can still construct s = A + B[-1] even if condition fails, but then verification will reject because the suffix of length n-1 won't match B. So we don't need to explicitly check the overlapping condition; we can just construct s = A + B[-1] (or A[0] + B) and then verify all lengths. The verification will catch inconsistency. So we can simply for each assignment, compute s = A + B[-1] (since we assume A is prefix and B is suffix), compute all prefixes/suffixes, and verify. This is simpler.
Similarly for the opposite assignment: prefix = B, suffix = A, construct s = B + A[-1] and verify.
Thus algorithm:
Read all strings. Group by length: For each length L (1..n-1), store a list of strings of that length (should be two). Also store for each input index: its string and length.
Let list_n1 = strings of length n-1 (two strings). If there are more than two? Guarantee exactly two.
For each permutation (assign which is prefix and which is suffix), do:
candidate = prefix + suffix[-1] (prefix is of length n-1, suffix is the other)
(Equivalently candidate = prefix[0] + suffix)
Compute all prefix strings of candidate: for L=1..n-1, pref[L] = candidate[0:L]
Compute suffix strings: for L=1..n-1, suff[L] = candidate[n-L:n]
For each L, check that the multiset of given strings of length L equals the multiset {pref[L], suff[L]}.
If all L pass, then this candidate works. Record the labeling: For each input string (by index), compare with pref[len] and suff[len] to assign:
If the input string equals pref[len] and not yet assigned? But there may be duplicate: if pref[len] == suff[len], then both assignments are possible. We need to assign exactly one P and one S for that length. Since we have two input strings of that length, we need to assign one as P and the other as S. However, they are identical; we can arbitrarily assign, but we must ensure the output string has exactly one P and one S for that length? Actually the output must have total counts of P and S each equal to n-1. If for a length L, pref==suff, then both roles are the same string; but we have two copies of that string in the input. Since they are identical, we can assign one copy as P and the other as S. That will satisfy that exactly one P and one S for that length (though the strings are same, the labeling is arbitrary). So when we produce output, for each index, we need to decide whether that particular occurrence is P or S. If pref != suff, then exactly one of the two given strings matches pref; the other matches suff. So assignment is forced. If pref == suff, then both strings match both roles. But we need to assign one P and one S. We can arbitrarily assign the first occurrence (by input order) as P, second as S, or vice versa. However, we must ensure that the output we produce is consistent with the candidate we selected. Since candidate says both roles are the same, any assignment where we label one occurrence as P and the other as S is valid because it corresponds to some mapping (there is no constraint that the string labeled P must be different from S). So we can choose arbitrarily.
We need to output for all indices. So we can, after selecting candidate, for each length L, we have the list of indices that have strings of that length (there are exactly two). We'll have expected pref and suff strings. If pref != suff, then we can identify which index string equals pref (that gets 'P'), the other gets 'S'. If both strings equal both pref and suff (because they are equal), then we can assign, say, the first index in the list (the one that appears earlier) as 'P', the second as 'S' (or any). That yields a valid output.
Given guarantee that at least one will work, we can just iterate two permutations and break when found.
But wait: Is it possible that both permutations fail? According to guarantee, there is some string s that is consistent with the given strings. That s has its own prefix and suffix of length n-1, say p_true and s_true. In the input, these two strings appear as the two strings of length n-1. So the permutation where we assign prefix = p_true and suffix = s_true will make the candidate = s_true? Actually if we construct candidate = p_true + s_true[-1], that should equal the true s. Because s = p_true + last_char, and last_char is s_true[-1] (since s_true = s[1..n] = last n-1 chars, its last char is s[n-1]). So candidate will be exactly s. Then verification will succeed. So at least one permutation (the correct one) will succeed. So algorithm is correct.
But careful: Could there be a scenario where both permutations produce a candidate that passes verification? Yes, that happens when the true s is a palindrome? Actually if s is a palindrome, then p_true = s[0..n-2]? Wait, for palindrome of length n, prefix of length n-1 might not equal suffix of length n-1 unless it's symmetric. For palindrome, s is symmetric, so s[0..n-2] vs s[1..n-1] are not necessarily equal. Example: s = "aba", n=3, prefix2 = "ab", suffix2 = "ba". They are different. So both assignments? If we swap them, we get candidate = "ba" + "b"? Actually prefix assignment swapped: take prefix = "ba", suffix = "ab", construct candidate = "ba" + "ab"[-1] = "bab"? That's "bab", which would give prefixes: "b", "ba", "bab"; suffixes: "b", "ab", "bab". The given strings are for s="aba": length1: "a","b"? Actually for "aba", prefixes: "a","ab"; suffixes: "a","ba". So the input would have two strings of length1: "a" and "a"? Wait, careful: For s="aba", proper prefixes: "a", "ab"; proper suffixes: "a", "ba". So length1 strings: two copies of "a"? Actually there are two length1 strings: one from prefix "a", one from suffix "a". So both are "a". Length2 strings: "ab" and "ba". So input: (e.g.) "a", "ab", "ba", "a". So the two length2 strings are "ab" and "ba". For the candidate "bab", its prefixes: "b", "ba", "bab"; suffixes: "b", "ab", "bab". So length1 strings: "b" and "b"? Actually both would be "b", but input length1 strings are both "a". So candidate "bab" would fail verification because length1 strings don't match. So swapping fails. So only correct assignment works. So both assignments succeed only if the true s is such that swapping yields the same set? For that to happen, the multiset of prefixes and suffixes must be invariant under swapping the roles of p(n-1) and s(n-1). This would require that for each length L, the multiset {pref(L), suff(L)} is symmetric. That's the case when the string is such that pref(L) = suff(L) for all L? Not exactly. Let's think: If we have a valid s, then the swapped assignment (p' = s_true, s' = p_true) yields candidate s' = s_true + p_true[-1] =? This candidate would be the "reverse" maybe? It could be that this candidate also satisfies the multiset condition if the original set is symmetric? But guarantee says the input strings come from some s, but it could be that there are multiple s consistent with the same set of strings. For instance, example 3: n=2, strings "a" and "c". Both s="ac" and s="ca" are consistent. So swapping the length1 strings yields the other s, and both pass verification. So indeed both assignments may work when there are multiple possible s. That's fine.
Thus our algorithm works.
Edge Cases: n=2. Then we have two strings of length 1. Our grouping: length1 has two strings. For each assignment (A as prefix, B as suffix), candidate = A + B[-1] = A + B (since B length1). So candidate = A + B. Similarly opposite candidate = B + A. Then we verify that for L=1, the multiset of given strings equals {pref(1), suff(1)} = {candidate[0], candidate[1]}. That's just checking that the two given strings are exactly the two characters (order doesn't matter). This will hold for both candidates if the two given strings are distinct. If they are equal (e.g., both "a"), then candidate = "aa" from both assignments (since A = "a", B = "a", candidate = "aa") and verification will hold. So output can be "PS" or "SP". In either case, for the two indices, we assign based on which matches prefix? If they are both "a", and candidate's prefix and suffix are both "a", then both given strings are "a". Then we arbitrarily assign one as P and the other as S. That's okay.
Now, implementation details:
We need to store the input strings and also grouping by length. For verification, we can for each length L, compute expected multiset: two strings: pref(L) and suff(L). Then we need to compare with the given two strings. Since there are only two, we can just count matches.
Simplify verification: For each length L, we have an array given_strs[L] = [str1, str2] (the two input strings of that length). We compute expected_pref = candidate[0:L], expected_suff = candidate[n-L:n]. Then we check:
If expected_pref != expected_suff:
Then we need that given_strs[L] contains exactly one expected_pref and exactly one expected_suff. So we can check: (given_strs[L][0] == expected_pref and given_strs[L][1] == expected_suff) or (given_strs[L][0] == expected_suff and given_strs[L][1] == expected_pref). That's all.
If expected_pref == expected_suff:
Then both given_strs[L] must be equal to that string. So check: given_strs[L][0] == expected_pref and given_strs[L][1] == expected_pref.
That's it.
Now, after finding a valid candidate, we need to output the assignment for each input index. Since we stored the input strings in order, we also stored for each index its length L. We also have the grouping by length, but we need to assign per index. For each length L, we know which of the two given strings should be prefix and which suffix (if they differ). But careful: The given strings might appear in any order; we need to assign exactly one 'P' and one 'S' for that length. For consistency, we can just, after candidate is valid, iterate over all indices, and for each index, we know its string str_i and length L_i. We also know the expected prefix for that length, pref(L_i), and suffix, suff(L_i). If pref(L_i) != suff(L_i), then if str_i == pref(L_i), output 'P'; else if str_i == suff(L_i), output 'S'; else (shouldn't happen). If pref(L_i) == suff(L_i), then we need to assign one 'P' and one 'S' arbitrarily among the two indices with that length. To do that, we can process each length separately: for length L with two indices, if pref == suff, we can assign the first occurrence (in input order) as 'P' and second as 'S' (or any deterministic rule). But we have to be careful: The indices are across the whole list; we can just for each index individually assign based on string equality? If both strings are same, then both equality checks hold for both pref and suff, so we can't distinguish. So we need a deterministic rule that ensures exactly one P and one S per length. One approach: When pref == suff, we know that both given strings are that value. We can iterate through all indices, and for each length L, keep a counter of how many P assigned for that length so far. For each index of that length, if we haven't assigned any P yet, assign 'P', else assign 'S'. This yields exactly one P and one S. This works because there are exactly two indices per length.
But what if pref != suff? Then we can also use the equality check: exactly one string equals pref, the other equals suff. So we can simply assign based on equality. However, we should also ensure that we don't accidentally assign two P's if both strings equal pref (which would happen if pref == suff? but that case we handle separately). So in the unequal case, it's safe: the string that matches pref gets 'P', the other gets 'S'. Since both strings are distinct from each other? Actually they could be equal? If pref != suff, but the given strings could be both equal to something else? No, they must match the set {pref, suff}, so one is pref, the other is suff, and pref != suff, so they are distinct. So exactly one matches pref, one matches suff. So we can just assign.
Thus, after candidate verification, we can produce output.
Now, time complexity: O(n^2) due to building candidate and verifying each length (n-1 lengths, each string comparison up to length O(n) but n max 100, so fine). 2 permutations.
Potential pitfalls: The input strings may not be unique across lengths, but we only group by length.
We must also consider that the two strings of length n-1 are stored in list_by_len[n-1] as two strings. However, we don't know the order relative to input; we just need to pick one as prefix and one as suffix. Since there are exactly two, we can try both assignments. So in code, we can do:
Let a = list_by_len[n-1][0], b = list_by_len[n-1][1].
Try assignment: prefix = a, suffix = b.
If fails, try prefix = b, suffix = a.
Note: It's possible that both succeed; we can just pick the first that succeeds (or either). We must guarantee to output something; so after first success we break and output.
But careful: When we try an assignment, we must construct candidate = prefix + suffix[-1]. However, if suffix is of length n-1, its last character is suffix[-1]. That's fine.
But there is a subtlety: For n=2, suffix length is 1, so suffix[-1] is the only character. candidate = prefix + suffix (since suffix length 1). That's fine.
Now, verification: For each L from 1 to n-1, we compute expected_pref = candidate[0:L] and expected_suff = candidate[n-L:n]. But note: For L = n-1, expected_pref = candidate[0:n-1] = prefix? Actually if we constructed candidate as prefix + suffix[-1], then expected_pref should equal prefix? Let's check: candidate = prefix (length n-1) + suffix[-1] (length 1). So candidate[0:n-1] = prefix (by construction). And expected_suff for L=n-1 is candidate[1:] = prefix[1:] + suffix[-1]. For the candidate to be valid, this must equal suffix. But we haven't enforced that; we rely on verification to check. So verification for L=n-1 will compare expected_suff with the given suffix string. Since we are using suffix as the second string in the assignment, we need that expected_suff == suffix. If not, verification fails. So it's fine.
Now, what about L = n? Not needed.
Thus algorithm is solid.
However, is there any scenario where neither assignment works even though there is a valid s? Let's double-check.
Suppose the true s is such that its prefix of length n-1 is A, suffix of length n-1 is B. Then if we try assignment prefix = A, suffix = B, candidate = A + B[-1] gives true s, verification passes. So that assignment works. So there must be at least one working assignment.
But wait, could it be that the given strings include the two of length n-1, but due to duplicates across lengths, the candidate we construct might incorrectly pass verification for some other reason? No, because the true s works.
Thus we can find a candidate.
Now, about the grouping: we need to build list_by_len[L] as an array of strings (size 2). However, there might be more than two strings per length? The problem says exactly 2 strings of each length. So yes.
Implementation steps:
Read integer n.
Initialize an array inputs of length 2n-2. Each element: (string, length). Also initialize by_len as dictionary or list of length n (index 0..n-1 maybe), but better to have a list of lists. Since n up to 100, we can create by_len = [[] for _ in range(n)] and ignore index 0.
For i in range(2n-2):
read line as s_i.
L = len(s_i)
inputs[i] = (s_i, L)
by_len[L].append(s_i)
Now, get the two strings of length n-1: let p1, p2 = by_len[n-1][0], by_len[n-1][1].
Define a function check(prefix_candidate, suffix_candidate) that returns (bool, candidate_s) maybe, and if bool true, then also produce assignment output.
But we can incorporate verification inside.
Pseudo:
def try_assign(prefix_str, suffix_str):
candidate = prefix_str + suffix_str[-1] # string length n
# Verify all lengths
for L in range(1, n):
prefL = candidate[:L]
suffL = candidate[n-L:]
# get the two given strings for length L
given = by_len[L] # list of two strings
if prefL != suffL:
# need given[0]==prefL and given[1]==suffL or vice versa
if (given[0] == prefL and given[1] == suffL) or (given[0] == suffL and given[1] == prefL):
continue
else:
return False, None
else: # prefL == suffL
if given[0] == prefL and given[1] == prefL:
continue
else:
return False, None
return True, candidate
Then we try:
success, cand = try_assign(a, b)
if not success:
success, cand = try_assign(b, a)
We can assert success (since input guarantee).
After we have cand, we produce output:
Initialize result array of chars length 2n-2.
We need to assign per index. But we must handle the case where for a given length, pref == suff. Our assignment should ensure exactly one P and one S for that length. Since we have already verified that the two given strings are both equal to that value, we can assign arbitrarily.
We could also use a per-length counter:
Initialize p_assigned = [0] * (n+1) to count how many P's assigned for each length (we just need to know if we assigned already for that length). Then for each index i from 0 to 2n-2:
s_i, L = inputs[i]
prefL = cand[:L]
suffL = cand[n-L:]
if prefL != suffL:
if s_i == prefL:
result[i] = 'P'
else:
result[i] = 'S'
else: # equal
if p_assigned[L] == 0:
result[i] = 'P'
p_assigned[L] = 1
else:
result[i] = 'S'
# p_assigned remains? we don't need more
But careful: If prefL != suffL, there is exactly one string that equals prefL and one that equals suffL. However, what if s_i equals both? impossible because they are distinct. So fine.
But is there any possibility that for a length where pref != suff, the two given strings might be such that both could be interpreted as prefix? No, because the set is exactly {pref, suff}. So exactly one string equals pref. So assignment is deterministic. However, if we assign using the rule above, we may end up assigning both as P if the first one equals pref and second also equals pref? That can't happen because there is only one pref string. So it's fine.
But we must be careful: The input may contain the two strings of length L in any order. So for pref != suff case, we assign 'P' to the index whose string equals pref; 'S' to the other. That yields exactly one P and one S. So we don't need to track p_assigned for unequal case; we can just assign based on equality. However, we have to be careful that when pref != suff, we might encounter both indices where s_i == prefL (only one) and for the other, s_i == suffL. So that's fine.
So the per-length counter is only needed for the equal case.
Alternatively, we can just, for each length, collect the indices and if pref==suff, assign first index as P, second as S (based on order of appearance). That is deterministic and simpler.
Implementation:
After we have candidate, we can precompute for each length L: prefL, suffL, and also a flag equal = (prefL == suffL). Then we can create a dictionary mapping length to a list of indices (ordered as they appear). Actually we already have by_len for strings, but not indices. So we can also create indices_by_len as list of lists of indices, initially empty, while reading input. For each index i, append i to indices_by_len[L]. Then after reading, each indices_by_len[L] will have two indices (the order they appear). So we can use that.
Then for each L:
if not equal:
For each of the two indices in indices_by_len[L]:
if inputs[i][0] == prefL: result[i] = 'P' else: result[i] = 'S'
else:
# assign first index as P, second as S (or any)
result[indices_by_len[L][0]] = 'P'
result[indices_by_len[L][1]] = 'S'
But wait: In the equal case, both strings are the same, so inputs[i][0] == prefL for both. So we could also just assign first as P, second as S. That's fine. That will output exactly one P and one S per length.
Now, is it guaranteed that for equal case, both given strings are exactly prefL? Yes, because we already verified that in check. So that works.
Thus, after we have a valid candidate, we can assign output accordingly.
Edge Cases: Need to ensure that for each length L, indices_by_len[L] has exactly 2 indices, and they are in the order of input. Good.
So by length:
len1: "a", "a"
len2: "ba", "ab"
len3: "aba", "aba"
len4: "abab", "baba"
n=5, so length4 is n-1.
Two strings of length4: "abab" and "baba".
Try assignment 1: prefix="abab", suffix="baba". candidate = "abab" + "baba"[-1] = "ababa". That's "ababa". Verify:
len1: pref="a", suff="a". given len1: two "a": both "a" -> OK.
len2: pref="ab", suff="ba". given len2: "ba","ab" -> matches set? Yes: one is "ab" (pref), one is "ba" (suff). OK.
len3: pref="aba", suff="aba". given len3: "aba","aba" -> OK.
len4: pref="abab", suff="baba". given len4: "abab","baba" -> OK.
So valid. Then assign output: Need to map input indices:
Index1: "ba" len2 -> suff? candidate suff2 = "ba", so it's suffix -> 'S'
Index2: "a" len1 -> both pref/suff equal -> assign first among len1 indices? We have indices_by_len[1] = [2,4] (if 1-indexed? careful: indices 0-based: index1? Let's use 0-based: index0:"ba", index1:"a", index2:"abab", index3:"a", index4:"aba", index5:"baba", index6:"ab", index7:"aba". So len1 indices: index1 and index3. pref1="a", suff1="a". Since equal, assign first (index1) as 'P', second (index3) as 'S'.
Index2: "abab" len4 -> pref4="abab" -> 'P'
Index3: "a" len1 -> 'S' (as assigned)
Index4: "aba" len3 -> both equal; len3 indices: index4 and index7. pref3="aba". So assign first (index4) as 'P', second (index7) as 'S'.
Index5: "baba" len4 -> suff4="baba" -> 'S'
Index6: "ab" len2 -> pref2="ab" -> 'P'
Index7: "aba" len3 -> 'S' (as assigned)
Thus output string: index0 S, index1 P, index2 P, index3 S, index4 P, index5 S, index6 P, index7 S => "SPPSPSPS". That matches example output.
Assignment2: prefix="baba", suffix="abab". candidate = "baba"+"b"? Actually suffix="abab", its last char = "b", candidate = "babab". Then verification? len2 pref = "ba"? candidate="babab": len2 pref = "ba", suff = "ab"? Actually candidate "babab": first2 "ba", last2 "ab"? Yes. Given len2 strings are "ba","ab" -> ok. len3 pref="bab", suff="bab"? Actually pref3="bab", suff3="bab"? candidate "babab": suffix3 = last3 = "bab"? starting at index2? indices: 0 b,1 a,2 b,3 a,4 b. suffix3 = indices 2-4 = "bab". pref3 = "bab". So both "bab". But given len3 strings are "aba","aba". That fails. So assignment2 fails. So we pick first.
Example2:
Input:
3
a
aa
aa
a
n=3. strings: len1: "a","a", len2: "aa","aa". by_len[2] = ["aa","aa"]. Try assignment1: prefix="aa", suffix="aa". candidate = "aa"+"a" = "aaa". Verification: len1: pref="a", suff="a". given len1: both "a" -> ok. len2: pref="aa", suff="aa". given len2: both "aa" -> ok. So success. Then assign output: indices:0:"a" len1,1:"aa" len2,2:"aa" len2,3:"a" len1. We'll need to assign one P and one S per length. For len1 (indices 0 and 3): equal, assign first (index0) as P, second (index3) as S. For len2 (indices 1 and 2): equal, assign first (index1) as P, second (index2) as S. Output: P P S S? Actually index0 P, index1 P, index2 S, index3 S => "PPSS". That's the example output. Could also be others.
Our algorithm with assignment based on order yields "PPSS". That's acceptable.
If we had tried the other assignment (swap) also yields same candidate? Actually prefix="aa", suffix="aa" are identical, swapping does nothing; candidate same. So both permutations lead to same candidate and success. So first works.
Example3:
Input:
2
a
c
n=2. by_len[1] = ["a","c"].
Try assignment1: prefix="a", suffix="c". candidate="a"+"c" = "ac". Verify: len1: pref="a", suff="c". given len1: "a","c" -> matches. success. Assign: len1 indices:0 and1, pref != suff, so assign: index0 (string "a") matches pref -> P; index1 (string "c") matches suff -> S => "PS". That's example output? Actually example output is "PS"? They gave output "PS"? Let's see: In the problem statement, Example3 input 2 a c output "PS"? The example says Output PS? Actually the text: Input 2 a c Output PS? Let's read: "Input 2 a c Output PS" Actually it's shown: Input 2 a c Output PS? The problem statement:
Input
2
a
c
Output
PS
So yes. However they mention "The answer "SP" is also acceptable." So our algorithm would try assignment1 first (depending on order of strings in by_len[1] which we get from input order). Input order: first "a", second "c". So by_len[1] = ["a","c"] (since we appended in order). So assignment1 uses prefix = first element "a", suffix = second "c". This yields "PS". If we instead try assignment2 (swap), we'd get "SP". Our algorithm will succeed on the first try and output "PS". That's fine.
Now, need to ensure that we handle cases where the two strings of length n-1 are not necessarily in the order that yields true s first; we try both. Good.
Now, consider a tricky scenario: Suppose n=4. Input strings might be like: For s = "abca". Then prefixes: "a","ab","abc"; suffixes: "a","ca","bca". So length1: two "a"? Actually suffix1 = "a", prefix1="a": both "a". length2: "ab" and "ca". length3: "abc" and "bca". So n-1=3: strings: "abc" and "bca". So by_len[3] = ["abc","bca"]. Try assignment1: prefix="abc", suffix="bca". candidate = "abc"+"a"? suffix[-1] = "a" => "abca". Verification passes. The other assignment: prefix="bca", suffix="abc". candidate = "bca"+"c" = "bcac". Verify: length1: pref="b", suff="c"? Actually candidate "bcac": pref1="b", suff1="c"; but given length1 strings are both "a". Fail. So only one works.
Now, what about a scenario where there are multiple s consistent. For example, n=3 with strings: length1: "a","b"; length2: "ab","ba". That would correspond to s="aba"? Check: s="aba": prefixes: "a","ab"; suffixes: "a","ba"? Actually length1: "a" from prefix, "a" from suffix? That's two "a", not "a" and "b". So not that. s="abb"? prefixes "a","ab"; suffixes "b","bb"? not match. s="abc"? prefixes "a","ab"; suffixes "c","bc"? not match. So maybe that set is not possible? Actually need exactly 2 strings per length. For n=3, length1 must have two strings; they could be "a" and "b". That would require s's first and last characters be 'a' and 'b' (order unknown). For length2, strings "ab" and "ba". Could s="aba"? Then length1: "a","a" not match. s="abb": length1: "a","b"? actually suffix1 = "b", prefix1="a" => set {"a","b"} good. length2: prefix2="ab", suffix2="bb" => {"ab","bb"} not match. s="bab": length1: "b","b"? not. s="abc": length1: "a","c" not. s="aab": length1: "a","b"? prefix1="a", suffix1="b" => {"a","b"} good. length2: prefix2="aa", suffix2="ab" => {"aa","ab"} not match. s="aba"? no. So maybe no s yields that set. But problem guarantee ensures input is from some s.
Now, consider scenario where the two strings of length n-1 are same? That implies that s's prefix of length n-1 equals its suffix of length n-1. That means s[0..n-2] = s[1..n-1]. This implies that s consists of the same character repeated? Let's analyze: For strings of length n, if s[0..n-2] = s[1..n-1], then s[0] = s[1], s[1] = s[2], ..., s[n-2] = s[n-1], so all characters equal. So s is a uniform string (all same letter). In that case, all prefixes and suffixes of same length are identical. So all given strings of each length will be two copies of the same string. This is consistent.
Now, what about candidate generation? If both n-1 strings are same, say "aaa...", then both assignments are essentially the same (prefix and suffix same). candidate = prefix + suffix[-1] = "aaa...a" + 'a' = same uniform string. So verification passes.
Now, our assignment for output: Since for each length, pref == suff, we assign first index as P, second as S. That's fine.
Now, one nuance: The verification we wrote uses by_len[L] which is a list of two strings. However, the order of strings in by_len[L] is the order they appear in input. That's fine for verification, because we only care about multiset. But we must be careful that in verification, we are checking if given[0] == pref and given[1] == suff or swap. This is correct.
But what about the possibility that for a length L, pref != suff, but the given strings are such that they match but we may have both strings equal to pref? Actually if pref != suff, then the set {pref, suff} contains two distinct strings. The input must have exactly those two strings. So one of the given strings is pref, the other is suff. Could it be that both given strings are equal to pref? That would be invalid because then the multiset wouldn't match; our verification would fail. That's fine.
Now, one more nuance: The candidate string may be constructed such that for some L, pref(L) and suff(L) might be swapped relative to the given strings? Actually our verification checks that the given multiset equals {pref(L), suff(L)}. So that's correct.
Now, consider a potential tricky case: The two strings of length n-1 might be such that both assignments produce a candidate that passes verification, but those candidates are different. That's fine; we can output either. So our algorithm picks first success.
Now, verify correctness in all cases: Since we check all lengths, if candidate passes, it means for each L, the two input strings are exactly the prefix and suffix. Thus, candidate is a valid s. So labels are consistent.
Now, potential issue: Could there be a scenario where candidate passes verification but the labeling we produce based on candidate does not satisfy the condition "there exists at least one string consistent with it"? Since candidate itself is such a string, it's fine. So output is acceptable.
Now, we should also consider if the input could be such that the candidate passes verification but the assignment we produce yields something like two P for a length? In our assignment, we ensure exactly one P per length (if equal we assign one P and one S; if unequal we assign based on equality, which yields one P and one S). So output string will have exactly n-1 P and n-1 S. So valid.
Thus, solution is straightforward.
Now, let's implement in Python.
Implementation details:
Read integer n.
Initialize inputs = [] list of tuples (string, length).
Initialize by_len = [[] for _ in range(n)] (index L from 0 to n-1, but we will use 1..n-1). We'll ignore index 0.
Initialize indices_by_len = [[] for _ in range(n)] similarly.
For i in range(2*n-2):
s = input().strip()
L = len(s)
inputs.append((s, L))
by_len[L].append(s)
indices_by_len[L].append(i)
After reading, we can optionally verify that each by_len[L] length == 2.
Now, let a, b = by_len[n-1][0], by_len[n-1][1].
Define try_assign(prefix_str, suffix_str) function that returns bool and candidate string if successful.
In the function:
candidate = prefix_str + suffix_str[-1] # length n
quick length check: len(candidate) == n
for L in range(1, n): # L from 1 to n-1
pref = candidate[:L]
suff = candidate[n-L:]
g = by_len[L] # list of two strings
if pref != suff:
if (g[0] == pref and g[1] == suff) or (g[0] == suff and g[1] == pref):
continue
else:
return False, None
else:
if g[0] == pref and g[1] == pref:
continue
else:
return False, None
return True, candidate
Now, try:
success, cand = try_assign(a, b)
if not success:
success, cand = try_assign(b, a)
assert success
Now, produce output:
result = [''] * (2*n-2)
for L in range(1, n):
idx_list = indices_by_len[L]
pref = cand[:L]
suff = cand[n-L:]
if pref != suff:
# assign based on string equality
# idx_list[0] and idx_list[1] correspond to the two strings (order in input)
s0 = inputs[idx_list[0]][0]
s1 = inputs[idx_list[1]][0]
# Determine which matches pref
if s0 == pref:
result[idx_list[0]] = 'P'
result[idx_list[1]] = 'S'
else:
# s1 must be pref
result[idx_list[1]] = 'P'
result[idx_list[0]] = 'S'
else:
# equal: assign first as P, second as S
result[idx_list[0]] = 'P'
result[idx_list[1]] = 'S'
Now print ''.join(result).
Edge Cases: The above assignment for pref != suff assumes that exactly one of s0, s1 equals pref. But what if due to some bug both equal? That would mean pref == suff? But we are in else case where pref != suff, so if both equal pref then both would equal pref, but then suff is different, so the set {pref, suff} would have one string equal to pref and the other to suff. If both s0 and s1 are pref, then the set does not contain suff. Our verification would have failed. So safe.
Now, could there be scenario where we accidentally assign both as P? In pref != suff case, we assign one P and one S. So fine.
Now, consider the case where pref == suff but there are more than two indices? Not possible; there are exactly 2 per length.
Thus algorithm works.
Now, test with custom cases.
Case: n=4, s="abca". Input simulate:
prefixes: "a","ab","abc"
suffixes: "a","ca","bca"
So list: length1: "a","a"; length2: "ab","ca"; length3: "abc","bca". Input order can be arbitrary but group accordingly.
Let's write a test:
n=4.
Input strings (order maybe): "a", "ab", "abc", "a", "ca", "bca". That's 6 lines. by_len[3] = ["abc","bca"] (or swapped). Our algorithm tries prefix="abc", suffix="bca" -> candidate="abca". Verification passes. Then assignment: length1 indices: two "a", equal -> assign first as P, second as S. length2: strings "ab" and "ca", pref2="ab", suff2="ca", so assign accordingly. length3: "abc" and "bca", pref3="abc", suff3="bca". Output could be e.g., for input order we defined, first "a" (P), second "ab" (P), third "abc" (P), fourth "a" (S), fifth "ca" (S), sixth "bca" (S) => "PPPS SS"? Actually that would be 3 P's and 3 S's? But n-1=3 per type, so 3 P and 3 S. That's "PPPSSS"? Let's list: index0: "a" P, index1: "ab" P, index2: "abc" P, index3: "a" S, index4: "ca" S, index5: "bca" S -> "PPPS SS"? Actually string "PPPSSS"? count: 3 P then 3 S. That's valid.
Now, if input order swapped such that length1 strings are not first? No matter.
Thus algorithm works.
Now, consider scenario where both assignments succeed but produce different candidates; we pick first. That's fine.
One more nuance: In the verification step, we compare strings for each L. For L = n-1, we compare pref = candidate[:n-1] which is prefix_str (since candidate = prefix_str + suffix_str[-1]). And suff = candidate[1:] which should equal suffix_str if candidate is consistent. So our verification includes that condition, so we don't need to explicitly check overlapping.
Now, ensure that candidate length is n. Since prefix_str length = n-1, plus one char = n. Good.
Now, what about the scenario where n=2 and both strings are the same (e.g., "a" and "a")? Then by_len[1] = ["a","a"]. Assignment1: prefix="a", suffix="a" -> candidate="aa". Verification: len1 pref="a", suff="a", given strings are both "a" -> passes. So output: indices: two indices, equal -> assign first P, second S => "PS" or "SP"? Depending on which index is first. If input order is first "a", second "a", output "PS". That's acceptable. Also assignment2 yields same candidate and same assignment if we swap? Actually if we swap, we get prefix="a", suffix="a" again because both are same; the function try_assign with arguments swapped will be identical, so it will pass. But we only do second if first fails, which it doesn't. So we output "PS". If they wanted "SP", they'd also accept. So fine.
Now, consider scenario where the two strings of length n-1 are identical but the candidate verification fails? That cannot happen because if they are identical and the input is from some s, then s must be uniform. Then candidate built as uniform string will pass verification because all prefixes and suffixes match. So first assignment will succeed.
Now, consider potential pitfalls: The function try_assign uses by_len[L] which is a list in order of input. But our verification only checks unordered multiset using conditions. However, if the order of by_len[L] is such that given[0] and given[1] are both same string and we compare with pref and suff, we do the correct check: for equal case, we check both given strings equal pref; for unequal, we check either ordering. So it's correct.
Now, memory: small.
Now, overall complexity: O(n^2) due to substring operations. But n <= 100, fine.
Now, final step: Provide code.
But wait, we should also think about potential mistake: In try_assign, we assume that candidate string is built from prefix and suffix strings of length n-1. However, if the given strings of length n-1 are not in the correct orientation (i.e., prefix vs suffix), candidate may be constructed incorrectly and verification fails. That's expected.
One more nuance: Could there be a scenario where both assignments produce candidates that pass verification but the labeling we produce from the candidate might not be consistent with the assignment of the n-1 strings? Actually labeling is derived from candidate's prefix/suffix sets, which are determined solely by candidate. If candidate passes verification, then for each length L, the two given strings are exactly the prefix and suffix of candidate. So the labeling we assign (matching which is prefix) will be consistent with candidate. However, is it possible that candidate passes verification but the mapping for length n-1 does not match the assumption we used to build candidate? Let's examine: Suppose we used assignment: prefix = A, suffix = B to build candidate. If candidate passes verification, then for length n-1, we must have that the prefix of candidate is A and suffix of candidate is B (since those are the only strings of that length). That is indeed forced because the given strings for L=n-1 are A and B, and verification ensures that {pref(L), suff(L)} = {A,B}. But if both A and B are equal, then pref(L) = suff(L) = A = B, so it's fine. If they are distinct, then exactly one of pref(L) equals A and the other equals B. But which one is which? In our verification, we didn't enforce that pref(L) = A; we only checked that the set matches. So it's possible that candidate's pref(L) = B and suff(L) = A, even though we assumed prefix = A to construct candidate. Let's see if that can happen.
Suppose we construct candidate = A + B[-1]. For candidate's prefix of length n-1, it's A by construction. For its suffix of length n-1, it's A[1:] + B[-1]. For the verification to pass with distinct A,B, we need that the set {pref, suff} equals {A,B}. Since pref = A by construction, we need suff = B. That forces A[1:] + B[-1] = B. This is exactly the overlapping condition. If that condition does not hold, verification fails because suff would not be B, and the set would be {A, something else} which would not match {A,B}. So verification only passes if suff = B. So in case of distinct A,B, if verification passes, then indeed pref = A and suff = B, matching our construction assumption.
Now consider if we swap assignment: we use prefix = B, suffix = A. Then candidate = B + A[-1]. For verification to pass, we need suff = A. That would require B[1:] + A[-1] = A. So for distinct A,B, if both conditions hold, then both candidates pass. This would imply A and B satisfy both overlapping conditions, which might happen only in special symmetric cases. Let's see if that can happen. Conditions: (1) A[1:] + B[-1] = B; (2) B[1:] + A[-1] = A. Can both hold? Let's denote A and B as strings of length n-1. Condition (1) means B = A[1:] + b, where b = B[-1]; but also B[-1] = b, and A[1:] = B[:-1]. So A[2..]? Actually condition (1) is A[1:] = B[:-1] and B[-1] is whatever. Condition (2) is B[1:] = A[:-1] and A[-1] is whatever. So these imply that A and B are rotations? Let's analyze: A = a1 a2 ... a_{n-1}, B = b1 b2 ... b_{n-1}. Condition (1): a2...a_{n-1} = b1...b_{n-2} and b_{n-1} is free. Condition (2): b2...b_{n-1} = a1...a_{n-2} and a_{n-1} is free. Combining: a2...a_{n-1} = b1...b_{n-2} and b2...b_{n-1} = a1...a_{n-2}. This suggests a kind of palindrome-like structure? Let's test with n=4 (length3). Find strings A, B length3 satisfying both. Let A = xyz, B = uvw. Conditions: yz = uv (A[1:]=B[:-1]) => yz = uv. And vw = xy (B[1:]=A[:-1]) => vw = xy. So we have: yz = uv and vw = xy. Write A = a1 a2 a3, B = b1 b2 b3. Conditions: a2 a3 = b1 b2, and b2 b3 = a1 a2. Then we can attempt to solve. For example, suppose a1=a, a2=b, a3=c. Then condition b2 b3 = a b => b2=a, b3=b? Actually b2 b3 = a b so b2='a', b3='b'. Then condition a2 a3 = b1 b2 => b c = b1 'a' => so b1='b'? Actually a2 a3 = b c; b1 b2 = b1 'a'. So b c = b1 a => so b1 = b, and then a = c? That would require c = a. So a3 must equal a2? Let's solve systematically: a2 a3 = b1 b2; b2 b3 = a1 a2. So we have b2 = a1? Not necessarily. Use variables. From b2 b3 = a1 a2 => b2 = a1, b3 = a2. Then from a2 a3 = b1 b2 => a2 a3 = b1 a1. So b1 = a2, and a3 = a1. So we have: b2 = a1, b3 = a2, b1 = a2. So B = (b1, b2, b3) = (a2, a1, a2). A = (a1, a2, a3) with a3 = a1. So A = (a1, a2, a1). B = (a2, a1, a2). So for n=4, example: a1='a', a2='b' => A="aba", B="bab". Then candidate1: A+B[-1] = "aba" + 'b' = "abab"? Actually B[-1] = 'b', candidate1 = "abab". Check if verification would pass? For s="abab", prefixes: "a","ab","aba"; suffixes: "b","ab","bab". Given set for length1? Need two strings: one "a", one "b"? For length2: "ab" and "ab"? Actually suffix2 of "abab" is "ab"? Wait, "abab": suffix length2 = "ab"? Actually indices: 0 a,1 b,2 a,3 b. suffix length2 = s[2:4] = "ab". So suffix2 = "ab". So length2 set would be {"ab","ab"}? That's two "ab". But given length2 in our hypothetical input? Actually we haven't defined the whole input set. But note that the conditions we derived came from the possibility that both assignments satisfy verification. For that to happen, the full set of prefixes and suffixes of candidate1 must match the given strings. The given strings come from some original s? In our derivation, we haven't ensured that all lengths match. But it suggests that there could be cases where both assignments produce valid candidates, meaning there are two distinct strings s that have the same multiset of prefixes and suffixes. This is possible, as example with n=2: "a","c" gives both "ac" and "ca". For n=3, can we have two distinct strings with the same set of proper prefixes and suffixes? Let's check: For n=3, we need length1: two strings (which could be same or different), length2: two strings. Suppose we have s1="aba", prefixes: "a","ab"; suffixes: "a","ba". So set: length1: {"a","a"} (two "a"); length2: {"ab","ba"}. Suppose s2="bab": prefixes: "b","ba"; suffixes: "b","ab". Set: length1: {"b","b"}? That's different. So not same set. s2="abc": set length1: {"a","c"}? Not same. s2="aaa": set: length1: {"a","a"}; length2: {"aa","aa"}. So for s1="aba", length2 set {"ab","ba"}; for s2="aab"? Let's find if any other s yields same multiset as s1. For s1="aba", length1 set has two "a". So any other s must have both first and last char 'a'. So s must be a? * a? Actually first char = a, last char = a. So s = a x a. Then length2 prefixes: "a" + x = "a"+x; suffix: x + "a" = x+"a". So set = {"ax", "xa"}. For s1, x='b', set={"ab","ba"}. For another s, say x='c', set={"ac","ca"}. Different. So not same. So for n=3, maybe no two distinct strings give same multiset except if uniform? For uniform "aaa", set: length1: {"a","a"}, length2: {"aa","aa"}. Could another string give same set? Need first and last char both 'a' to have length1 set {"a","a"}. And length2 set must be two "aa". That requires that both prefix2 and suffix2 be "aa". Prefix2 = s[0:2] must be "aa", so s[0]='a', s[1]='a'. Suffix2 = s[1:3] must be "aa", so s[1]='a', s[2]='a'. So s = "aaa". So unique. So no two distinct strings produce same set for n=3? But example 2 had "aaa" only, not two distinct strings. So both assignments produce same candidate (since both n-1 strings are same). So both assignments are essentially same.
For n=4, maybe there exist distinct strings with same multiset? Let's attempt to find: Suppose we have strings of length 4. The set of proper prefixes and suffixes consists of lengths 1,2,3 each two strings. Could there be two different strings s and t such that the multiset of their prefixes and suffixes are identical? Possibly if s and t are reverses? Let's test: s="abca", we computed set. t="acba"? Let's not dig. But it's possible that both assignments yield valid distinct candidates. In that case, our algorithm picks the first that works, which is fine.
Now, one more check: Could there be a scenario where the candidate constructed from prefix = a, suffix = b passes verification, but the candidate constructed from prefix = b, suffix = a also passes verification? That would mean both assignments yield a candidate that matches the given multiset. That implies there are two strings s1 and s2 consistent with the same input set. Then our algorithm will output based on the first successful candidate. That's allowed, as any answer is acceptable. So fine.
Now, ensure that we correctly handle cases where the two strings of length n-1 are such that both assignments produce candidate but those candidates differ. Example: n=2 with "a","c" we already saw. For n=2, our algorithm tries prefix=a, suffix=c -> candidate "ac", verification passes, so output "PS". That's acceptable. If we had swapped, output would be "SP". Since any is acceptable, "PS" is fine.
Now, consider n=2 and both strings same: "a","a". Then both assignments produce candidate "aa". Verification passes. We'll output "PS" (if first index gets P). That's acceptable.
Now, consider n=3 with strings: length1: "a","b"? Not possible from some s? Let's check if there exists s: first char and last char are a and b (order unknown). For s="abb": prefixes: "a","ab"; suffixes: "b","bb". Set length1: {"a","b"} good. length2: {"ab","bb"} not matching if given length2 are "ab","ba"? Actually we need to see if there is a case where both assignments work for n=3? That would require that the two length2 strings are such that both overlapping conditions hold. For n=3, length2 strings are of length 2. Let them be X and Y. We need both X[1] + Y[1]? Actually conditions: With prefix=X, suffix=Y, candidate = X + Y[1] (since Y length2, Y[-1] is second char). Condition for success: The suffix of candidate length2 must equal Y, i.e., X[1] + Y[1] = Y. That is X[1] = Y[0] and Y[1] is Y[1] obviously. So condition: X[1] == Y[0]. For the swapped assignment to also succeed, we need Y[1] == X[0]. So both conditions: X[1] == Y[0] and Y[1] == X[0]. That means X and Y are reverses of each other. For example X="ab", Y="ba". Then X[1]='b' == Y[0]='b', Y[1]='a' == X[0]='a'. So both assignments could be valid? Let's test: Input: length1 strings? For the whole set to be consistent, we need length1 strings as well. Let's attempt to find an s consistent with set: length1: two strings, must be the first and last characters of s. If both assignments are possible, that means there exist at least two s that produce the same multiset. Let's see if for n=3, with length2 strings "ab" and "ba", can we find s such that its prefix2 and suffix2 are these? For s, we have prefix2 = s[0:2], suffix2 = s[1:3]. For one s, we could have prefix2="ab", suffix2="ba". That would imply s[0]='a', s[1]='b', and from suffix2: s[1]='b', s[2]='a', so s="aba". For the other assignment, prefix2="ba", suffix2="ab" would give s[0]='b', s[1]='a', s[2]='b', so s="bab". So these are two possible strings. However, their sets of length1 strings are: for s="aba", length1: {"a","a"} (two 'a'); for s="bab", length1: {"b","b"} (two 'b'). So the overall sets differ. So to have the same input set (including length1 strings), the length1 strings must match both possibilities. For the set to be the same for both s, we would need length1 strings to be both "a" and "b" maybe? But each s gives two identical length1 strings because first and last char are same? Actually for s="aba", first='a', last='a', so both are 'a'. For s="bab", both are 'b'. So the multiset for length1 is two identical letters. So if the input set had length1 strings {"a","b"} (distinct), that would not match either s. So could there be an input set that is consistent with both s? That would require that the multiset of length1 strings is the same for both s. For s="aba", length1 multiset = {a,a}. For s="bab", = {b,b}. These are different unless a=b. So only if a=b, which would make both strings uniform, but then length2 strings would be "aa" and "aa", not "ab" and "ba". So no.
Thus for n=3, both assignments cannot both pass unless the length1 strings also match both. Since the input set is fixed, only one will pass. So fine.
Now, consider n=4. Could there be a scenario where both assignments produce valid s? Possibly if the length3 strings are such that both overlapping conditions hold AND the other lengths (1,2) also match both s. For both assignments to pass verification, the multiset of all lengths must be identical for both candidates. That means the input set would be consistent with two distinct strings. Example 3 for n=2 shows it's possible. Could it be for n=4? Let's try to construct: We need two strings s and t of length 4 such that the multisets of their proper prefixes and suffixes are identical. For n=2, we had s="ac", t="ca". For n=3, we didn't find. For n=4, maybe there is. Let's try to find such a pair. Condition: The set of length 1 strings must be {s[0], s[3]} for s, and also {t[0], t[3]}. For the multisets to be equal, either both have same multiset. If s[0] != s[3], then the multiset has two distinct chars. For t, to have same multiset, its first and last must be the same two chars (maybe swapped). So possible. For length 3, we need {s[0:3], s[1:4]} = {t[0:3], t[1:4]}. And for length 2, {s[0:2], s[2:4]}? Actually suffix2 = s[2:4]? Wait suffix of length 2 = last two chars = s[2:4]. So set for length2 is {s[0:2], s[2:4]}. For t, it must be same set. So we need to find s and t distinct satisfying these. This is reminiscent of the problem of string reconstruction from its prefixes and suffixes. It may be possible that two strings yield same set. Let's try to search manually: Let s = "abca". Then set: L1: {a,a}? Actually s[0]=a, s[3]=a => {a,a}. L2: prefix2="ab", suffix2="ca" => {ab, ca}. L3: prefix3="abc", suffix3="bca" => {abc, bca}. Now find t distinct such that set matches: For t, L1 must be {a,a} so t[0]=a, t[3]=a. L2 must be {ab, ca}. So t[0:2] and t[2:4] must be {ab, ca}. Since t[0]=a, t[0:2] must start with a, so possible assignments: either t[0:2] = ab and t[2:4] = ca, or t[0:2] = ca and t[2:4] = ab. But t[0:2]=ca would require t[0]=c, contradicting t[0]=a. So only t[0:2]=ab, t[2:4]=ca. Then t = ab + ca? t[0:2]=ab => t[0]=a, t[1]=b. t[2:4]=ca => t[2]=c, t[3]=a. So t = "abca", same as s. So unique.
Try s = "abcd". L1: {a,d}. L2: {ab, cd}. L3: {abc, bcd}. For t: L1 must be {a,d} => t[0]=a, t[3]=d. L2 must be {ab, cd}. Since t[0]=a, t[0:2] must start with a, so t[0:2]=ab, then t[2:4]=cd => t[2]=c, t[3]=d => t="abcd". Or if t[0:2]=cd, then t[0]=c contradict. So unique.
Try s = "acbd"? Let's see if we can get two. For both to be possible, we need that the two length3 strings are reverses of each other maybe? And the length2 strings also satisfy some condition. It seems maybe only n=2 yields ambiguous cases? Actually the problem statement's Note for first example says "The only string which Ivan can guess in the first example is 'ababa'." That suggests uniqueness for that case. Second example: "The only string which Ivan can guess in the second example is 'aaa'." So uniqueness there. Third example: ambiguous. So ambiguous case exists for n=2. Could there be ambiguous for n>2? Possibly but not needed. Our algorithm works regardless.
Now, we should also consider that the function try_assign uses by_len[L] which is a list of the two strings for that length. However, note that by_len[L] contains the strings in the order they were read. That's fine.
Now, confirm that after reading, we have exactly 2 strings per length. The problem guarantees that.
Now, one more potential nuance: The input lines may contain trailing spaces? We'll strip.
Now, coding.
We'll write solve() function.
Now, test with provided examples.
Example 1: Should output "SPPSPSPS". Our algorithm gave that.
Example 2: Should output "PPSS". Our algorithm gave that.
Example 3: Should output "PS". Our algorithm gave that.
Now, test with a custom case n=2, strings: "c", "c". Then output? Let's simulate: Input order: first "c", second "c". by_len[1] = ["c","c"]. try_assign("c","c") -> candidate="cc". Verification: len1 pref="c", suff="c", given=["c","c"] -> passes. Then indices_by_len[1] = [0,1], equal, assign index0 P, index1 S => "PS". That's acceptable.
Now, test n=2, strings: "a", "b". Output "PS" if order as read. That's fine.
Now, test n=3, strings: let's generate from s="aba". Input order could be: "a","ab","ba","a". Then by_len[2] = ["ab","ba"]? Actually order: suppose input: index0:"a", index1:"ab", index2:"ba", index3:"a". Then by_len[2] = ["ab","ba"]. Try assignment1: prefix="ab", suffix="ba" -> candidate="ab"+"a" = "aba". Verification: len1: pref="a", suff="a", given=["a","a"]? Actually by_len[1] would be ["a","a"] (index0 and index3) -> passes. len2: pref="ab", suff="ba", given=["ab","ba"] -> passes. So success. Then assignment: len1 equal -> assign first index (0) P, second index (3) S. len2 not equal -> index1 is "ab" matches pref => P; index2 is "ba" matches suff => S. Output: index0 P, index1 P, index2 S, index3 S => "PPSS". That's acceptable (similar to example2 but different strings). But note example2 had "aaa", but here it's "aba". Output "PPSS" is valid? For s="aba", correct assignment could also be other? Let's check: For s="aba", the prefix of length1 is "a", suffix1 is "a". So both length1 strings are "a". So we need to assign one P and one S. For length2, prefix2 is "ab", suffix2 is "ba". So assignment forced. So "PPSS" is a valid assignment (first "a" P, second "a" S). If input order is different, output might differ. So okay.
Now, consider scenario where by_len[L] order might affect assignment for unequal case? In unequal case, we assign based on which string equals pref. That will correctly assign P to the one that matches prefix. That is deterministic and correct.
Now, all good.
But we need to consider a potential pitfall: The function try_assign uses by_len[L] directly, but the order of strings in by_len[L] is the order they appear. However, when we later assign output using indices_by_len[L], we need to ensure that the mapping between the strings in by_len[L] and the indices is consistent. Since we built both simultaneously, by_len[L] contains strings in the order we appended, and indices_by_len[L] contains indices in the same order. So for a given length L, by_len[L][i] corresponds to inputs[indices_by_len[L][i]]. So in assignment step, we can use that mapping. But in our assignment code above, we used idx_list and then retrieved the strings via inputs[idx_list[0]][0] etc. That's fine.
Now, there is a simpler way: After we have candidate, we can just iterate over all input indices and assign based on candidate's prefix and suffix for that length, using the rule: if string equals prefix, then 'P'; else if equals suffix, then 'S'. For lengths where prefix == suffix, both equal, so we would assign both as 'P' if we use that rule? Actually if we naively do: for each i: if s_i == pref(L): result[i] = 'P' else if s_i == suff(L): result[i] = 'S', then for equal case both conditions are true, but we would assign 'P' to both (since the first condition matches). That would give two P's for that length, which is not allowed. So we need special handling for equal case. So we need to ensure exactly one P and one S. So we need to enforce distribution.
Our approach using indices_by_len ensures that.
Alternatively, we could keep a count per length and assign first occurrence as P if not assigned yet, else S. That would work even if we iterate all indices in order. Let's adopt that to be simpler: After candidate determined, initialize result = [''] * (2*n-2), and p_used = [False] * (n+1) (or a counter). For each index i from 0 to 2n-2:
s_i, L = inputs[i]
pref = cand[:L]
suff = cand[n-L:]
if pref != suff:
if s_i == pref:
result[i] = 'P'
else: # s_i == suff
result[i] = 'S'
else:
if not p_used[L]:
result[i] = 'P'
p_used[L] = True
else:
result[i] = 'S'
This works because for equal case, both strings will match pref, but we assign the first encountered as P, second as S. For unequal case, exactly one will match pref (since strings are distinct), and that one will be assigned P, the other S. Also p_used not needed for unequal case but we can still use; but the condition if pref != suff ensures we don't rely on p_used. This is simpler and avoids needing indices_by_len. So I'll implement that.
Now, final code:
def solve():
import sys
input_data = sys.stdin.read().splitlines()
# First line is n
n = int(input_data[0].strip())
lines = input_data[1:] # should have 2n-2 lines
# It might have empty lines? Probably not, but strip.
# Ensure we have exactly 2n-2 lines; if reading from sys.stdin.read() may include extra newline? But splitlines handles.
# However, some judges may have trailing spaces; but fine.
# We'll take the first 2n-2 lines after stripping.
strs = [line.strip() for line in lines[:2*n-2]]
code
# Group by length
by_len = [[] for _ in range(n)] # index length L
inputs = [] # list of (s, L)
for s in strs:
L = len(s)
inputs.append((s, L))
by_len[L].append(s)
a, b = by_len[n-1][0], by_len[n-1][1]
def check(prefix, suffix):
cand = prefix + suffix[-1] # string of length n
# verify all lengths
for L in range(1, n):
pref = cand[:L]
suff = cand[n-L:]
g = by_len[L] # list of two strings
if pref != suff:
if (g[0] == pref and g[1] == suff) or (g[0] == suff and g[1] == pref):
continue
else:
return False, None
else:
if g[0] == pref and g[1] == pref:
continue
else:
return False, None
return True, cand
ok, cand = check(a, b)
if not ok:
ok, cand = check(b, a)
# According to problem guarantee, ok should become True
# Now produce output
result = [''] * (2*n-2)
p_used = [False] * (n+1) # track if we have used P for this length
for i, (s_i, L) in enumerate(inputs):
pref = cand[:L]
suff = cand[n-L:]
if pref != suff:
if s_i == pref:
result[i] = 'P'
else:
result[i] = 'S'
else:
if not p_used[L]:
result[i] = 'P'
p_used[L] = True
else:
result[i] = 'S'
sys.stdout.write(''.join(result))
Now, test with examples.
Let's run through example1 manually with code.
n=5, inputs as before. by_len[4] gets ["abab","baba"]? Actually order: we need to see reading order: from the given input:
5
ba
a
abab
a
aba
baba
ab
aba
So by_len[4] will be: length 4 strings: "abab" (line3) and "baba" (line6) -> a="abab", b="baba". check(a,b): cand = "abab" + "baba"[-1] = "abab" + 'a' = "ababa". Verification passes. Then assignment as described yields "SPPSPSPS". Good.
Now, example2: n=3, inputs: "a","aa","aa","a". by_len[2] = ["aa","aa"] (first "aa" at line2? Actually lines: 1: "a", 2: "aa", 3: "aa", 4: "a". So by_len[2] = ["aa","aa"]. a="aa", b="aa". check(a,b): cand="aa"+"a" = "aaa". Verification passes. Then assignment: indices: 0 L1, 1 L2, 2 L2, 3 L1. For L1: pref="a", suff="a" equal, p_used[1] initially false -> index0 gets P, then p_used[1]=True; index3 later gets S. For L2: pref="aa", suff="aa" equal, p_used[2] initially false -> index1 gets P, then p_used[2]=True; index2 gets S. Output: P P S S -> "PPSS". Good.
Example3: n=2, inputs: "a","c". by_len[1] = ["a","c"]. a="a", b="c". check(a,b): cand = "a"+"c"[-1] = "a"+"c" = "ac". Verification: L=1: pref="a", suff="c", g=["a","c"] -> matches (pref != suff, g[0]==pref, g[1]==suff) -> passes. So ok. Assignment: For each index: i0 L1, pref="a", suff="c", not equal. s_i = "a" -> equals pref => P. i1 -> equals suff => S. Output "PS". Good.
Now, consider scenario where check(b,a) is the one that passes. That'll work.
Now, edge case: n=100, strings. Should be fine.
Now, is there any scenario where our verification fails because by_len[L] order may cause false negative? For example, if pref != suff but the given strings are in the opposite order relative to our condition check: we check (g[0]==pref and g[1]==suff) or (g[0]==suff and g[1]==pref). That's correct.
Now, think about possibility that for some L, pref == suff but the given strings are in some order; we check both equal to pref. That's correct.
Now, one more nuance: The candidate we constructed uses prefix + suffix[-1]. But what if the suffix string is of length n-1, but its last character might be ambiguous if the string contains newline? Not relevant.
Now, potential bug: When n=2, suffix[-1] is the only character, and candidate = prefix + that character. That's fine.
Now, could there be a situation where the candidate constructed is of length n but the suffix we computed for L=n-1 is not equal to the given suffix, yet the verification passes because the set condition might still be satisfied if pref and suff are swapped? But for L=n-1, set condition: if pref != suff, then the given strings must be {pref, suff}. Our candidate's pref is prefix (by construction), suff is something. For the set to be {pref, suff} where suff is the given suffix, we need that the given set contains both pref and suff. But if our candidate's suff is not equal to the given suffix, but by some coincidence, the other given string equals candidate's suff? Let's examine: Suppose we assign prefix = A, suffix = B. Build candidate = A + B[-1]. Compute pref_n1 = A, suff_n1 = A[1:] + B[-1]. The given strings for L=n-1 are A and B. For verification to pass, we need {pref_n1, suff_n1} = {A, B}. Since pref_n1 = A, we need suff_n1 = B. So indeed it forces that condition. If suff_n1 != B, then the set would be {A, suff_n1} which is not {A, B} unless B == suff_n1. So verification fails. Good.
Now, ensure that we are using the same by_len in check as later. Since by_len is not modified, fine.
Now, about reading input: using sys.stdin.read().splitlines() is fine. But note that there may be blank lines? Usually not. However, the input format says the next 2n-2 lines contain strings. So after reading n, we expect exactly 2n-2 lines. But when using read().splitlines(), if there is an extra newline at the end, it may produce an empty string at the end? For safety, we could use sys.stdin.readline() in a loop. But using splitlines and then taking first 2n-2 non-empty? However, if there is trailing newline, splitlines will not include an empty line for the trailing newline? Actually "abc\n".splitlines() -> ["abc"]; "abc\n\n".splitlines() -> ["abc", ""]? Actually if there is an empty line at end, it could include it. To be robust, we can read line by line using for _ in range(2n-2): s = sys.stdin.readline().strip(). That's simpler.
We'll implement with sys.stdin.readline.
Plan:
import sys
def solve():
import sys
n_line = sys.stdin.readline()
while n_line.strip() == '':
n_line = sys.stdin.readline()
n = int(n_line.strip())
inputs = []
by_len = [[] for _ in range(n)]
for _ in range(2*n-2):
s = sys.stdin.readline().strip()
L = len(s)
inputs.append((s, L))
by_len[L].append(s)
# proceed as before
Now, we also need to ensure that we don't have any off-by-one: by_len is list of length n, but we use index L (1 <= L <= n-1). So by_len[L] exists. That's fine.
Now, final code.
But before finalizing, let's think about the possibility that the candidate construction might be ambiguous if the two n-1 strings are same: prefix = A, suffix = A, candidate = A + A[-1] = A + last char of A. That yields a string of length n with the first n-1 characters being A, last char being the last char of A again. That is a uniform string only if A is uniform? Actually if A is any string, then candidate = A + A[-1]. For example, if A = "abc", candidate = "abcc". But is that a valid s for the case where the two n-1 strings are identical? The true s must have prefix and suffix both equal to A. If both are A, then s[0..n-2] = A and s[1..n-1] = A. This implies that s[0]=s[1], s[1]=s[2], ..., s[n-2]=s[n-1] and also s[0..n-2]=A, so A must be of form cccc? Let's solve: s[0..n-2]=A, s[1..n-1]=A. Then s[0]=A[0], s[1]=A[1],..., s[n-2]=A[n-2]. Also from s[1..n-1]=A, we have s[1]=A[0], s[2]=A[1],..., s[n-1]=A[n-2]. So we have A[1] = s[1] = A[0]; A[2] = s[2] = A[1]; ...; and also s[n-1] = A[n-2]. So A[1] = A[0], A[2] = A[1] = A[0], ..., A[n-2] = A[0]. So all characters of A are same. So A is uniform. And s = A + A[-1] = c^{n-1} + c = c^n, which is uniform. So our candidate "abcc" would not satisfy the condition s[1..n-1]=A because s[1..3] = "bcc", not "abc". So verification would fail. But our check will catch that because for length n-1, pref = candidate[:n-1] = A, suff = candidate[1:] = A[1:] + A[-1] (since candidate = A + A[-1]), which is not equal to A unless A is uniform. Since by_len[n-1] contains two copies of A, verification requires that both given strings (both A) equal pref and suff? Actually condition: pref != suff? If A is not uniform, pref != suff. Then given strings are both A, but we need set {pref, suff} = {A, A}? That would require pref = A and suff = A, which fails because pref = A, suff != A. So verification fails. So we will try the other assignment (which is the same). So both fail? But the problem guarantees that there is some string s consistent with the input. So if the input has two identical n-1 strings, that forces A to be uniform, and thus the true s is uniform. So the given set must also have uniform prefixes/suffixes for all lengths. So indeed the candidate built from uniform A (e.g., A="aaa") would pass. So if the input erroneously gave two identical n-1 strings but not uniform? That would violate the guarantee that these strings are prefixes and suffixes of some existing string. So it won't happen. So our check is safe.
Now, confirm that in case both n-1 strings are identical and uniform, candidate = A + A[-1] will produce a uniform string (since A uniform). For A="aaa", candidate="aaaa". Verification: For L=3 (n-1=3), pref="aaa", suff="aaa" (since candidate[1:] = "aaa"? Actually candidate="aaaa", n=4? Wait n length? For n=4, n-1=3, A="aaa". candidate = "aaa"+"a" = "aaaa". Then pref3="aaa", suff3 = candidate[1:4] = "aaa". So pref==suff. Given both are "aaa". So passes. Good.
Thus all good.
Now, complexity O(n^2) fine.
Now, let's produce final answer.
One more thing: The output string must be of length 2n-2. We'll ensure join.
Now, testing with some random data. We can also write a quick check in mind.
Now, code is ready.
We should also consider the case where the input strings may have leading/trailing spaces. We'll strip.
Now, final answer.
Now, possible improvements: none needed.
Now, I'll write final solution explanation and code.
But before finalizing, re-read problem statement: "It is guaranteed that there are exactly 2 strings of each length from 1 to n-1. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length n." So our approach is correct.
Now, let's produce final answer. ```python
import sys
def solve() -> None:
n_line = sys.stdin.readline()
while n_line.strip() == '':
n_line = sys.stdin.readline()
n = int(n_line.strip())
code
# store input strings together with their lengths
inputs = [] # list of (string, length)
by_len = [[] for _ in range(n)] # by_len[L] -> list of two strings of length L (1 ≤ L ≤ n-1)
for _ in range(2 * n - 2):
s = sys.stdin.readline().strip()
L = len(s)
inputs.append((s, L))
by_len[L].append(s)
# the two strings of length n-1
a, b = by_len[n-1][0], by_len[n-1][1]
# try to build a candidate string assuming 'prefix' = first, 'suffix' = second
def check(prefix: str, suffix: str):
"""return (True, candidate) if the assignment works, else (False, None)"""
cand = prefix + suffix[-1] # length n
# verify all lengths
for L in range(1, n):
pref = cand[:L]
suff = cand[n-L:]
g = by_len[L] # the two given strings of this length
if pref != suff:
if (g[0] == pref and g[1] == suff) or (g[0] == suff and g[1] == pref):
continue
else:
return False, None
else: # pref == suff
if g[0] == pref and g[1] == pref:
continue
else:
return False, None
return True, cand
ok, cand = check(a, b)
if not ok:
ok, cand = check(b, a)
# according to the problem guarantee, at least one will succeed
# produce answer
res = [''] * (2 * n - 2)
p_used = [False] * (n + 1) # for equal prefix/suffix we assign only one 'P' per length
for i, (s, L) in enumerate(inputs):
pref = cand[:L]
suff = cand[n-L:]
if pref != suff:
if s == pref:
res[i] = 'P'
else: # must be the suffix
res[i] = 'S'
else: # prefix == suffix
if not p_used[L]:
res[i] = 'P'
p_used[L] = True
else:
res[i] = 'S'
sys.stdout.write(''.join(res))