We need to understand the problem: There are n participants, each from region 1..m. Each region has at least two participants. For each region, we need to form a team of two people such that the team satisfies the property: "none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points." This means: For each member in the team, there is no other participant from the same region with higher points who is not on the team, such that if we replace that member with that higher-scoring participant, we would still have a valid team? Wait, the description: "The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points." It means that if we take any member of the team, there is no other participant from the same region not in the team who has higher points than that member. In other words, both team members must be the top (or among the top) in the region, such that no one with higher points is left out. But since the team size is exactly 2, this condition implies something like: The team must consist of the two highest-scoring participants? Let's think.
Suppose we have scores for region i sorted descending: s1 >= s2 >= s3 >= ... >= sk (k>=2). Consider a team (a,b) of two distinct participants. The condition: For each of a and b, there is no other participant from same region not in the team with higher points. That means that if a's score is Sa, there is no participant not in team with score > Sa. Similarly for b. So both a and b must be such that all participants with scores strictly greater than their scores are either themselves or the other member? But since there are only two members, it implies that the set of participants not in the team cannot contain anyone with score > min(Sa, Sb) because if, say, Sa is the lower score, then a is the lower one; then someone with higher score than a but not in team would violate condition for a. Actually condition applies individually: For each team member, we require that no other participant from the region not in the team has a higher score than that member. So consider the team with members X and Y. Let their scores be x and y. For member X, any participant Z not in {X,Y} must have score <= x. Similarly, any Z not in {X,Y} must have score <= y.
Thus all participants not in the team must have scores <= min(x, y)? Wait, if x <= y, then for X (lower) we require all others <= x, which is stricter; for Y (higher) we require all others <= y. The condition for X (the lower) is stronger: if all others <= x, then automatically they are <= y because x <= y? Actually if x <= y, condition for X ensures all other participants' scores <= x <= y, so condition for Y also holds. Conversely, if y < x, condition for Y ensures all others <= y. So essentially, the condition reduces to: Let the two team members' scores be a and b. Without loss, assume a <= b. Then we require that all other participants from that region have scores <= a. In other words, the lowest-scoring team member must have a score that is at least as high as the scores of all non-team participants. Or put differently, the two chosen participants must be the two highest-scoring participants, but careful: What if there are ties? If there are multiple participants with the same high score, conditions might allow multiple teams.
Let's consider examples. Example 2: Region 1: participants Ivanov (800), Petrov (800), Sidorov (800). All three have 800. Condition: For any team of two, say (Ivanov, Petrov). For member Ivanov (score 800), there is no non-team member (Sidorov) with higher score? Score 800 is not higher (equal). So condition says: "not included in the team and who received a greater number of points." It says greater number, strictly greater. So if the non-team participant also has 800, that's not greater, so condition is not violated. Similarly for Petrov. So the team (Ivanov, Petrov) satisfies condition because all non-team participants have score <= each team member? Actually check: For member Ivanov, we need that no non-team member has score > 800. The only non-team member (Sidorov) has 800, which is not >800, so ok. So the condition holds. Similarly, any pair of these three would satisfy the condition. Thus the team is not uniquely determined; there are 3 possible teams. So we output ?.
Now consider scenario where there are two distinct top scores and a lower third. Suppose scores: 800, 790, 600. For team (800,790): For member with 790, non-team (600) <= 790, ok. For member with 800, non-team (600) <= 800, ok. So condition holds. For team (800,600): For member with 600, non-team (790) > 600, violates condition (since there is a non-team member with greater points than 600). So not allowed. For team (790,600): similar violation because non-team (800) > 600. So only (800,790) is valid. So uniquely determined.
What about scores: 800, 800, 790? Team (800,800): non-team (790) <= 800? Actually for member with 800, non-team has 790 which is not >800, so ok. So valid. Team (800,790): For member with 790, non-team (800) > 790, violates condition. So invalid. Team (800,790) other ordering similarly. So only (800,800) valid. So unique.
Scores: 800, 800, 800, 700: Top three 800, one 700. Teams: Any two of the three 800's: For any 800 member, non-team participants: the third 800 and the 700. The third 800 has score equal to 800 (not >800), 700 is less, so condition holds. So any pair of 800's is valid. What about team (800,700): For member 700, non-team includes two 800's which are >700, so invalid. So many teams: number of ways to pick two of the three 800's = 3. So not unique.
Scores: 800, 800, 800, 800 (four 800): Then any pair works, because for any team member, non-team participants also have 800 which is not greater. So many teams. Not unique.
So uniqueness condition: The team is uniquely determined if and only if there is exactly one pair (two participants) that satisfy condition. That will happen when the top two scores are strictly greater than the third highest score, and also the first two are not tied? Wait, if top two are distinct but second equals third? Example: scores: 800, 790, 790. Let's test: participants: A:800, B:790, C:790. Consider team (800, B). For member B (790), non-team includes C (790) which is not greater than 790? Actually 790 is not > 790, so condition holds. For member 800, it's fine. So (800, B) valid. Team (800, C) similarly valid. Team (B, C): For member B (790), non-team includes A (800) which is > 790, so invalid. So two valid teams: (800,B) and (800,C). So not unique. So uniqueness requires that the second highest score be strictly greater than the third highest. But also what about ties for first? If top two are tied, then there might be multiple valid teams if there are at least two people with that top score? Let's examine: top scores: first = 800, second = 800, third = 700. Then any two of the top-score participants (who have 800) are valid. If there are exactly two participants with 800, then only one pair (the two 800s) is valid; that would be unique. Wait, need to consider: Suppose region has exactly two participants? Then team is forced (the only two). But if there are more, condition: If there are exactly two participants with the maximum score (800) and a third lower (700), then consider team of the two 800s: valid. Could there be another valid team? (800,700) invalid because 700 sees 800 >. So only one. So uniqueness holds. But if there are three or more with the maximum score, then multiple pairs among those max scorers are possible. So uniqueness condition: The valid teams are exactly those that consist of two participants from the set of participants whose scores are strictly greater than the score of any participant not in the team? Let's formalize.
We need to characterize the set of pairs (i,j) (distinct) such that for every other participant k from same region, score(k) <= min(score(i), score(j))? Actually from earlier: With ordering: assume s_i <= s_j, then condition is that all other participants have scores <= s_i. So the condition is: The minimum of the two selected scores must be >= the maximum score among the other participants (those not selected). More precisely: Let a = min(score(p1), score(p2)), b = max(...). Then require a >= max_{k not in team} score(k). If a is strictly greater than the maximum of non-team, condition holds. If equal? If a equals the maximum of non-team, then for the team member with score = a (the lower one), there exists a non-team participant with score = a, but that's not strictly greater, so condition holds. So condition is: min(score(p1), score(p2)) >= max_{k not in team} score(k). Actually careful: It needs to be that for the lower-scoring member, no non-team participant has a strictly higher score. So if there is a non-team participant with score equal to the lower member's score, that's fine. So the condition is: minScore(team) >= maxScore(non-team)? Let's test: team (800,800), min=800, non-team max=800, condition: min >= max? 800>=800 true, but need >? No, equal is okay. So condition is minScore >= maxScore(non-team). Actually if minScore > maxScore, fine. If equal, still fine because no strictly higher. So indeed condition is min(team) >= max(other).
Therefore, for a region with participants sorted descending: s1 >= s2 >= s3 >= ... >= sk (k>=2). A pair (i,j) is valid iff the smaller of their scores is at least the maximum score among the participants not chosen. That maximum among the not chosen depends on which two are chosen.
If we choose participants with ranks (by descending order) p and q (p<q in sorted list, where p and q are indices in sorted list from 1 to k), then the set of not chosen includes all except those two. The maximum among not chosen is either s1 if we didn't pick the top, or s2 if we picked the top but not the second, etc. More formally: The maximum score among the not chosen is the maximum among the scores of participants not in the team. Since scores are sorted descending, the maximum not chosen will be:
- If we pick the top participant (s1) and some other participant, then the not chosen set includes s2 (unless we also pick s2) and others. So the max not chosen is s2 if we didn't pick s2, else s3 if we picked both s1 and s2, then max not chosen is s3.
In general, if we pick two participants from the sorted list, the max not chosen is the highest score among those not selected, which is the first score in the sorted list that is not selected. So if we select the top two (s1 and s2), then max not chosen = s3 (if exists, else if k=2, there are no other participants, then the condition vacuously holds because there is no non-team participant to violate; we can treat max not chosen as -infinity). If we select s1 and s3 (skipping s2), then max not chosen = s2 (since s2 is not selected). If we select s2 and s3, then max not chosen = s1.
Now condition minScore(team) >= max not chosen.
Let team members have scores a and b, with a <= b. Then we need a >= M where M = max(score of participants not selected). This condition eliminates many pairs.
Let's list possibilities based on sorted scores:
Let k be number of participants in region.
Case k=2: only one pair, always valid, unique.
Case k>=3:
We need to find all pairs (i,j) with i<j (indices in sorted order) such that if we pick participants at positions i and j (1-indexed descending), then let minScore = s_j (since j>i, s_j <= s_i). Then M = maximum among not selected = the highest score among those not i and j. This will be:
- If i=1, j=2: then M = s3 if exists (k>=3), else no other; so condition: s2 >= s3? Actually min = s2, need s2 >= s3. So pair (1,2) valid iff s2 >= s3. But s2 >= s3 always holds because sorted descending? Actually s2 >= s3 is true by definition (s2 >= s3). So condition always holds? Wait, condition is s_j >= M. For (1,2): min = s2, M = s3. Since s2 >= s3, condition holds. So (1,2) is always valid (given at least 3 participants). But check example: scores 800, 790, 600. s2=790 >= s3=600, ok. (1,2) valid. Yes. So top two always valid? Let's test with ties: 800,800,800: s2=800, s3=800, condition s2 >= s3 holds (800>=800). (1,2) valid, yes. So always valid.
Now consider (1,3): Here we pick s1 and s3. min = s3, M = s2 (since s2 is not selected). Condition: s3 >= s2. Since sorted descending, s3 <= s2. For this to hold we need s3 == s2 (equal). If s3 < s2, then condition fails. So (1,3) is valid only if s3 == s2. Similarly, (1,j) for j>=3: min = s_j, M = s2 (since s2 is the highest not selected if s1 is selected and s2 not; if we also skip s2? Actually if j>2, we select s1 and s_j. The not selected set includes s2, s3,..., except s_j. The highest among those is s2. So condition: s_j >= s2. Since s_j <= s2, this requires s_j == s2. But if s_j == s2, then s2 = s_j, but also s2 is included among not selected? Wait careful: If we pick s1 and s_j, and j>2, then s2 is not selected unless j=2. So the maximum among not selected is s2. So for (1,j) to be valid, we need s_j >= s2. Given sorted descending, s_j <= s2. So equality must hold: s_j == s2. But if s_j == s2, then that means s2 = s_j, i.e., there is a tie for second? Actually if s2 = s3 = ... = s_j = some value, then picking any j with that value, condition becomes s_j (equal to that value) >= s2 (same value). So holds. However, if we pick s1 and s_j where s_j = s2, then s2 is not selected but has same score as s_j. Then the condition s_j >= s2 holds as equality. So (1,j) valid when s_j == s2. But note that if s_j == s2 but j>2, then s2 (which is at index 2) has the same score. So there exists at least one other participant with same score as s_j that is not selected (specifically s2). That's allowed because equality is fine. So yes, (1,j) can be valid if all scores from index 2 to j are equal? Actually need s_j >= s2. Since s_j <= s2, equality needed. So s_j must equal s2. So if s2 = s3 = ... = s_j, then for each such j, (1,j) valid. But if s2 > s3, then only (1,2) valid among pairs involving the top.
Now consider pairs not involving the top, e.g., (2,3): pick s2 and s3. min = s3, M = s1 (since s1 is not selected). Condition: s3 >= s1. Since s3 <= s1, only possible if s3 == s1, which would imply all scores equal? Actually if s3 == s1, then s1 = s2 = s3 (since sorted). So (2,3) valid only if all three equal. In general, any pair that does not include the top score: then max not selected will be s1 (unless we also exclude s1? Actually if neither i nor j is index 1, then s1 is not selected, so M = s1). Condition: min(s_i, s_j) >= s1. Since min <= s1, equality must hold, so min = s1 => all scores equal. So such pairs are valid only if all scores are equal. Similarly, for pairs not including the top two? Actually any pair that excludes s1 will have M = s1, so requires min >= s1, implying s_i = s_j = s1. So all participants must have the same score.
What about pairs that include the top but also other selections? Already considered (1,j). Also pairs (i,j) where i>1 and j>1, both not top, invalid unless all equal.
Also possible pairs that include s2 but not s1? That's (2, j) with j>2. Then M = s1 (since s1 not selected). Condition: min(s2, s_j) >= s1. Since s2 <= s1, need equality. So again all equal.
Thus, summarizing:
Given sorted descending scores s1 >= s2 >= s3 >= ... >= sk.
The valid teams are:
-
The pair of the top two (s1, s2) always valid.
-
Additionally, any pair that includes s1 and any participant with score equal to s2 (i.e., any participant whose score is the same as the second highest) is also valid, provided that participant is not s2? Actually if s2 itself, that's the top two pair, already counted. If there are multiple participants with score equal to s2 (i.e., s2 = s3 = ... = s_t for some t >= 3, where s_{t+1} < s2 or t = k), then for any j in [2, t], pair (1, j) is valid. Also, what about pairs that include s1 and someone with score < s2? Those are invalid because condition fails (s_j < s2 => s_j < M (since M=s2) => s_j >= s2 fails). So only those with s_j == s2.
-
Additionally, if all scores are equal (s1 = s2 = ... = sk), then any pair of two participants is valid. This includes pairs not involving the top. But note that in this case, the condition that includes s1 and any with equal score already covers pairs (1, j) for all j; but also pairs like (2,3) become valid because M = s1 = score, and min = score >= score holds. So indeed all pairs are valid.
But careful: In the all-equal case, the set of valid teams includes all C(k,2) pairs. So there can be multiple.
Now, the condition for uniqueness: There must be exactly one valid pair.
So when does that happen? Let's analyze.
We have k >= 2 participants per region.
Case k = 2: exactly one pair -> unique.
Case k >= 3:
We have always at least one valid pair: (1,2). If there is any other valid pair, then the team is not uniquely determined. So uniqueness requires that the only valid pair is (1,2).
Thus we need to check:
-
Are there any other pairs (1, j) for j>=3 that are valid? That happens when s_j == s2. So if there exists any participant with score equal to s2 besides the one at index 2? That is, if s3 == s2, then (1,3) is valid, and possibly more. So uniqueness requires s2 > s3 (strictly greater). i.e., the second highest score is strictly greater than the third highest.
-
Also, need to ensure that no other type of pair (i,j) with i>1, j>1) is valid. That would be a pair not including s1. When could such a pair be valid? Only if all scores are equal, as argued. But if all scores equal, then obviously s2 = s3, violating the previous condition. Also, if all equal, then there are many pairs. So the condition s2 > s3 should already exclude the all-equal case (since if all equal, s2 = s3). However, there is a special case: what if k=3 and s2 > s3, then (2,3) is not valid because s3 < s2 <= s1, and M = s1 > s3, so invalid. So okay.
But also consider the possibility that there is a tie for first and second? That is, s1 = s2 but s2 > s3? That's possible: e.g., scores 800,800,790. Then s1 = s2 = 800, s3 = 790. s2 > s3 (800 > 790). According to our earlier analysis, the valid pairs: (1,2) is valid (the two top). (1,3): min = s3=790, M = s2=800, 790 >= 800? No, fails. (1,3) invalid. (2,3): min=790, M=s1=800 fails. So only (1,2) is valid. Is that true? Check condition: For team (800,800), both members have 800, non-team participant (790) is not > 800, so condition holds. Are there any other valid teams? Could there be a team of (first 800, third 790)? For member 790, non-team includes the other 800 which is > 790, so invalid. So only one team. So yes, unique. So condition for uniqueness is: the two highest scores (after considering ties) must be such that the second highest score is strictly greater than the third highest, but it doesn't matter if first and second are equal? Let's test: s1 = s2, s2 > s3 => unique? Yes, we saw unique. But wait, what if there are more than two participants with the top score? That is, s1 = s2 = s3? Then s3 equals s2, so s2 is not > s3 (they are equal). So condition fails, and there are multiple pairs among those three top participants. So indeed condition is s2 > s3 (i.e., the second highest score is strictly greater than the third highest). Note that if there are exactly two participants (k=2), there is no s3; we can treat as vacuously s2 > s3? But k=2 is separate.
Thus algorithm per region: gather all participants, sort by score descending, break ties arbitrarily? For uniqueness we need to know the second highest and third highest scores. Actually we need to compare s2 and s3. But careful: There might be multiple participants with the same score. The condition s2 > s3 is equivalent to: there are at most two participants with score >= s2? Actually s2 is the second highest score. If s2 > s3, it means that there is at most one participant (the top) with score greater than s2? Actually s1 >= s2 > s3, so s2 is strictly greater than all scores after the second. It also allows s1 = s2 or s1 > s2. So there are exactly either 1 or 2 participants with scores >= s2? Actually if s1 > s2, then s1 > s2 > s3, so exactly one participant (top) has score > s2, and exactly one has score = s2 (the second). If s1 = s2, then there are at least two participants with score = s2 (since s1 and s2), but could be exactly two? If s1 = s2 > s3, then exactly two participants have score = s2 (or greater? They are equal). But if there are more than two with score = s2, that would mean s3 = s2, contradicting s2 > s3. So indeed if s1 = s2 > s3, there are exactly two participants with the top score (which equals s2). So in both cases, the set of participants with score >= s2 is exactly two individuals: the top two positions. Because if s1 > s2, then participants with score >= s2: includes s1 and s2 (since s1 > s2, s1 >= s2). If s1 = s2 > s3, then participants with score >= s2 are exactly those with score = s1 = s2, which are at least two. But if there were three with score = s2, then s3 = s2, contradiction. So exactly two. So we can rephrase: The team is uniquely determined if and only if there are exactly two participants whose scores are at least the second highest score? More straightforward: The team is uniquely determined if and only if the number of participants with the maximum score is either 1 or 2? Let's test.
Case: Maximum score appears 1 time (s1 > s2 > ...). Then s2 is the second highest, unique. s2 > s3 likely holds? It might be that s2 = s3 if there is tie for second? But if max appears once, s2 might equal s3 if there are multiple with second highest score. Example: scores 800, 790, 790. Here max appears once, but s2 = s3 = 790. Then s2 > s3? No, they are equal. So the team is not uniquely determined as we saw earlier (two valid teams: (800,790) with either of the two 790s). So uniqueness fails. So the condition is not just about max count. The condition is that the second highest score must be strictly greater than the third highest. That is equivalent to saying that the second highest score is unique (i.e., appears exactly once) and also that there is no tie for second place. And also if the max appears more than once? If max appears twice (800,800,790): s1 = s2 = 800, s3 = 790, then s2 > s3, uniqueness holds. So max count 2 with s2 unique? Actually s2 is 800, but there are two with that score, but s2 is not unique; however, because s3 is lower, the condition s2 > s3 holds. So the condition is about comparison between s2 and s3, not about uniqueness of s2.
Thus algorithm: For each region, we need to:
- Collect participants (surname, score).
- Sort participants by score descending.
- Determine s2 and s3 (if exist).
- If number of participants in region = 2: output the two surnames (any order). Unique.
- Else (k>=3):
- Let scores sorted: scores[0] >= scores[1] >= scores[2] >= ...
- If scores[1] > scores[2]: then unique team is the two participants corresponding to the top two scores (positions 0 and 1). Output their surnames.
- Else (scores[1] == scores[2] or possibly if k=3? Actually if k>=3 and scores[1] == scores[2], then not unique, output "?".
But careful: Is it possible that scores[1] > scores[2] but there are other participants with same score as scores[1]? That would mean scores[1] = scores[2] because if there is another participant with score equal to scores[1], then that participant would be at index 2 or earlier? Since sorted descending, if scores[1] is the second highest, and there is another participant with same score, then that participant would have index 2 (or maybe index 1 if there are ties? Actually sorted descending, if there are multiple with same score, they occupy consecutive positions. So if scores[1] > scores[2], that means the score at index 2 is strictly less, so there is no other participant with score equal to scores[1] except possibly the first if equal? But if s1 = s2, then scores[0] = scores[1]. In that case scores[1] could be equal to scores[0] but scores[2] is lower. So scores[1] > scores[2] is true. So condition holds.
Edge case: What if k=3 and scores[1] == scores[2]? Then not unique. If k>3 and scores[1] == scores[2] but scores[2] > scores[3]? Actually if scores[1]==scores[2], then we have at least two participants with the second-highest score (including possibly the first if equal). But then we have at least three participants with score >= scores[2]? Let's analyze: If scores[1]==scores[2], then the second highest score appears at least twice. Then there exists at least a tie for second. That violates s2 > s3 because s3 = scores[2]? Actually s3 = scores[2] (since index 2 is third). So s2 = scores[1] == scores[2] = s3, so s2 is not > s3. So condition fails, output "?".
What about scenario where k>=3 but there are exactly two participants with the maximum score, but also there is a tie for second? That's impossible because if there are exactly two with max, then the second highest is max? Actually if there are exactly two max, then s1=s2=max, and s3 < max. So s2 > s3. That's unique. If there are three max? then s1=s2=s3, so not unique.
Thus algorithm seems correct.
But we must also consider the case where there are more participants but s2 > s3, but maybe some other pair like (1,3) becomes valid because s3 == s2? No because s3 < s2, so (1,3) invalid. And pairs not including top are invalid because they'd have M = s1, and min = something <= s1, but could be equal if all equal; but since s2 > s3, not all equal. So only (1,2) valid.
Thus answer per region:
-
If s2 > s3 (or region has exactly two participants): output surnames of participants with the two highest scores (the top two). If there are ties for first? If s1 = s2, output those two (any two among the top scores? But if s1 = s2 > s3, there are exactly two participants with that top score, so they are the top two. So we just output those two (the two highest-scoring participants). But careful: If s1 = s2 > s3 but there are exactly two participants with top score? That's fine. But if there are more than two with top score? That would be s3 also equal, so s2 > s3 fails. So indeed only two participants have top score. So just pick the two highest positions.
-
Else: output "?".
But one more nuance: What if the region has exactly two participants? Then output their names. This fits: we don't need to check s2 > s3 because no s3.
So the problem reduces to: For each region, we need to know the top two scores and the third highest score if exists, to compare. But also we need the surnames of the top two participants to output if unique. And if not unique, output "?".
Constraints: n up to 100k, m up to 10k. So total participants n. We can group participants by region. For each region, we need to find the top three scores (by value) and corresponding participants. Since each region may have many participants, but total across all regions is n. So we can iterate over all participants, add to region's list, and after reading all, for each region we need to find the top three scores. However, we also need to output surnames. So we need to store the participants per region. Since m up to 10k, and n up to 100k, we can store vectors per region.
We must consider that the scores range 0-800, but we still need to sort or find top three. For each region, we could sort its participants by score descending (and maybe by name? not needed). But sorting all participants globally or per region? Since each region could have many participants (worst case: n=100k, m=1, then one region with 100k participants). Sorting each region individually would total O(n log n) if we sort each, but if we sort each region separately, the sum of sizes across regions is n, and sorting each region individually could lead to total O(n log n) overall if we sort each region; but the sum of (size_i log size_i) can be larger than n log n? Actually by convexity, maximum sum when one region has all n: that's O(n log n). So total O(n log n) is fine for n=100k. But we can also find top three without full sort by scanning and keeping top three scores with names. That would be O(n) per region? Actually scanning all participants once per region would be O(n) total if we process all participants and update per region top scores. That's better: O(n) overall. Since we only need top three (or top two) and compare third, we can maintain for each region a small structure: the top three scores and the corresponding surnames (maybe multiple names for ties? Actually we need to know if there is a tie for second or third. For comparing s2 > s3, we need the actual scores. Also to output the two participants if unique, we need the two highest-scoring participants. But careful: If there is a tie at top? For unique case, s1 and s2 may be tied? Actually s1 may equal s2, but we said unique if s2 > s3. In that case, the two highest are the ones we output. If there is a tie at top and s2 > s3, then there are exactly two participants with the top score? Let's check: Suppose s1 = s2 = 800, s3 = 790. Then the two highest are the two participants with score 800. But there could be multiple participants with score 800? If there are three participants with 800, then s3 = 800, so s2 is not > s3. So the case s1 = s2 > s3 implies exactly two participants have the top score. So the top two positions are uniquely determined participants (the two that have the maximum score). However, what if s1 > s2 > s3, then the top two are unique as well. So in either unique case, the two participants to output are uniquely identified: they are the two highest-scoring participants. But note: If there is a tie for second? That is s1 > s2 = s3, then not unique, so we output "?". So we don't need to worry about which two to output in unique case because they are uniquely determined: the ones with the highest and second highest scores (there cannot be a tie for second if unique). Actually could there be a tie for second but still unique? That would be s1 > s2 = s3, but s2 = s3 so s2 is not > s3, so condition fails, so not unique. So indeed unique case has strictly s2 > s3, so the second highest score is unique. However, the top score might be tied with the second? If s1 = s2 > s3, then the second highest is not unique? Actually there are two participants with the same score s2, but that's okay because s2 > s3; the second highest score as a value is s2, but there are two participants with that score. But the two participants to output are those two (both with s2). That's fine because they are the two highest; even though both have same score, they are the only ones at that top level. So we need to output the two participants that are the top two in the sorted order; they are uniquely determined as the participants with the maximum score (since there are exactly two such participants). So we need to know which participants those are.
Thus for each region, we need to be able to retrieve the two participants with the highest scores, and also know the third highest score to compare.
We can process participants one by one: For each region, we maintain the best (top) scores and the corresponding surnames. Since we need top three, we can keep a list of up to three best distinct scores? But careful: We need to know the third highest score value, but if there are multiple participants with same score, the "third highest" might be same as second if there are many ties. For example, region has participants with scores: 800, 800, 800. Then s2 = 800, s3 = 800, so we need to detect that s2 == s3 to output ?. So we need to know not just top three scores but also the number of participants at those scores. Essentially, we need to know for each region:
- The highest score (max)
- The second highest score: which is the maximum score among participants excluding the top participant(s) that are tied for first? Actually the second highest score is defined as the next distinct score after the highest? Or as the score of the second participant in sorted order. Since we need to compare s2 and s3, we need to consider the scores of the 2nd and 3rd participants in descending order, not distinct scores. Because if the highest score appears multiple times, the second participant also has that same score (if count(max) >=2). So s2 is the score of the second participant in the sorted list. So we need to know the scores at positions 1, 2, 3 (0-indexed) after sorting all participants descending. That depends on the counts of participants at each score level.
Thus we need to keep track of the top three participants in the sorted order. That can be done by maintaining a list of the top three participants (by score, with tie-breaking maybe by any order) as we read input. But careful: With ties, the order among same score is irrelevant; we just need to know the score at positions 2 and 3. So we can maintain the three best scores and also maybe keep count of participants at those scores? Actually we need to be able to determine if there is a third participant with score equal to s2. That is, if the second highest score appears at least twice? That would make s3 equal s2. But also if there are exactly two participants with the top score (s1=s2>s3), then s2 is the top score but there are exactly two participants with that score, so the third participant's score is lower. So we need to differentiate between having count(max) = 2 (then s2 = max, s3 < max) and count(max) >= 3 (then s3 = max). So simply keeping top three scores as we scan: we can maintain the top three participants (distinct individuals) sorted by score. After reading all participants, we can sort these three if necessary? Actually we can update a list of top three highest-scoring participants. But if there are many participants with the same high score, we might need to know if there are at least three with that score. So the top three participants we keep would all have the same score if there are at least three with max. So if after scanning we have top three participants, we can check: let a, b, c be the three highest in order (by score descending, with some tie-breaking). Then s1 = a.score, s2 = b.score, s3 = c.score if region has at least 3 participants; else if region has 2, we just output them. But if region has many participants but the third highest score is lower than second, then c.score < b.score. If b.score == c.score, then s2 == s3, so output "?". However, what if region has only 2 participants? Then we have no third, and it's unique. If region has more than 2, we need third score.
But careful: Maintaining the top three participants by score during scanning is straightforward: for each participant, compare with the current top three list; we can keep an array of up to three best (scores and surnames). But we need to ensure that if there are ties, we keep the correct ones? Actually for uniqueness decision, we only need the scores of the second and third best participants, and also the surnames of the top two for output. So we can keep the top three participants (i.e., the three highest scores, with ties broken arbitrarily). However, consider a region with many participants, e.g., scores: 800 (A), 800 (B), 800 (C), 700... The top three participants we keep could be A, B, C (all 800). Then s1=800, s2=800, s3=800 => s2==s3 => output ?. That's correct. If scores: 800 (A), 800 (B), 790 (C), ... The top three would be A, B, C. s2=800, s3=790 => s2 > s3 => unique. However, what if there is a scenario where the second highest score appears more than once but we might not capture the third participant if the third participant has the same score as second but our top three list only keeps three participants, but if there are more than three participants with the second highest score? That would require the highest score maybe also? Let's think: Suppose scores: 800 (A), 790 (B), 790 (C), 790 (D). Then top three participants by score: A (800), B (790), C (790). So s1=800, s2=790, s3=790 => s2 == s3, output ?. That's correct. But if we only kept three, we have B and C as the two highest among the 790s? That's fine because we need to detect equality between s2 and s3. However, what if we kept A (800), B (790), D (790) but C also 790, but D is also 790, so s2=790, s3=790 still. So any three that include two 790s will show s2==s3. So correct.
But we need to be careful if region has exactly 2 participants: we will have only top two, and maybe third is not present. That's fine.
Thus algorithm:
- Initialize for each region i (1..m): an empty list of top participants? Since m up to 10000, we can allocate arrays of size m+1, each containing a small fixed-size container (like three entries). We'll keep an array of structures: best1_name, best1_score; best2_name, best2_score; best3_name, best3_score; but they need to be updated as we read participants.
We process each participant: read surname, region r, score s.
We need to update the top three for region r. This is like maintaining the three largest scores (with ties) and associated names. Since we need the actual participants for output (the two highest), we need to store their surnames. For region r, we have current list of up to three best participants (sorted descending among themselves). When a new participant comes, we compare its score with the current ones and insert if it belongs to top three, possibly evicting the current third if needed. However, we must also consider that if there are ties, we might need to keep multiple participants with same score to correctly determine the third's score. But as argued, keeping exactly three participants (the three highest in the multiset) is sufficient to determine s1, s2, s3: the scores of the first, second, third participants in the sorted list. But what about the case where there are more than three participants with the same top score? For example, region has four participants all score 800. The top three would be three of them, all score 800, so s1=800, s2=800, s3=800 => s2==s3 => output ?. That's correct. So we don't need to know about the fourth because it doesn't affect the comparison.
What about a region with scores: 800, 800, 800, 800, 800 (5 participants). Top three all 800 => ?. correct.
What about region with scores: 800, 800, 800, 799,... Top three: 800,800,800 => ?. correct (since s2==s3). Actually is the team uniquely determined in that case? We have three participants with 800, so there are multiple pairs among those three. So indeed not unique.
Thus storing top three is enough.
But there is a nuance: When updating top three, we need to maintain the order correctly. For uniqueness determination, we need the scores of the second and third positions. But if we only keep three, we need to ensure that when we insert a new participant, we correctly evict the lowest of the four (old three + new) to keep the top three. However, if there are ties, we need to consider that among participants with same score, any can be kept; the relative order doesn't matter because s2 and s3 are defined as the scores at positions 2 and 3 in the sorted list. For multiple participants with same score, the assignment to positions is arbitrary but the values are the same. So if we have three participants with scores, say, 800, 800, 790, and a new participant with 800 comes, the sorted list would be 800,800,800,790 (if we include all). The top three would be 800,800,800; but if we had previously stored 800,800,790 and now we add a new 800, we need to replace the 790 with the new 800 to reflect the top three now being 800,800,800. So our update must be able to evict the smallest score among the current three when a higher (or equal) score appears that is larger (or equal) and we want to keep the three highest scores. But careful: If we have three participants with scores 800,800,800, and a new participant with 800 arrives, the sorted list top three would still be 800,800,800 (any three of the four). But the fourth 800 would be beyond top three. So we don't need to keep it, because we only care about top three. But our algorithm must ensure that when we have exactly three 800s stored, and a new 800 comes, we might choose to keep the three highest, but we could ignore the new one. That's fine. But we must be careful that we don't inadvertently keep a lower score if we have multiple participants with same score. For instance, we start empty. Add participant A (800). Best list: [A]. Add B (800). Now list: [A,B] (maybe sorted). Add C (790). List: [A,B,C]. Add D (800). Compare: we have three currently: scores 800,800,790. The new score 800 is >= 790. We want to keep the three highest scores: 800,800,800. So we should replace the smallest (790) with D. So we need to implement update that inserts new participant into a sorted list of up to three, discarding the smallest if size would exceed three.
But what if we have two 800s and one 800 already? Actually if we have three 800s already, new 800: all current scores are 800, new is 800. The smallest among current is 800, new is 800, they are equal. To keep the top three, we could either keep the existing three or replace one; but either way, the set of scores among the top three remains all 800. So we can ignore the new one or replace one arbitrarily; doesn't affect s1, s2, s3 (they remain 800). So it's fine.
Thus maintaining a fixed-size priority (or sorted list of up to three) works.
After reading all participants, for each region i:
- Let k = number of participants in region i? We might not have counted directly. But we can also maintain count per region (maybe). However, we need to know if k==2 or >=3. Actually we can infer from the top three: if we have only two participants in region, we will have only two entries in our top list (since we never added a third). So we can just check if we have a third participant (i.e., best3_name is filled). But careful: We might have only two participants but we might have incorrectly stored a third? No, if there are only two, we will only have added two. So we can check if count < 3? But we need the count to decide uniqueness. Actually for region with exactly two participants, we output the two names. For region with >=3, we check condition s2 > s3. If we have at least three participants, best3 will be filled (since we always kept top three). However, it's possible that a region has many participants but our top three list might have less than three if we didn't update correctly? But we process all participants, so if region has at least three participants, we will have encountered at least three; our update algorithm should ensure we keep up to three, so at the end we will have three entries if region size >=3. (Unless we made mistake in update: if region has three participants but one of them is lower than the first two, we will have three; if all three have same score, we will have three; so yes.) So we can check: if the region has less than three participants (i.e., we have only two entries), then output the two names (unique). Else (three entries exist), we compare best2.score and best3.score. If best2.score > best3.score, output the two surnames (best1 and best2). Else output "?".
But we must be careful: What if region has more than three participants, but the third highest score is equal to the second? That yields "?". That's correct.
Edge case: region has exactly three participants, best2.score > best3.score? Then unique. Example: scores 800, 800, 790 (unique). That yields best2=800, best3=790, 800>790 -> unique. Output best1 and best2. But careful: if scores are 800, 790, 790 (best2=790, best3=790) -> not unique. So correct.
Now, we must ensure that the two participants we output are indeed the top two. In unique case, best1 and best2 are the highest and second highest. However, could there be a scenario where best1 and best2 are not the correct unique pair? Let's examine: Suppose region has participants: A:800, B:800, C:800? Then not unique, so we won't output them. So ok.
But what about case where region has participants: A:800, B:800, C:800, D:799? That's not unique because there are three 800s, s2==s3 (both 800). Our top three would likely be A,B,C (all 800). So best2=800, best3=800 -> output "?". That's correct.
Now consider region with participants: A:800, B:800, C:799, D:799. Sorted: 800,800,799,799. s2=800, s3=799 => s2>s3 => unique. Our top three would be A,B,C. best2=800, best3=799 => unique. Output A and B. Indeed the unique team is the two 800s. So correct.
Now consider region with participants: A:800, B:799, C:799, D:798. Sorted: 800,799,799,798. s2=799, s3=799 => s2==s3 => not unique. Because there are two participants with second highest score (799). Indeed possible valid teams? Let's check: top two: (800, B) with B 799. Is (800, C) also valid? For (800,B): min=799, M = max of others (C=799, D=798) => M = 799. Condition min >= M -> 799 >= 799 ok. So (800,B) valid. (800,C) similarly valid. So two valid teams. So not unique. So correct.
Now consider region with participants: A:800, B:799, C:798, D:797. Sorted: 800,799,798,797. s2=799, s3=798 => s2>s3 => unique (800,799). Check: (800,799) valid, (800,798) invalid because 798 < 799? Let's verify: (800,798): min=798, M = max of others (799,797) = 799, condition 798 >= 799 false, so invalid. So unique. Good.
Thus algorithm stands.
Now about implementation details.
We need to store for each region:
- count of participants? Not strictly needed but could be used to detect if there are exactly two. However we can also check if we have best3 filled. But if region has exactly two participants, we won't have a third; but we could also have initialized best3 with sentinel (score = -1). So at end, if best3.score == -1 (or not set), then region has <=2 participants? But it could have exactly two or one? However problem guarantees at least two per region, so it's either exactly two or >=3. So if we have only two entries (i.e., best3 is not set), then it's exactly two. But careful: Our update algorithm might have stored best3 only if there were at least three participants encountered. So if region has exactly two, we will have best1 and best2 set, best3 empty. So we can test if best3 is not present (maybe using a flag or initial score = -1). So for each region, we can have arrays: top_names[3], top_scores[3] and a count 'cnt' up to 3 of how many we have stored? Actually we always store up to 3 highest we've seen; after processing all participants, if region size is >=3, we will have exactly 3 entries (since we never discard below top3? But we might have exactly 3 if region size>=3, but if region size is exactly 3, we have 3; if region size >3, we also have 3. So if region size >=3, we will have 3. So at the end, we can check: if we have at least 3 entries (i.e., top_scores[2] is set), then region size >=3; else (only 2 entries) region size ==2.
But what if region size is huge and we always keep exactly 3 entries? Yes.
Implementation of update per region:
We can maintain for each region a list (like a small array) of the top participants. For each new participant, we need to insert it into the list while keeping the list sorted descending by score, and then trim to at most 3. Since list size max 3, we can just do a simple insertion:
- Append the new participant to a temporary list of up to 4 entries (the existing top 3 plus the new), sort by score descending (and maybe if scores equal, order doesn't matter), then take the first 3. However, sorting 4 items each time for up to 100k updates might be okay? Each region might receive many participants. In worst case, all 100k participants are in one region, we would do 100k updates, each sorting 4 items => 100k * O(4 log 4) trivial. But we need to do this for each participant; overall 100k * small constant, fine. However, we could implement more efficiently by scanning and comparing, but it's fine.
But we need to store the surnames (strings) for the top participants. Sorting 4 strings each time might be a bit heavy but still fine. But we can avoid sorting by manual insertion: Compare new score with existing ones, find its position. Since the list is tiny, we can just do a linear check: iterate over current list (size up to 3) to see where new participant fits, then shift or discard as needed.
Simpler: Keep a vector for each region, but we don't want to store all participants because memory might be high but still okay? n=100k, storing all strings is fine. But we can also just keep top three and discard others. So we need to update per region.
Implementation plan:
- Define for each region: an array of (score, surname) for up to three entries, initially empty.
- Also we might want to keep a count of participants per region? Not needed but could be useful for debugging.
Processing each participant:
read surname (string), region r, score s.
// Update region r's top three.
Let current list L (size up to 3). Add (s, surname) to L, then sort L descending by score; if size > 3, drop the last (lowest score). But if size > 3 after adding, we need to drop the smallest. However, we should be careful: when scores tie, we might arbitrarily drop one; that's fine.
But sorting each time could cause us to lose track of which two are the highest if we later need to output them. However, since we only keep top three and we don't care about order beyond that, it's okay. But we need to know which are first and second at the end. So we need to store them in sorted order. So after all updates, the list for each region should be sorted descending by score.
Simplify: At the end, we can sort the final list (size up to 3) for each region. But to avoid storing all participants, we update as we go, but it's easier to just maintain a min-heap of size 3? Actually we want top three maximum, so we could maintain a min-heap of size 3 (keeping the smallest among the top). But then at the end we would need to retrieve the top three in order; we could pop and sort. Simpler to just maintain an unsorted list of up to 3, and at the end sort it. But we need to ensure that if a participant has score higher than some existing in the list, we replace the smallest. So we can do: keep list of up to 3 entries. When adding new:
- If list size < 3: add to list.
- Else (size == 3):
- Find the minimum score among the three. If new score > min_score, replace that entry with new.
- Else if new score == min_score, we might optionally keep the old? Either way, it's fine; but if we always replace when >=? We need to be careful: if all three have same score and new has same score, we might replace one, but that would still keep three with same score; but what if we replace and later another same score appears, we might end up with only one of the original? But as long as we keep three entries all with that score, it doesn't matter which individuals. But if we always replace the smallest when new score >= min_score, then in a region with many participants all with same score, we might keep only the last three encountered, which is fine because they all have same score. So it's okay.
But we need to be careful: Suppose we have scores: 800 (A), 800 (B), 800 (C). Initially: add A -> list [A]; add B -> list [A,B]; add C -> list [A,B,C]; now size=3. Next, add D with 800. min_score = 800, new_score = 800 >= min_score, so we replace the smallest (which is one of them, say A). Now list becomes [B,C,D]. So we still have three 800s. So okay.
But suppose we have scores: 800 (A), 800 (B), 799 (C). List: [A,B,C]. Next, add D with 800. min_score = 799, new 800 > 799, so we replace C (the min). Now list becomes [A,B,D] all 800. That's correct: the top three are now all 800, so s3=800, but actually the true sorted order is 800,800,800,799? Wait, we have participants: A,B,D (800), and also C (799) exists but is not in our list. But our top three should be the three highest scores: which are three 800s, because there are three participants with 800: A, B, D. So the third highest score is 800, not 799. Our list correctly captured that. So we need to have dropped the 799. That's good. But what about the condition s2 > s3? In this region, we have three 800s and a 799. s2 = 800 (since second highest is 800), s3 = 800 (since third highest is 800). So s2 == s3, so not unique. Our list will have three entries all with score 800, so best2.score = 800, best3.score = 800 => s2 == s3 => output "?". That's correct.
Now suppose we have scores: 800 (A), 800 (B), 799 (C), 799 (D). The sorted order: 800,800,799,799. s2=800, s3=799 => unique. Our update: add A -> [A]; add B -> [A,B]; add C -> [A,B,C] (scores 800,800,799). add D (799). size=3, min_score among list is 799 (C). new_score = 799 >= 799, so we could replace C with D (or maybe we compare >? if we replace when >=, we replace C with D. So list becomes [A,B,D] with scores 800,800,799. That's fine because the third entry is 799. But note that the true top three sorted are 800,800,799? Actually the third highest score is 799 (since we have two 800s and then the highest 799 is the third). The list [A,B,D] gives third as 799, which is correct. However, what about the possibility that we have more than two 799s? But we only need third highest, which is 799. So fine.
But consider if we had scores: 800, 800, 800, 799, 799. Sorted: 800,800,800,799,799. s2=800, s3=800 (third is 800). Our update: after adding first three 800s, list = [800,800,800]. Then add 799: min_score=800, new=799 < 800, so we don't replace. So list remains [800,800,800]. So best3=800, s3=800, s2=800 => not unique. Correct.
Thus update with replacement only when new_score > min_score (or >=? we used > for the case when new_score equals min_score? Let's check: In the case where we have exactly three 800s and a fourth 800 appears, we want to keep three 800s, not necessarily the same individuals, but we must ensure that we still have three 800s. If we only replace when new_score > min_score, then for new 800, min_score = 800, new_score = 800 is not >, so we would not replace. Then list would remain as previous three 800s, which is fine because we already have three 800s; the fourth 800 is not needed. But what if we had list [800,800,799] and new 800 appears? Then min_score=799, new 800 > 799, so replace, resulting in [800,800,800]. Good. If we had list [800,800,800] and new 799 appears, we don't replace. So we should replace only if new_score > current_min_score. If new_score == current_min_score, we might consider whether to replace to maintain the most recent? But it's not necessary; we can keep the existing. However, consider scenario: we have list [800,800,800] (from three 800s) and then we get a new 800. If we don't replace, list stays with three 800s. That's correct. If we replace (by >=) we also have three 800s. Both fine. However, there is a subtle scenario: we have list [800,800,799] and a new 799 appears. If we replace only when >, we would not replace because 799 is not > 799. Then list stays [800,800,799]. That's correct because the third highest is 799, and we have at least one 799; but we might have two 799s, but we only need one 799 to know the third score. However, if there are two 799s, the third highest score is 799, but the fourth is also 799? Actually sorted: 800,800,799,799,... So third score is 799. Our list has one 799, which is fine. But what if we later get another 800? We already handled that. So using > for replacement works: we only replace the smallest if the new score is strictly greater than the current smallest. But what about when we have less than 3 entries? We just add. So algorithm: For region r, have an array top[3] (maybe with -1 sentinel). When new participant (score s, name):
- If top[2] is not yet filled (i.e., we have less than 3 entries), just add it (maybe append and then sort later). But simpler: we can treat the list as unsorted and at the end sort. But we need to find the min among the list for replacement. Since size <=3, we can just keep them in an unsorted vector and find min each time. Or we can keep them sorted to make min easier. But either way, constant time.
I'll implement as follows:
For each region, maintain a vector<pair<int,string>> top; (max size 3). For each participant:
Append (score, name) to top (so now size maybe 4).
Sort top in descending order by score (if equal, any order).
If top.size() > 3, pop the last element (lowest score).
This is O(4 log 4) per participant, which is fine.
At the end, after processing all participants, for each region:
let k = number of participants in that region? We might not have stored count, but we have top.size().
Actually we need to know if there are exactly 2 participants. If top.size() == 2, then region has exactly two (since we would have added all participants, and if there were three or more, top.size() would be 3 after processing all? Wait, if there are exactly two participants, we will process both; after first, top size 1; after second, top size 2; final top size =2. So yes, top.size() ==2 indicates exactly two participants. If top.size() ==3, indicates there were at least three participants. However, what if there were more than three participants but we always keep only three? Then top.size() will be 3. So we can't distinguish between exactly three and more than three, but we don't need to; we just need to know if there are at least three. So condition: if top.size() == 2 => exactly two => output the two names. else (top.size() == 3) => at least three => then check scores: if top[1].first > top[2].first => unique, output top[0].second and top[1].second; else output "?".
But wait: Could top.size() be 1? No, because each region has at least two participants. So top.size() will be at least 2.
But careful: The method of adding and then sorting and popping may result in top.size() = 3 even if region had only two participants? No, because we only added two participants, after second addition, we would have top.size() = 2 (since after adding, we sort and if size > 3 we pop; but after second addition, size =2, not >3, so we keep both). So final top.size() = 2. So fine.
Thus this approach works.
Now, we need to store surnames. They are strings up to length 10. We can store them as std::string.
Complexities: n=100k, m=10k, so we need arrays of size m+1 for storing top vectors. However, storing a vector per region (with 2-3 elements) is okay. Alternatively, we could store three arrays: top1_name, top1_score, top2_name, top2_score, top3_name, top3_score, and update manually.
I'll implement with vector of vectors? But overhead of vector per region (m up to 10k) is fine; each vector small. Or we can use array of struct Region { vector<pair<int,string>> top; } But vector overhead might be non-negligible but still okay for 10k. Alternatively, use fixed-size arrays and manage them.
Given we need to sort after each insertion, using a fixed-size array may be simpler: for each region, have an array of 3 entries with fields (score, name). Also maintain a count cnt of how many entries currently stored (0..3). When adding new participant, we can place it into the array at position cnt (if cnt<3) then sort the array (or insert in correct position). Or we can treat it as: we have up to 3 best, we can compare with each and possibly replace. But sorting each time is simple enough.
But since we have many participants, and m could be 10k, we could also accumulate all participants in a per-region vector and then after reading all, for each region, sort that vector and compute. That would be O(n log n) overall and simpler to code, because we just group participants by region, store them all (name, score). Then for each region, sort its vector by score descending, then check condition. That is straightforward and likely fast enough: total sorting cost sum_i (k_i log k_i). Since total n=100k, sum of k_i log k_i is at most n log n (when one region has all). That's about 100k * ~17 = 1.7M operations, which is fine. Memory: storing all participants in vectors per region: each participant stored once with string and int. That's okay. This avoids the need to maintain top three while reading. Simpler to implement and less error-prone.
I'll choose this simpler approach: Use vector for each region to store pairs (score, surname). After reading all input, for each region i from 1 to m:
- sort its vector in descending order of score (if equal, any order, but we need to output two names; ordering among ties not important).
- let k = vector size.
- if k == 2: output the two surnames (order arbitrary).
- else (k >= 3): let s2 = vector[1].score, s3 = vector[2].score. If s2 > s3: output surnames of vector[0] and vector[1]. Else output "?".
But careful: In case of tie for first? If s1 = s2 > s3, then vector[0] and vector[1] are two participants (maybe not the only two? but they are the first two in sorted order. But if there are two participants with max score, they will be the first two (since sorted descending). However, could there be more than two with max score? Then s2 == s3 (since third also max), so condition fails and we output "?" anyway. So it's safe: when condition passes, the first two are exactly the two highest-scoring participants, and they are the unique team.
But is it always true that the first two in sorted order correspond to the two participants that should be output? In unique case, there is exactly one valid pair, which is the two highest-scoring participants. Since sorting yields a list, the first two are the two highest-scoring participants. So we output them.
Potential nuance: What if there are exactly two participants? Then we output the two names (they are the only two). Good.
Thus algorithm is trivial.
Complexities: We need to store strings and scores. Input reading: O(n). Sorting each region: sum O(n log n) worst-case, okay.
Implementation details:
- Use 1-indexed regions: from 1 to m.
- For each region, we can push a tuple: (score, surname) into a vector. We'll need to store the surname for output.
But careful: When sorting by score descending, we need to break ties consistently but it doesn't matter.
Potential pitfalls: The surnames are case-sensitive and distinct globally. But we output them in arbitrary order. So we can just output the two names in the order they appear in sorted list (first and second). Or we can output "name1 name2" separated by space.
Now verify with given examples.
Example 1:
n=5, m=2
Region1: Ivanov 763, Petrov 595, Sidorov 790 -> sorted: Sidorov 790, Ivanov 763, Petrov 595. s2=763, s3=595 -> s2>s3, output Sidorov and Ivanov (order maybe Sidorov Ivanov). That matches.
Region2: Andreev 800, Semenov 503 -> only two, output Andreev Semenov. Matches.
Example2:
Region1: Ivanov 800, Petrov 800, Sidorov 800 -> sorted: three 800. s2=800, s3=800 => not >, output "?".
Region2: Andreev 763, Semenov 503 -> two, output Andreev Semenov. Matches.
Thus correct.
Now consider additional tests.
Edge test: region with two participants: unique.
Edge: region with many participants and top two same, third lower: unique. Output the two top.
Edge: region with top two same and third same -> ?.
Edge: region with top1 > top2 = top3 > top4 -> s2 = top2, s3 = top2 (equal) -> ?.
Edge: region with top1 > top2 > top3 = top4? Actually s2 > s3 still unique if s2 > s3, regardless of s4.
Edge: region with many participants and s2 > s3 but there is a tie for first? Actually if s1 = s2 > s3, then first two are both max. That's unique. Our sorted list: the two max are first two; we output them. Good.
Now, one nuance: The problem statement: "The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points." According to our interpretation, the condition is min(team) >= max(non-team). But could there be other interpretations? Let's verify with some more examples.
Consider region with scores: 800, 800, 800, 800, 799. According to our condition, any two 800s form a valid team? Check team (800,800). Non-team includes two other 800s and 799. For each member (800), any non-team member has 800, which is not greater than 800. So condition holds. So many teams. So not unique. Our condition s2 > s3? s2 = 800 (second highest), s3 = 800 (third highest) -> s2 not > s3, so "?". Good.
Consider region with scores: 800, 800, 799, 799, 799. Sorted: 800,800,799,799,799. s2=800, s3=799 -> unique? According to condition, is there only one valid team? Let's list valid teams: (800,800) is valid because min=800, non-team max=799, 800>=799. Is there any other valid team? Consider (800,799): min=799, non-team max = max(other 800, other 799's) = 800. So 799 >= 800? false. So invalid. So only (800,800) valid. So unique. Our condition: s2=800 > s3=799 => unique, output the two 800s. Good.
Consider region with scores: 800, 799, 799, 799. Sorted: 800,799,799,799. s2=799, s3=799 -> not unique. Check valid teams: (800,799) - check if any such team valid? For (800,799): min=799, non-team max = max(other 799's) = 799. So condition 799 >= 799 holds. So (800, first 799) valid. Also (800, second 799) valid, (800, third 799) valid. Also what about (799,799)? For (799,799): min=799, non-team includes 800 and another 799. max non-team = 800. Condition 799 >= 800 false. So only teams including the top 800 and any one of the 799s are valid. Since there are three 799s, there are three valid teams. So not unique. Our condition: s2==s3 -> "?". Good.
Consider region with scores: 800, 800, 800, 800. s2=800, s3=800 -> "?". Indeed many teams.
Consider region with scores: 800, 800, 800, 700, 700. s2=800, s3=800 -> "?" (multiple 800s). Good.
Consider region with scores: 800, 800, 700, 700. s2=800, s3=700 -> unique. Check: only (800,800) valid. So output the two 800s.
Consider region with scores: 800, 750, 750, 700. s2=750, s3=750 -> "?". Because (800,750) with either 750 yields valid? For (800,750): min=750, non-team max = max(other 750,700) = 750, condition holds. So there are two valid teams (since two 750s). So not unique. So condition holds.
Consider region with scores: 800, 750, 749, 700. s2=750, s3=749 -> unique: (800,750). Check if (800,749) invalid because min=749, non-team max=750 => 749<750. So only one.
Thus logic stands.
Now one more nuance: In the case where region has exactly two participants, there is no third. So we output them. That's straightforward.
Now confirm that the problem input guarantees that at least two participants per region. So no region with fewer than two.
Now implement.
Implementation steps:
-
Read n, m.
-
Create vector of vector of pairs: participants_by_region of size m+1 (index 1..m). Each inner vector will hold pairs (score, surname). Or store as struct with surname and score.
-
Loop i=0..n-1:
read surname (string), region r, score s.
participants_by_region[r].push_back({s, surname}).
-
After reading, for each region i from 1 to m:
let vec = participants_by_region[i].
Let k = vec.size().
If k == 2:
print vec[0].second and vec[1].second (in any order). But note that the vector may be in order of input; not sorted. However, for output we can just print the two names as they appear? But the problem says "in an arbitrary order". So we can print them as they are stored, but to be safe, maybe we should output the two participants in some order, but it doesn't matter. However, the example output seems to have the higher-scoring first? Not necessarily. In example1, region1 output "Sidorov Ivanov". Sidorov had 790, Ivanov 763, so they output higher first? But it says arbitrary. So we can output the two names in the order we get after sorting (if we sort for all regions). For consistency, I'll sort for all regions, even if k==2 (though not needed). For k==2, sorting will put higher score first, but any order fine.
But to avoid extra sorting for k==2, we can just output as is. However, for simplicity, we can sort all region vectors regardless of size; overhead negligible. So I'll sort each region's vector descending by score. Then:
if k >= 3:
if vec[1].first > vec[2].first:
print vec[0].second << " " << vec[1].second
else:
print "?"
else (k==2):
print vec[0].second << " " << vec[1].second
But careful: What if k >=3 but after sorting, vec[1].first > vec[2].first fails (i.e., equal), then "?". If vec[1].first > vec[2].first passes, then unique.
But is it possible that k >=3 but after sorting, the third highest score does not exist? No, if k>=3, index 2 exists.
Now consider potential scenario: region has exactly 3 participants, but the second highest score equals the third? Then not unique. Good.
Now, what about region with more than 3 but after sorting, the third highest score is equal to the second? Then not unique. Good.
Thus algorithm is correct.
But wait: Did we overlook the case where there is a tie for first and the second highest is unique but the top two are not uniquely identified? For example, region with participants: A:800, B:800, C:700. Here s1=800, s2=800, s3=700 -> unique team is (A,B). However, are there exactly two participants with max score? Yes. But suppose we sorted, we will have A and B as first two (maybe A then B). That's fine. But is there any chance that the sorted order might place C in second if we sort incorrectly? No, because scores determine order: both 800 are higher than 700.
Thus fine.
Now one more nuance: The problem says "The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team." So if there are two participants with same score and there is a tie for second but with distinct participants, then there can be multiple valid teams. That's covered.
Now, we need to output m lines.
Implementation details:
We'll use C++.
Pseudo:
int n, m;
cin >> n >> m;
vector<vector<pair<int, string>>> regions(m+1); // 1-indexed
for(int i=0; i<n; ++i){
string name;
int reg, score;
cin >> name >> reg >> score;
regions[reg].emplace_back(score, name);
}
for(int i=1; i<=m; ++i){
auto& vec = regions[i];
sort(vec.begin(), vec.end(), [](const pair<int,string>& a, const pair<int,string>& b){
return a.first > b.first; // descending score
});
if(vec.size() == 2){
cout << vec[0].second << " " << vec[1].second << "\n";
} else { // size >=3
if(vec[1].first > vec[2].first){
cout << vec[0].second << " " << vec[1].second << "\n";
} else {
cout << "?\n";
}
}
}
But wait: The problem statement says "There were at least two schoolboys participating from each of the m regions of Berland." So size is at least 2. So no region with size 1. So it's fine.
Now test with some custom.
Test 1:
n=6, m=2
Region1: A 1 800, B 1 800, C 1 800, D 1 700 -> size 4; sorted: 800,800,800,700; s2=800, s3=800 => "?".
Region2: E 2 500, F 2 400 -> size 2 -> output "E F" (or F E depending on sort). But we sort, so E 500, F 400 -> output "E F". That seems correct.
Now, there is also case where region size=2, but they have same score: output both, unique. That's correct.
Now, one more nuance: The problem says: "It is guaranteed that for each region at least two its representatives participated in the qualifying contest." So no region with zero.
Now, consider potential pitfalls: The input size: n up to 100k, m up to 10k. Using vector of vectors with strings: we'll store all names, total memory: each name string up to 10 chars, but std::string may have overhead. But 100k strings is fine. We can store as std::string. Alternatively, we could store char arrays but not needed.
Now, about sorting: For each region, we sort its participants. In worst-case, one region has 100k participants, sorting that vector of 100k pairs of (int, string) is okay: O(100k log 100k) ~ 1.7 million comparisons. Each comparison involves int comparison primarily; string may not be compared because we only compare by score. Our comparator uses only scores. So it's efficient.
Thus solution is straightforward.
But wait: There is a subtle condition: "none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points." The phrasing: "none of them can be replaced by a schoolboy ... who received a greater number of points." Could it be interpreted differently? Could it mean that you cannot replace a team member with a non-team member who has higher points such that the new team would still satisfy some property? But the problem statement: "The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points." The phrase "can be replaced" likely means that if you try to replace that team member with some other participant (not in the team) who has higher points, the resulting two-person set would not satisfy some property? But the property described might be that after replacement, the new team would still need to satisfy the same condition? Actually reading: "The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points." This is ambiguous. It might mean: For each team member, if you consider any other participant from the same region who is not on the team and has a higher score, then replacing the team member with that higher-scoring participant would result in a team that does NOT have the property that "none of them can be replaced ..."? Actually it's self-referential.
Let's parse the original statement: "The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points." This is typical phrasing of "maximal" set under domination: The two selected are such that you cannot replace one of them with a higher-scoring outsider and still have a valid team (maybe under the same criteria). But the condition "none of them can be replaced by ... who received a greater number of points" might mean that if you try to replace a team member with a higher-scoring outsider, the resulting team would not satisfy the same property? Or simply that such a replacement is not allowed? Usually such problems define a team as "stable" or "undominated": there is no participant outside the team who has a higher score than a team member. That matches our interpretation: The team is such that no outsider has a higher score than either team member. Because if there was an outsider with higher score than a team member, you could replace that team member with the outsider and get a "better" team, which is undesirable for the original team? The phrasing "can be replaced" might mean that it is possible to replace them and still have a valid team, but the condition is that such a replacement is not possible. That is exactly: For each team member, there does not exist a non-team participant with a higher score. Because if such a participant existed, you could replace the team member with that higher-scoring participant, and the new team would still consist of two participants; but would it necessarily satisfy the same condition? The problem does not state that the new team must satisfy the condition; it simply says "none of them can be replaced by a schoolboy ... who received a greater number of points." It doesn't say "such that after replacement the resulting team still meets the condition". So the interpretation is: You cannot replace a team member with a higher-scoring outsider, period. That means the team members must be such that there is no outsider with a higher score. Because if there were, you could indeed replace (in the sense of performing the action), regardless of whether the new team is valid. So the condition is that the team is "maximal" in the sense that each member is not dominated by an outsider. So our interpretation stands.
Let's double-check with known problem context. This appears to be a problem from Codeforces? I recall a problem "School Team" maybe. I've seen similar problem: "Very soon Berland will hold a School Team Programming Olympiad." It might be Codeforces Round #... I think the problem is "School Team" (CF 121A? not sure). I recall a solution that basically checks if the second highest score is greater than the third highest. So our approach matches typical solutions.
Thus final answer is as above.
Now we must ensure correct output for region with exactly two participants: output the two surnames (any order). If we sort, we output the higher-scoring first maybe. That's acceptable.
Now let's test with another scenario:
Input:
3 1
A 1 100
B 1 100
C 1 90
Sorted: A 100, B 100, C 90. s2=100 > s3=90 -> unique, output A B. But is it truly unique? Check teams: (A,B) valid. (A,C): min=90, non-team includes B 100 > 90, so invalid. (B,C) similarly invalid. So unique. Output A B. Good.
Input:
3 1
A 1 100
B 1 90
C 1 90
Sorted: A 100, B 90, C 90. s2=90, s3=90 -> not unique. Check: (A,B) valid? min=90, non-team C=90 => condition 90>=90 holds, so valid. (A,C) similarly valid. (B,C): min=90, non-team A=100 > 90 invalid. So two valid teams. Output "?". Good.
Input:
4 1
A 1 100
B 1 100
C 1 100
D 1 90
Sorted: A 100, B 100, C 100, D 90. s2=100, s3=100 -> not unique. Check teams: any two of the three 100s are valid. So multiple. Output "?". Good.
Input:
4 1
A 1 100
B 1 99
C 1 99
D 1 98
Sorted: A 100, B 99, C 99, D 98. s2=99, s3=99 -> not unique. Check: (A,B) valid? min=99, non-team max = max(C=99, D=98) = 99 -> valid. (A,C) also valid. (B,C) invalid. So two valid teams. Output "?". Good.
Thus matches.
Now, what about region with many participants and s2 > s3, but what if there is a tie for first and second is lower? Actually that's covered.
Now we should also consider if there is a situation where the team is uniquely determined but the two participants are not the two highest? Could there be a scenario where the top two are not valid, but some other pair is valid? Let's try to find a counterexample. Suppose we have scores: 10, 9, 8, 8. Sorted: 10,9,8,8. s2=9, s3=8 => s2 > s3. According to our rule, (10,9) is valid. Check (10,9): min=9, non-team max = 8 => valid. Is there any other valid pair? (10,8): min=8, non-team max = max(9,8) =9 => 8>=9 false. (9,8): min=8, non-team max = 10 => false. So only (10,9). So good.
Suppose scores: 10, 8, 8, 7. s2=8, s3=8 => s2 == s3, so not unique. Indeed (10,8) with either 8 is valid? Check (10,8): min=8, non-team max = max(other 8,7) =8 => valid. So two valid teams. (8,8): min=8, non-team max =10 => false. So not unique.
Thus the top two are always a valid team, and uniqueness holds exactly when they are the only valid team.
But is it always true that the top two are a valid team? Check with any set: sorted s1 >= s2 >= ... >= sk. For (s1, s2), min = s2, max non-team = s3 if k>=3 else none. Since s2 >= s3 by sorting, condition holds. So yes, top two always valid.
Thus the set of valid teams always includes the top two, and any other valid team must include s1 (since any team not including s1 would have min <= s2, and M >= s1 >? Actually if team does not include s1, M = s1, so need min >= s1 => min = s1, so both members must have score s1, meaning all participants have same score. So only possible when all scores equal. In that case, top two is also a valid team (since all scores equal). But if all scores equal, there are many teams, including (s1, s2) but also others. So uniqueness fails.
Thus unique iff top two is the only valid team, which happens exactly when there is no other valid team. And other valid team exists if either there is another participant with score equal to s2 (i.e., s3 == s2) because then (s1, any participant with score s2) gives multiple; or if all scores equal, then also (s2, s3) etc. But the condition s2 > s3 captures the absence of any participant with score equal to s2 besides the second participant? But what about the case where s1 > s2 but there is another participant with score equal to s1? That's impossible because s1 is max; if there is another with same max, then s1 = s2 = max, and s3 could be lower. That gives s2 > s3 (since s3 < max). So uniqueness holds. So the only way to have extra valid teams is to have at least two participants with score equal to s2, i.e., the second highest score appears at least twice. That includes the case where s2 = s3. Also if all scores equal, that also qualifies because s2 = s3. So condition s2 > s3 is necessary and sufficient for uniqueness.
Thus solution is correct.
Now we just need to implement.
Potential issues: The input size: n up to 100k, reading with cin may be slower if not optimized. Use ios_base::sync_with_stdio(false); cin.tie(0). Also string reading: use cin.
Also ensure we use correct data structures.
Now let's write final code.
Pseudo code:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<vector<pair<int, string>>> regions(m+1);
for (int i = 0; i < n; ++i) {
string name;
int reg, score;
cin >> name >> reg >> score;
regions[reg].emplace_back(score, name);
}
for (int r = 1; r <= m; ++r) {
auto& vec = regions[r];
// sort by score descending
sort(vec.begin(), vec.end(), [](const auto& a, const auto& b) {
return a.first > b.first;
});
if (vec.size() == 2) {
cout << vec[0].second << " " << vec[1].second << "\n";
} else { // size >= 3
if (vec[1].first > vec[2].first) {
cout << vec[0].second << " " << vec[1].second << "\n";
} else {
cout << "?\n";
}
}
}
return 0;
}
Now verify with examples.
But wait: The example input uses "Ivanov 1 763" etc. The output order is "Sidorov Ivanov". Our sorted order for region1: scores: Sidorov 790, Ivanov 763, Petrov 595. So vec[0].second = "Sidorov", vec[1].second = "Ivanov". So we output "Sidorov Ivanov". That matches.
For region2: Andreev 800, Semenov 503 -> output "Andreev Semenov". Good.
Second example: region1 sorted: all 800, order maybe based on input order? After sorting with comparator only on score, the order among ties is unspecified; it will be stable? Actually sort may not preserve order for equal elements. But since scores equal, the comparator returns false for both a<b and b<a, so the order is not defined; it could be any. However, for output we only care when unique? But in region1 case, we output "?" anyway because s2 == s3. So the order of equal elements doesn't matter because we only output if unique, and uniqueness fails. So it's fine.
But note: For region2, there are only two participants, sorted will put Andreev (800) first, Semenov (503) second; output as expected.
Thus code works.
But let's also test region with exactly two but same score: Input: 2 1; A 1 500; B 1 500. Sorted: both 500, but comparator returns false for both, order could be either A,B or B,A. But both are valid outputs, as order arbitrary. So fine.
Now, what about region with exactly three participants but the two highest are unique (s2 > s3) but there is a tie for first? Actually s1 = s2 > s3, then sorted: first two are two participants with max score. The order among them could be any, but we output both. That's fine.
Now, potential pitfalls: Input might contain large strings? Only up to 10 characters.
Now, memory: vector of vectors with 100k entries, each entry is a pair<int, string>. That is okay.
Thus solution is done.
But before finalizing, think about whether we need to consider the case where there are exactly 3 participants and s2 > s3, but s1 = s2? That's fine.
Now, one more nuance: The problem states: "There were at least two schoolboys participating from each of the m regions of Berland." So region size >=2. Good.
Thus final answer.
But I recall some solutions for this problem: they use sorting and check if second > third, else output "?". That's exactly it.
Now write final answer.
But I'm thinking: Could there be a scenario where region size >=3, s2 > s3, but there is also a participant with score equal to s2 but not in the top two? That would mean s3 = s2, contradict s2 > s3. So no.
So final answer.
Now I'll produce the final response with explanation and code.
But the user asked: "Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests." So we need to output for each region either two surnames or "?".
Thus answer.
Now produce final message. ```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<vector<pair<int, string>>> regions(m + 1); // 1-indexed
for (int i = 0; i < n; ++i) {
string name;
int reg, score;
cin >> name >> reg >> score;
regions[reg].emplace_back(score, name);
}
for (int r = 1; r <= m; ++r) {
auto& vec = regions[r];
// sort by score descending
sort(vec.begin(), vec.end(), [](const auto& a, const auto& b) {
return a.first > b.first;
});
if (vec.size() == 2) { // exactly two participants -> unique
cout << vec[0].second << ' ' << vec[1].second << '\n';
} else { // at least three participants
if (vec[1].first > vec[2].first) { // second > third => unique
cout << vec[0].second << ' ' << vec[1].second << '\n';
} else {
cout << "?\n"; // not unique
}
}
}
return 0;
}