We need to parse the problem. It's a round-robin tournament among n teams. Each team plays every other team exactly once. The results are given from each team's perspective: for team i, we have its results against the other teams in some order? But we need to be careful: the input gives for each team a list of n-1 numbers: the results r1 ... r_{n-1}. But the ordering of opponents is not explicitly given? Usually in such problems, the order of teams in input is fixed: team names are given in order, and the results correspond to matches against the other teams in order (probably in the order of the teams as they appear in input, but skipping itself). For example, dataset 1: n=6, teams: A, B, C, D, E, F in that order. For team A, results: 1 0 0 2 0 correspond to matches against B, C, D, E, F? Since there are 5 numbers, matches against the other 5 teams. Similarly for team B: 0 0 1 1 0 correspond to matches against A, C, D, E, F? But we need to interpret consistently. However, typical problem would list results for each team, with results in the same order as the teams appear in the input list, but skipping the own team. So for team i, the results are for matches against team 1,2,...,i-1,i+1,...,n? Possibly in increasing index order, but skipping its own index.
But we need to combine these to compute wins and losses. Also draws (2) might be counted as neither win nor loss? The ranking criteria: first by most wins, then by fewest losses. Draws are not considered wins or losses. So we need to compute for each team: wins = number of matches where result is 1 (win) from its perspective; losses = number of matches where result is 0 (loss) from its perspective. Draws (2) count as neither.
But caution: If we have both perspectives from each pair, we need to ensure consistency: the result from team A vs team B should be complementary: if A's result against B is 1 (win), then B's result against A should be 0 (loss); if A's result is 0, B's result is 1; if both are 2, then it's a draw. But the problem statement says: "ri is 0 for loss, 1 for win, 2 for a draw." So it's a unilateral reporting: each team reports the outcome of its match. So for each match, we have two entries: one from each team. They should be consistent? Possibly the input is guaranteed to be consistent. But we must compute wins and losses from each team's perspective. If we simply sum each team's own 1's as wins and 0's as losses, we get correct counts because the two entries will correctly reflect win/loss/draw.
But we must be careful: we must not double count matches. But since we only use each team's own reported results, it's fine.
Now ranking: sort teams by descending wins, then ascending losses. If two teams have same wins and losses, they have same rank; output them in the order of input. That means stable sort: maintain input order as secondary key (or just sort with comparator that uses wins then losses, but when equal, preserve input order). So we can store teams in an array with index i (0..n-1). Then sort with comparator: if wins != other.wins: higher wins comes first. Else if losses != other.losses: lower losses comes first. Else: lower original index first.
Now input: multiple datasets, each starting with n, then n lines of data. End when n=0.
Team name t is a single-byte alphabetic character (maybe uppercase or lowercase? example uses uppercase A-F in first dataset, lowercase g h w b in second). So we treat as char.
The input for each team: first token is team name t (single char). Then n-1 integers.
Number of datasets up to 50, n up to 10, so trivial.
Now potential pitfalls: For each team, the results are given, but the ordering of opponents is ambiguous. For correct computation of wins/losses per team, we don't need to know the opponent; we just count the numbers. So we can ignore ordering. However, if the input might not be consistent (e.g., A reports win vs B, B reports win vs A) that would be inconsistent but we assume it's consistent.
But wait: The problem might expect us to consider that each team's results are given in the same order as the teams appear in the input list? In some problems, they provide a matrix of results where the row i corresponds to team i, and column j corresponds to match vs team j, with maybe a dash or something for self. But here it's just a list of n-1 numbers. Without specifying ordering, we must assume they are given in the order of the teams as listed, skipping itself. That is typical.
But we don't need to know opponent for counting wins/losses; we just sum the numbers. So it's fine.
Thus algorithm:
For each dataset:
- Read integer n; if n==0: break.
- Initialize list teams = [] with each element: name, wins=0, losses=0, index.
- For i from 0 to n-1:
- Read line. Split.
- first token is name.
- Then tokens: there should be n-1 integers.
- For each integer r:
if r == 1: wins += 1
if r == 0: losses += 1
// r==2: ignore (draw)
- Append record (name, wins, losses, i)
- Sort records using comparator described.
- Output names in sorted order, each on its own line (the example output shows each name on separate line). After each dataset, we output the sorted names? The example output for first dataset: E, A, B, D, F, C each on separate line. For second dataset: w, h, b, g each on separate line. There is no blank line between datasets.
So just print each name on a new line.
Check example:
Dataset1: n=6
A: 1 0 0 2 0 => wins: count 1's: 1 (first) plus maybe? Also any other 1? Only one? Actually 1,0,0,2,0 -> one 1, four 0's? Wait there is a 2 also. So wins=1, losses=4? (0's count as loss). So A: wins=1, losses=4? But in output, A is second after E. Let's compute others to verify.
B: 0 0 1 1 0 -> wins: two 1's? Actually numbers: 0,0,1,1,0 -> wins=2, losses=3? (three 0's). So B: wins=2, losses=3.
C: 1 1 1 1 1 -> wins=5, losses=0? But output has C last. That seems contradictory: According to ranking criteria, most wins first, so C should be first. But output has E first and C last. So obviously my interpretation is wrong. Because if we count wins as number of 1's, C has all wins, would be top. But they output C at bottom. So there is something else: Perhaps the result numbers are not from the perspective of that team? Or maybe the numbers are for matches in order against other teams, but 1 indicates win for that team? Could be that the numbers represent the opponent's scores? Hmm.
Maybe we misinterpret: In round-robin, each team plays each other. The results are given as "score"? No, the problem says: "the result ri (0, 1, or 2) for each match of t". It says 0 for loss, 1 for win, 2 for draw. That's clear. Then why C has all 1's but is ranked last? Something is off.
Let's re-examine example input:
6
A 1 0 0 2 0
B 0 0 1 1 0
C 1 1 1 1 1
D 1 0 0 1 2
E 2 0 0 0 0
F 1 1 0 2 1
If we count wins and losses as defined:
Team A: wins: count of 1 = 1 (first element) => 1; losses: count of 0 =? there are three zeros? Actually list: 1,0,0,2,0 -> zeros at positions 2,3,5 -> three zeros? Wait there is also maybe? Let's count: 1 (win), 0 (loss), 0 (loss), 2 (draw), 0 (loss) => wins=1, losses=3, draws=1. But total matches are 5, so matches: 1+3+1=5. So wins=1, losses=3.
Team B: 0,0,1,1,0 -> wins: two (positions 3,4), losses: three (positions 1,2,5). wins=2, losses=3.
Team C: 1,1,1,1,1 -> wins=5, losses=0. That would be top.
Team D: 1,0,0,1,2 -> wins: two (positions 1,4), losses: two (positions 2,3), draw:1 => wins=2, losses=2.
Team E: 2,0,0,0,0 -> wins:0 (none), losses:4? Actually list: 2,0,0,0,0 -> one draw and four losses? Check: 2 is draw, then four zeros? Actually there are four numbers after 2? The list: 2 0 0 0 0 => that's five numbers: one 2 and four 0s. So wins=0, losses=4, draw=1.
Team F: 1,1,0,2,1 -> wins: three (positions 1,2,5), losses: one (position3), draw:1 (position4) => wins=3, losses=1.
Now sorting by wins descending, losses ascending:
- C: wins=5, losses=0
- F: wins=3, losses=1
- B: wins=2, losses=3
- D: wins=2, losses=2? Actually D: wins=2, losses=2. So D vs B: D has wins=2, losses=2; B wins=2, losses=3. So D has fewer losses (2<3) so D should rank above B. So order: C, F, D, B, A? Actually A: wins=1, losses=3; E: wins=0, losses=4. So order: C, F, D, B, A, E? But example output: E, A, B, D, F, C. That's completely different. So clearly the interpretation is not that 1=win for that team.
Maybe the numbers are not the result from that team's perspective but the opponent's result? Or perhaps they are the runs? But problem says 0 for loss, 1 for win, 2 for draw. Could there be a different ranking rule? They said: "1. The team with the most wins is ranked high 2. If the number of wins is the same, the team with the fewest losses will be ranked higher." That is typical.
Maybe the input gives results for each team against others, but the order of opponents is not as we assumed, and we need to compute wins/losses from the whole set but the given numbers might be something else like "points" where 2 is a win? No.
Alternatively, maybe we misinterpret that each team's line includes the results against all other teams including itself? But that would be n numbers, but it says n-1. So not.
Maybe the numbers represent match outcomes from the perspective of the opponent? For instance, for team A, the numbers correspond to results of opponents? The description: "t r1 r2 ... rn−1" - "the result ri (0, 1, or 2) for each match of t". That suggests ri is the result of match involving t. So it's for t.
But why would team C have all 1's but be last? Let's try to compute using alternative: treat 0 as win, 1 as loss, 2 as draw. Then:
A: 1,0,0,2,0 -> wins: count of 0? Actually if 0=win, then wins count zeros: there are three zeros? positions 2,3,5 => 3 wins; losses: count of 1? there is one 1 => 1 loss; draws: one 2 => 1 draw. So wins=3, losses=1.
B: 0,0,1,1,0 -> zeros: three? positions1,2,5 => 3 wins? Actually zeros at 1,2,5 =3; ones at 3,4 =>2 losses. wins=3, losses=2.
C: 1,1,1,1,1 -> zeros:0, ones:5 => wins=0, losses=5.
D: 1,0,0,1,2 -> zeros:2 (positions2,3), ones:2 (positions1,4) => wins=2, losses=2.
E: 2,0,0,0,0 -> zeros:4 (positions2-5) => wins=4, losses=0? Actually ones count: none, except first is 2 draw. So wins=4, losses=0.
F: 1,1,0,2,1 -> zeros:1 (pos3), ones:3 (pos1,2,5) => wins=1, losses=3.
Now sort: E wins=4, losses=0 top; A wins=3, losses=1 next; B wins=3, losses=2 (since same wins, fewer losses first, so A then B); D wins=2, losses=2; F wins=1, losses=3; C wins=0, losses=5. Order: E, A, B, D, F, C. That matches example output exactly! So indeed they have swapped meaning: 0 indicates win, 1 indicates loss, 2 indicates draw. But the problem statement explicitly says "0 for loss, 1 for win, 2 for a draw." Could be a mistake in the problem statement? Or perhaps we misread: Actually the original Japanese problem might have defined differently? The problem statement we have is in English but perhaps it's a translation error. Let's check the example: In dataset 1, team E has results: 2 0 0 0 0. If 0 means win, then E has 4 wins (against others except a draw against someone). That makes E top. Team C has all 1's, meaning all losses, so bottom. That fits. So the correct interpretation for this problem is: 0 = win, 1 = loss, 2 = draw. But the problem text says opposite. However, many problems of this type (like judging contest results) sometimes use 1 for win, 0 for loss. But the example contradicts that. So we must follow the example as correct interpretation.
Thus for each team, we count wins as number of 0's, losses as number of 1's, draws as 2's ignored.
Wait but then we must also be careful: The ranking uses number of wins and fewest losses. If 0 is win, then wins = count of 0; losses = count of 1. That fits.
Now check second dataset to verify:
Second dataset:
4
g 1 1 1
h 0 1 2
w 0 0 0
b 0 2 1
Teams: g, h, w, b.
Interpretation: 0=win, 1=loss, 2=draw.
Compute for each:
g: results: 1,1,1 => all 1's => wins=0, losses=3.
h: 0,1,2 => wins: one 0 (first), losses: one 1 (second), draw: one 2 (third) => wins=1, losses=1.
w: 0,0,0 => wins=3, losses=0.
b: 0,2,1 => wins: one 0 (first), draw: one 2 (second), loss: one 1 (third) => wins=1, losses=1.
Now sort:
- w: wins=3, losses=0 -> top.
- h: wins=1, losses=1.
- b: wins=1, losses=1 (same rank, so output in input order: h then b because h appeared before b? Actually input order: g (index0), h (index1), w (index2), b (index3). So for same wins/losses, order by input index: h then b.
- g: wins=0, losses=3.
Sorted names: w, h, b, g. That matches example output: w, h, b, g. Yes.
Thus the mapping is confirmed: 0 = win, 1 = loss, 2 = draw. So the problem statement is reversed. We'll adopt this.
Now implement.
Potential pitfalls: The input lines may have extra spaces; we'll handle splitting. Also team name is a single character, but we can treat as string.
Now design code.
Pseudo:
while True:
line = readline().strip()
if line == '' continue? But we can use input().
n = int(line)
if n == 0: break
teams = [] # each is dict or object: name, wins, losses, idx
for i in range(n):
parts = input().split()
name = parts[0]
results = parts[1:] # list of strings, length n-1
# ensure length is n-1
wins = 0
losses = 0
for r in results:
if r == '0':
wins += 1
elif r == '1':
losses += 1
# else if '2' ignore
teams.append((name, wins, losses, i)) # use tuple
# sort with key: (-wins, losses, idx)
teams_sorted = sorted(teams, key=lambda x: (-x[1], x[2], x[3]))
for team in teams_sorted:
print(team[0])
Implementation in Python.
Edge cases: n up to 10, so fine.
Also note: the input includes multiple datasets. We need to process until 0.
Now about input reading: we can use sys.stdin.read().splitlines() and iterate, but simpler: while True: line = input().strip() if not line: maybe break? But safer: while True: line = input(); if line.strip() == '0': break; else n = int(line). But if there are blank lines? Probably not. Use sys.stdin to handle.
We'll write a solve() function.
Let's code.
Now we should consider that team names are unique. Good.
Now output: after each dataset, print names each on new line. The example shows no extra blank lines. So just print names sequentially.
Now ready.
But before final, we need to double-check the interpretation regarding the ordering of results. In our counting, we simply count 0 and 1 in the list, ignoring which opponent it corresponds to. That yields correct ranking for the example. However, is there any scenario where the ordering matters? For example, if we need to handle ties using head-to-head? But ranking criteria only uses total wins and losses, not head-to-head. So it's fine.
But what about consistency? The input could be inconsistent if two teams report conflicting results for the same match. But the problem probably guarantees consistency. Even if not, we are just counting each team's reported outcomes; that would be the team's own perspective, but if they conflict, then the totals might not be complementary. However, ranking is defined based on these reported numbers? It might be that the numbers are the actual results of each match; they must be consistent. So it's fine.
Thus solution is straightforward.
Now about reading input: we must handle cases where there are trailing spaces or blank lines. We'll use standard input reading.
We'll produce code in Python.
Now test with provided example.
Will get correct output.
Now finalize.
Potential nuance: the problem statement says "the team name t is a single-byte alphabetic character." So we can treat as string.
Now we are done.
But we need to write the solution as a full program.
We'll output each dataset's names each on new line, no extra blank lines.
Now produce final answer.
Also note: The problem statement says "Input: A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros." So there is a line with '0' only.
Now produce final code.
We'll implement:
import sys
def solve():
data = sys.stdin.read().strip().splitlines()
# But careful: lines may have trailing spaces, we strip each line as we process.
# Alternative: iterate through lines with index.
i = 0
out_lines = []
while i < len(data):
line = data[i].strip()
i += 1
if line == '':
continue # skip empty lines? but unlikely
n = int(line)
if n == 0:
break
teams = []
for idx in range(n):
if i >= len(data):
break # but input should be valid
parts = data[i].strip().split()
i += 1
name = parts[0]
results = parts[1:]
# ensure length: should be n-1
wins = results.count('0')
losses = results.count('1')
teams.append((name, wins, losses, idx))
teams.sort(key=lambda x: (-x[1], x[2], x[3]))
for t in teams:
out_lines.append(t[0])
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()
That should work.
Now think about potential issues: Using .count('0') and .count('1') is fine because they are exactly those characters.
Now we have solution.
But ensure that the results list length is n-1; if not, maybe there are extra spaces or something; but .split() handles.
Now final answer.
However, the problem statement originally says 0 for loss, 1 for win. But we derived the opposite from example. Might the problem have a mistake? Many programming contest problems define 1 as win, 0 as loss. But example contradicts. Possibly the input in example uses different mapping? Wait, maybe the results ri are the outcomes for the opponents? That is, for team A, the numbers are the results of the opponents? Let's examine: If we keep original mapping (0 loss, 1 win), but then interpret the numbers as the opponent's results? For example, for A: 1 0 0 2 0. If these are the opponents' results (i.e., if 1 means opponent wins, 0 means opponent loses, 2 draw), then A's own wins would be number of 0's? Actually if the given numbers are the opponent's outcome, then when we see 0, it means opponent lost, so A won; 1 means opponent won, so A lost; 2 draw. So that again yields wins = count of 0, losses = count of 1. So that is the same as our interpretation (swap mapping). So perhaps the description "0 for loss, 1 for win" refers to the result from the perspective of the team, but the given numbers are from the perspective of the opponent? That would be confusing. The simpler is to accept that the example uses 0 as win, 1 as loss. So we'll code accordingly.
Given the example output matches that, we'll go with it.
Now final answer.
I'll provide explanation and code.
In the explanation, we will note that wins are counted as number of 0's, losses as number of 1's.
But to be safe, we could compute both? Not needed.
Thus final answer. ```python
import sys
def solve() -> None:
lines = sys.stdin.read().splitlines()
i = 0
output = []
while i < len(lines):
line = lines[i].strip()
i += 1
if line == "":
continue # skip empty lines, if any
n = int(line)
if n == 0:
break
teams = [] # (name, wins, losses, original_index)
for idx in range(n):
parts = lines[i].strip().split()
i += 1
name = parts[0]
# results are the next n-1 tokens
results = parts[1:]
wins = results.count('0')
losses = results.count('1')
# '2' means draw, ignored
teams.append((name, wins, losses, idx))
# sort by: more wins first, then fewer losses, then original order
teams.sort(key=lambda x: (-x[1], x[2], x[3]))
for t in teams:
output.append(t[0])
sys.stdout.write("\n".join(output))
if name == "main":
solve()