We need to parse the problem: Taro has n cards with scores; Hanako has m cards with scores. They want to exchange exactly one card from each so that after swapping, the sum of Taro's cards equals the sum of Hanako's cards. They must exchange even if sums already equal? Actually "they have to exchange their cards even if they already have cards of the same total score." So even if current totals equal, they still must perform an exchange. That means after exchange, the totals must be equal. So we need to find a pair (a, b) such that a is from Taro's hand, b from Hanako's hand, and after swapping (i.e., Taro gives a and receives b, Hanako gives b and receives a), the sums become equal.
Let T_sum = sum of Taro's cards initially. Let H_sum = sum of Hanako's cards initially.
After exchange: Taro's new sum = T_sum - a + b; Hanako's new sum = H_sum - b + a. They must be equal:
T_sum - a + b = H_sum - b + a
=> T_sum - a + b = H_sum - b + a
=> bring terms: T_sum - a + b - H_sum + b - a = 0
=> (T_sum - H_sum) - 2a + 2b = 0
=> 2(b - a) = H_sum - T_sum
=> b - a = (H_sum - T_sum) / 2
Let diff = H_sum - T_sum. Then we need b - a = diff/2. Since a and b are integers, diff must be even. If diff is odd, impossible.
But note that after exchange, they still must have equal sums; we can also compute condition:
T_sum - a + b = H_sum - b + a => rearr: (T_sum - H_sum) = 2a - 2b => a - b = (T_sum - H_sum)/2 => b - a = (H_sum - T_sum)/2. Same.
Thus we need to find a card a from Taro and b from Hanako such that b - a = D, where D = (H_sum - T_sum)/2 (if diff even). Also note that if multiple pairs exist, we need to output the pair with smallest sum a + b. The problem says: "If there is more than one way to exchange a pair of cards that makes the total scores equal, output a pair of scores whose sum is the smallest." So among valid pairs, minimize a + b.
Additionally, they must exchange exactly one card each, even if sums already equal. But if sums are already equal initially, diff=0, D=0, so we need b - a = 0 => a = b. So we need to exchange cards of equal value. But also they must exchange. So we need to find a pair where a from Taro equals b from Hanako. And we want smallest sum (i.e., smallest a + b = 2a, so essentially smallest a). So we need to pick the smallest equal values? But note there might be multiple pairs with equal a and b? Actually if a = b, the sum is 2a. So smallest sum corresponds to smallest a. So we want the smallest common value? However, need to ensure that we pick a card from each hand. But they could be the same score but not necessarily distinct cards; they exchange distinct cards. So we need to check if there exists some score s such that Taro has at least one card with score s and Hanako has at least one card with score s. Then we can exchange those cards. The smallest such s yields smallest sum. But what if there are multiple pairs with same a+b? The problem says output a pair with smallest sum; if there are ties? Probably any with smallest sum, but we may need to be deterministic: perhaps choose smallest a? But the problem doesn't specify tie-breaking beyond sum. In typical ACM problems, they'd define unique output: "If there is more than one, output a pair of scores whose sum is the smallest." If still multiple, I think any is fine? But the sample output seems to show specific values. Let's check sample:
Sample Input and Output:
First dataset:
2 2
1
5
3
7
Output: 1 3
Let's compute: Taro: 1,5 sum=6. Hanako: 3,7 sum=10. diff=4, D=2. Need b - a =2. Pairs: Taro a=1, Hanako b=3 => 3-1=2 => valid. Taro a=5, Hanako b=7 => 7-5=2 => valid. Sums: 1+3=4, 5+7=12, so smallest sum is 4 -> 1 and 3. Output matches.
Second dataset:
6 5
3
9
5
2
3
3
12
2
7
3
5
Let's parse: n=6, m=5. Taro's 6 numbers: 3,9,5,2,3,3? Actually lines: "3\n9\n5\n2\n3\n3" -> That's 6 numbers: 3,9,5,2,3,3. So T_sum =? 3+9=12, +5=17, +2=19, +3=22, +3=25. So T_sum=25. Hanako's 5 numbers: "12\n2\n7\n3\n5" -> 12+2=14, +7=21, +3=24, +5=29. So H_sum=29. diff=4, D=2. Need b - a =2. Now list Taro's cards: 3,9,5,2,3,3. Hanako's:12,2,7,3,5.
Compute differences: For each a in T, b in H: b - a =?
a=3: b=12 =>9 not 2; 2 => -1;7=>4;3=>0;5=>2 => valid (a=3,b=5). Also a=3 appears thrice, so multiple.
a=9: b=12=>3;2=>-7;7=>-2;3=>-6;5=>-4 none 2.
a=5: b=12=>7;2=>-3;7=>2 => valid (5,7) sum=12; also b=5? 5-5=0; b=3? -2. So (5,7) works.
a=2: b=12=>10;2=>0;7=>5;3=>1;5=>3 no 2? 5-2=3; 3-2=1; etc. Not valid? Actually 7-2=5; 12-2=10; 2-2=0; 3-2=1;5-2=3. So none.
a=3 (again): same (3,5).
a=3: (3,5) again.
So valid pairs: (a=3,b=5) sum=8; (a=5,b=7) sum=12. Smallest sum is 8 -> 3 and 5. Output: 3 5. Yes.
Third dataset:
4 5
10
0
3
8
1
9
6
0
6
I think n=4, m=5. Taro: 10,0,3,8 sum=21. Hanako: 1,9,6,0,6? Actually: "1\n9\n6\n0\n6" -> 1+9+6+0+6=22. So diff=1, odd => impossible. Output -1. matches.
Fourth dataset:
7 4
1
1
2
1
2
1
4
2
3
4
3
Wait reading: "7 4" then lines: 1,1,2,1,2,1,4 (these are 7 numbers) then 2,3,4,3 (these are 4 numbers) => Taro: 1,1,2,1,2,1,4 sum? Let's sum: 1+1=2, +2=4, +1=5, +2=7, +1=8, +4=12. So T_sum=12. Hanako: 2,3,4,3 sum=12. diff=0, D=0. Need a = b. So need a card from Taro and a card from Hanako with same score. Available Taro scores: 1 (four times? Actually list: 1,1,2,1,2,1,4 => there are four 1's? Let's count: 1,1,2,1,2,1,4 => entries: index1:1, index2:1, index3:2, index4:1, index5:2, index6:1, index7:4 => so 1 appears at indices 1,2,4,6 => four 1's. Also 2 appears twice (indices3,5). Also 4 appears once. Hanako: 2,3,4,3 => has 2,3,4,3 => scores: 2 (once), 3 (twice), 4 (once). So common scores: 2 and 4. Also maybe? 1 not in Hanako. So we can exchange a=2 from Taro and b=2 from Hanako, sum=4; or a=4 from Taro and b=4 from Hanako sum=8. Smallest sum is 4 from 2 and 2. But sample output: 2 2. So matches.
Fifth dataset:
2 3
1
1
2
2
2
n=2, m=3. Taro: 1,1 sum=2. Hanako: 2,2,2 sum=6. diff=4, D=2. Need b - a =2. Taro's a: 1,1. Hanako's b: 2,2,2. For a=1, b=2 gives 2-1=1 not 2. So no valid pair. Could also consider a=1, b=2 only. So none. Output -1. matches.
Thus the solution: For each dataset, compute T_sum, H_sum. diff = H_sum - T_sum. If diff % 2 != 0: output -1. Else D = diff//2. Then we need to find a pair (a, b) with a in Taro list, b in Hanako list such that b - a == D. Among these, pick the one with minimal a + b. If multiple with same minimal sum, perhaps any is fine? But note that a+b minimal might have ties. For example, if D=0, a=b, and there are multiple scores that are common, but we pick the smallest a+b, which is 2*min_common_score. That is unique only if the smallest common score is unique. If there are two different scores that yield the same sum? For a+b, if D != 0, it's possible that two different pairs have same sum but different (a,b). For instance, if (a,b) and (a',b') with a+b = a'+b' and both satisfy b-a = b'-a' = D. Then we need to decide which to output. The problem statement: "output a pair of scores whose sum is the smallest. If there is more than one way... output a pair ... whose sum is the smallest." That suggests if there are multiple with the same smallest sum, any would be acceptable? But typically judges accept any as long as sum is minimal; but sometimes they expect the smallest a (or lexicographically smallest). To be safe, we can define tie-breaking: among pairs with minimal sum, choose the one with smallest a (or smallest b) to be consistent with sample? In sample we didn't see tie. But maybe there is ambiguity. Usually in such problems, they want the smallest sum and if multiple, the smallest a or something? But the statement doesn't specify further. However, typical UVA/ICPC problems: "If there is more than one, output the pair whose first number is the smallest; if still tied, output the pair whose second number is the smallest." But they didn't say that. They only said "output a pair of scores whose sum is the smallest." So I'd assume any pair with minimal sum is accepted. But to be deterministic and perhaps match expected output, we can adopt the strategy: find minimal sum, then among those, choose minimal a, then minimal b, or simply iterate in a sorted order and pick first. Usually the judge checks set equivalence not ordering? Actually the output is just two numbers separated by space. If there are multiple correct outputs, the judge might have a unique expected answer. So we need to infer from problem source? This looks like a problem from UVA or some contest. Possibly from AIZU online judge? Actually the format "Taro and Hanako" is reminiscent of POJ or AOJ. I recall a problem "Taro and Hanako" about exchanging cards to equalize sums. Usually they require output with smallest sum, and if multiple, then the smallest first number? But let's search memory: There's a known problem "Taro and Hanako" from JOI? Actually I've seen "Taro and Hanako" from Aizu Online Judge problem "ALDS1_5_C"? Not sure. Let's think: The sample matches our algorithm if we simply take the minimal sum, and if multiple with same minimal sum, choose the one with minimal a (or the first found). But the problem statement says "output a pair of scores whose sum is the smallest." That's all. So likely any minimal sum pair is accepted; but judges often require a specific pair, usually the one with the smallest a (or the smallest b) implicitly because they generate output by sorting candidates. To be safe, we can adopt a standard: among all pairs (a, b) with b - a = D, find the minimal sum s = a + b. Then among those, choose the minimal a (or perhaps lexicographically smallest (a,b)). That would produce a unique answer. The sample doesn't contradict. So we'll implement: after finding candidates, we iterate over all a in Taro, b in Hanako, check condition, compute sum, keep track of min_sum, and for ties on sum, keep the smallest a (or perhaps smallest a then smallest b). Since sum is same, smallest a would imply also smallest b? If sum fixed and difference fixed, then a and b are determined: given D, if sum = S, then we have b - a = D, and a + b = S => solving: a = (S - D)/2, b = (S + D)/2. So if sum S is fixed, a and b are uniquely determined. Actually if S and D are known, a and b are determined. So if there are multiple pairs with the same sum S, they must have the same (a,b) because a and b are derived from S and D. But could there be multiple pairs with same a and b values? Yes, if there are duplicate cards, but the pair scores are the same numbers. So the pair (a,b) as numbers is the same. So the minimal sum uniquely determines the numbers a and b (since D is fixed). Because from S and D, we get a = (S - D)/2, b = (S + D)/2. So if there are multiple pairs with the same S, they must have the same a and b values. So there is no ambiguity; the minimal sum will give a unique pair of numbers (a,b). However, is it possible that two different pairs of cards (different indices) have same a and b values? They are the same numbers, so output would be same numbers. So that's fine. So we just need to find minimal possible sum of (a+b) among all (a,b) satisfying condition. That yields the numbers to output.
Thus algorithm: compute T_sum, H_sum, diff = H_sum - T_sum. If diff % 2 != 0: print -1. Else D = diff/2. We'll need to search for minimal sum.
We can approach by enumerating all pairs: n and m up to 100, so at most 10,000 pairs, trivial per dataset. Number of datasets not specified, but likely up to some limit; still fine.
We need to output -1 if no pair found.
One nuance: The condition b - a = D. If D positive, b > a; if D negative, b < a. That's fine.
Also, note that the scores are non-negative up to 100. So we can use simple loops.
Edge case: If diff even but no pair satisfies condition, output -1.
Now, careful with input format: The input consists of multiple datasets, terminated by "0 0". For each dataset, first line "n m", then n+m lines each containing a score. So we need to read until both zero.
The sample input appears to have multiple datasets concatenated. So our code should loop.
Implementation details:
while True:
read line; if line.strip() empty? better read using sys.stdin.
parse n, m.
if n==0 and m==0: break.
read n integers for Taro, then m for Hanako.
compute T_sum = sum(taro), H_sum = sum(hanako)
diff = H_sum - T_sum
if diff % 2 != 0: print(-1); continue
D = diff // 2
# find best pair
best_sum = INF (maybe large)
best_a = best_b = None
for a in taro:
for b in hanako:
if b - a == D:
s = a + b
if s < best_sum:
best_sum = s
best_a = a
best_b = b
if best_a is None: print(-1)
else: print(best_a, best_b)
Note: If D is large (like >100) possible that no match, fine.
But wait: There's a nuance: The exchange must involve exactly one card from each. If there are duplicates, any is fine because we output scores only.
Also, what if the best pair yields same sum but from multiple a,b? As argued, if D fixed and sum fixed, a and b are determined, so they must be the same numbers. So the code will pick the first with that sum; but if there is another pair with same sum but maybe a different (a,b) that also yields same sum? That would imply (a,b) different numbers but same sum and same difference? Let's solve: For two pairs (a1,b1) and (a2,b2) with b1 - a1 = D and b2 - a2 = D, and a1+b1 = a2+b2 = S. Solve: a1 = (S - D)/2, b1 = (S + D)/2; a2 = (S - D)/2, b2 = (S + D)/2. So they are identical. So no ambiguity.
But what if D is not integer? No, we already handled even diff.
Thus the above algorithm is sound.
However, there is a catch: The problem statement says "they have to exchange their cards even if they already have cards of the same total score." That means if sums are equal initially, we cannot simply output 0 0 or nothing; we must find an exchange that keeps them equal, which is a = b. That's covered by D=0. So we need to find a common score. So our algorithm will handle that.
Now, confirm with sample 4: T_sum=12, H_sum=12 => diff=0, D=0. We look for b - a =0 => a = b. Among pairs, we consider a=1,b? Hanako has 2,3,4,3 so no 1. So only a=2,b=2 and a=4,b=4. Sums: 4 and 8. Minimal sum 4 => output 2 2. Works.
Thus implementation straightforward.
Complexities: O(n*m) per dataset, n,m <=100, and datasets up to maybe unknown but fine.
Now, regarding input reading: Because the numbers are given one per line, we can simply use input() in Python to read each line. However, caution: there may be leading/trailing spaces? Usually not. But we should handle reading efficiently. Use sys.stdin to read all lines and iterate.
Simpler: while True:
line = sys.stdin.readline()
if not line: break
n,m = map(int,line.split())
if n==0 and m==0: break
taro = [int(sys.stdin.readline().strip()) for _ in range(n)]
hanako = [int(sys.stdin.readline().strip()) for _ in range(m)]
... process.
That's fine.
Alternatively, use sys.stdin.read().split() to get all tokens and process sequentially. But since numbers are each on their own line, reading line by line is also easy.
We need to output -1 as just "-1" without spaces.
Now, let's test with sample.
We'll also test with some edge cases:
Case: n=1,m=1, Taro=5, Hanako=5 => sums equal diff=0, D=0. Need a=b=5. So output 5 5. That is valid exchange.
Case: n=1,m=1, Taro=5, Hanako=7 => diff=2, D=1. Need b-a=1 => a=5,b=6? But Hanako has 7 only, 7-5=2 not 1. So no. Output -1.
Case: with multiple ties: Taro: [10,12], Hanako: [14,16], diff=?? Let's compute T_sum =22, H_sum=30, diff=8, D=4. Pairs: 10,14 => diff=4 sum=24; 12,16 => diff=4 sum=28; Also 10,16 => diff=6; 12,14 => diff=2. So best sum=24 => output 10 14. So that's fine.
Now, note: The algorithm must find a pair with minimal sum. The straightforward O(n*m) works.
But we could also use sorting to find minimal sum faster, but not needed.
One more nuance: The problem statement: "If there is more than one way to exchange a pair of cards that makes the total scores equal, output a pair of scores whose sum is the smallest." Our algorithm picks the smallest sum, but if there are multiple pairs with same smallest sum, they would be same numbers because of the reasoning. But is it possible that two pairs have same sum but different (a,b) numbers? Let's double-check: The condition is b - a = D. Suppose we have two pairs (a1,b1) and (a2,b2) with b1 - a1 = D, b2 - a2 = D. Sum S1 = a1+b1, S2 = a2+b2. If S1=S2, does it force a1=a2? Let's solve: a1 = (S1 - D)/2, b1 = (S1 + D)/2. Similarly a2 = (S2 - D)/2, b2 = (S2 + D)/2. Since S1=S2, a1=a2, b1=b2. So yes, identical numbers. So no ambiguity. So we just need to find the minimal sum.
Thus algorithm is sound.
Edge: If D is not integer, we output -1.
Potential pitfalls: The sum may overflow? Not with these bounds.
Now, also consider the case where diff is even but D is negative. For example, T_sum > H_sum, so diff negative, D negative. Our condition b - a = D (negative) means a > b. That's fine. We still need to find a,b with that difference. The sum a+b may be minimal? But note that a and b are non-negative, so sum is non-negative. The minimal sum might be zero if a=0 and b = D? but if D negative, b would be negative? Actually if D negative, b - a negative, b < a. But b can be 0 if a = -D? For D negative, say D = -3, then need b - a = -3 => b = a - 3. If a=3, b=0 possible if Hanako has 0. So sum = 3. So minimal sum might be something else. So our algorithm handles negative D.
Now we need to be careful: b - a == D, where D can be negative. So we compute integer.
Now let's test with a case: n=1,m=1, Taro=7, Hanako=5 => T_sum=7,H_sum=5 diff=-2, D=-1 (since -2/2=-1). Need b - a = -1 => 5 - 7 = -2? Not -1. So no pair. But maybe Taro=8, Hanako=6 => diff=-2, D=-1 => b-a = -1 => 6-8=-2, not -1. So none. But if Taro=5, Hanako=3? diff=-2, D=-1, need b-a=-1 => 3-5=-2 not -1. So not working. Actually to get b-a = -1, need b = a-1. For Taro a=5, need b=4. So only if Hanako has 4 and Taro 5. So D negative is okay.
Our code: b - a == D, where D is negative. We'll compute correctly.
Now, also check scenario where D=0 but no common score, then output -1. That's correct.
Now, we should think about the possibility of exchanging cards that are the same? For example, if Taro and Hanako both have the same card score, they can exchange those identical cards. That is allowed. The problem didn't forbid exchanging same value. In D=0, a=b is required, so yes.
Now, consider the case where there are multiple pairs with minimal sum: But as argued, they would be same numbers, so output is same.
Thus the solution is straightforward.
Now, about input termination: "0 0". We need to ensure that we don't treat the following as datasets. The last line is "0 0". There is no extra data.
Now, regarding output formatting: For each dataset, output a single line containing two numbers or -1. The sample output has blank lines? Actually sample shows output lines separate, no extra blank lines. So we output exactly one line per dataset.
Now, write code.
But perhaps there is a more efficient method: Instead of nested loops, we can use sets or sorting. Since n,m <=100, nested loops are fine.
Implementation in Python:
import sys
def solve():
out_lines = []
while True:
line = sys.stdin.readline()
if not line:
break
n_m = line.strip().split()
if not n_m:
continue # skip empty lines? but not necessary
n, m = map(int, n_m)
if n == 0 and m == 0:
break
taro = [int(sys.stdin.readline().strip()) for _ in range(n)]
hanako = [int(sys.stdin.readline().strip()) for _ in range(m)]
t_sum = sum(taro)
h_sum = sum(hanako)
diff = h_sum - t_sum
if diff % 2 != 0:
out_lines.append("-1")
continue
D = diff // 2
best_sum = None
best_a = best_b = None
for a in taro:
for b in hanako:
if b - a == D:
s = a + b
if best_sum is None or s < best_sum:
best_sum = s
best_a = a
best_b = b
if best_a is None:
out_lines.append("-1")
else:
out_lines.append(f"{best_a} {best_b}")
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()
That should work.
But we need to be careful: In Python, reading with sys.stdin.readline() may produce lines with trailing newline, we use strip() to remove whitespace. Also, if there are blank lines in input? Unlikely.
Now, verify with sample input.
We'll simulate quickly.
Sample input (as provided) seems to have multiple datasets separated. Our code would read first line "2 2", then read next 4 lines for numbers, compute output, then read next line "6 5", then 11 numbers (6+5) etc. But careful: The sample input appears to be:
2 2
1
5
3
7
6 5
3
9
5
2
3
3
12
2
7
3
5
4 5
10
0
3
8
1
9
6
0
6
7 4
1
1
2
1
2
1
4
2
3
4
3
2 3
1
1
2
2
2
0 0
But the lines appear to be correct. After the dataset with "2 3", there is "0 0". So our code should process correctly.
We might want to test with that input string:
We'll simulate quickly.
But note: The second dataset: after "6 5", there are 6 numbers for Taro and 5 for Hanako: we read 6 lines: "3","9","5","2","3","3" then 5 lines: "12","2","7","3","5". That matches.
Third dataset: "4 5", then Taro 4: "10","0","3","8", Hanako 5: "1","9","6","0","6". Yes.
Fourth: "7 4", then Taro 7: "1","1","2","1","2","1","4", Hanako 4: "2","3","4","3". Yes.
Fifth: "2 3", Taro 2: "1","1", Hanako 3: "2","2","2". Yes.
Then "0 0". So all good.
Now, output:
-1 for third and fifth? Actually sample output:
1 3
3 5
-1
2 2
-1
So yes.
Now, check third dataset: diff=1 => odd => -1, correct.
Fifth: diff=4 => even D=2, need b - a =2. Taro a=1 => b=3? Hanako has only 2's, so b=2 gives diff=1, no. So no pair => -1.
So code works.
Now, potential pitfalls: When diff is even but D is not an integer? But we used integer division.
Now, verify scenario where best sum could be zero: if a=0 and b=0 and D=0, then output 0 0. That is valid. But we must be careful: best_sum initialized as None; we can handle that.
Now, we should ensure that we read numbers correctly. In some online judges, input may be large; but here it's small.
Thus solution is ready.
However, we need to be careful about reading lines: using sys.stdin.readline() may be fine. But sometimes they may have extra spaces at end of lines. strip() handles.
Alternatively, we could read all tokens using sys.stdin.read().split() and process sequentially. This is simpler to avoid line-by-line errors. Let's consider that approach:
Read all tokens from sys.stdin, convert to ints. Then iterate through tokens. The structure: while we have tokens, read n, m; if both zero break; then read next n+m numbers. That works. However, the input terminates with 0 0, so we don't need to worry about EOF. Using token list is easy. For example:
import sys
def solve():
data = sys.stdin.read().split()
it = iter(data)
out = []
while True:
try:
n = int(next(it))
m = int(next(it))
except StopIteration:
break
if n == 0 and m == 0:
break
taro = [int(next(it)) for _ in range(n)]
hanako = [int(next(it)) for _ in range(m)]
# process ...
print("\n".join(out))
That would work even if there are blank lines. It's simpler.
But careful: The input format says each dataset: first line n m, then subsequent n+m lines each contain a score. The token reading approach treats them all as integers regardless of line breaks. That's fine.
Thus I'll adopt the token reading method.
Now, final code:
import sys
def main():
tokens = sys.stdin.read().split()
idx = 0
out_lines = []
while idx < len(tokens):
n = int(tokens[idx]); m = int(tokens[idx+1]); idx += 2
if n == 0 and m == 0:
break
taro = []
for _ in range(n):
taro.append(int(tokens[idx])); idx += 1
hanako = []
for _ in range(m):
hanako.append(int(tokens[idx])); idx += 1
t_sum = sum(taro)
h_sum = sum(hanako)
diff = h_sum - t_sum
if diff % 2 != 0:
out_lines.append("-1")
continue
D = diff // 2
best_sum = None
best_a = best_b = None
for a in taro:
for b in hanako:
if b - a == D:
s = a + b
if best_sum is None or s < best_sum:
best_sum = s
best_a = a
best_b = b
if best_a is None:
out_lines.append("-1")
else:
out_lines.append(f"{best_a} {best_b}")
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
That is complete.
Now, double-check with sample input.
I'll run mental simulation:
tokens = ["2","2","1","5","3","7","6","5","3","9","5","2","3","3","12","2","7","3","5","4","5","10","0","3","8","1","9","6","0","6","7","4","1","1","2","1","2","1","4","2","3","4","3","2","3","1","1","2","2","2","0","0"]
Processing:
idx=0: n=2,m=2 -> taro=[1,5], hanako=[3,7]; compute diff=10-6=4 even D=2. Check pairs: (1,3) sum=4; (5,7) sum=12 => best (1,3). Output "1 3". idx now after reading numbers: after reading taro (2) and hanako (2), idx points to next token "6". Good.
Next: n=6,m=5 -> taro=[3,9,5,2,3,3], hanako=[12,2,7,3,5] -> diff=29-25=4 even D=2 => check pairs: (3,5) sum=8; (5,7) sum=12 -> best (3,5) -> output "3 5". Good.
Next: n=4,m=5 -> taro=[10,0,3,8], hanako=[1,9,6,0,6] -> t_sum=21, h_sum=22? Actually sum hanako: 1+9+6+0+6=22 -> diff=1 odd -> output "-1". Good.
Next: n=7,m=4 -> taro=[1,1,2,1,2,1,4], hanako=[2,3,4,3] -> sums both 12 diff=0 -> D=0. Check pairs: a=b common: 2 (from taro) and 2 (from hanako) -> sum=4; also 4 and 4 -> sum=8. best sum 4 -> output "2 2". Good.
Next: n=2,m=3 -> taro=[1,1], hanako=[2,2,2] -> t_sum=2, h_sum=6 diff=4 even D=2 -> need b-a=2: a=1,b=2 -> 2-1=1 !=2; no valid -> output "-1". Good.
Next: after that, idx reads next tokens: "0","0" -> n=0,m=0 -> break. Output lines: ["1 3","3 5","-1","2 2","-1"]. Print with newline. Matches sample.
All good.
Now, consider potential edge: If diff is even, D might be such that b - a = D, but a and b are both 0? That is possible. best_sum = 0, then output "0 0". That's acceptable.
Now, we should be careful: For D=0 and there are common zeros, best sum could be 0. So output "0 0". That is fine.
Now, complexity is fine.
Thus the solution is correct.
I will now produce the final answer with code and explanation.
But the request says "Write code in python". So I'll output the code block.
But also maybe they want explanation? The problem says "Which of the cards should be exchanged with which?" but it's a programming problem. Usually they want code.
Given the chat, I'll provide solution with code.
But note: The instruction in the problem is to output the result; my code will do that.
Thus final answer: Provide Python code.
I'll include a comment about approach.
Now, I'll produce the final message. ```python
import sys
def main():
# Read all tokens from input
tokens = sys.stdin.read().split()
idx = 0
out = []
while idx < len(tokens):
n = int(tokens[idx])
m = int(tokens[idx + 1])
idx += 2
# Termination condition
if n == 0 and m == 0:
break
# Taro's cards
taro = [int(tokens[idx + i]) for i in range(n)]
idx += n
# Hanako's cards
hanako = [int(tokens[idx + i]) for i in range(m)]
idx += m
t_sum = sum(taro)
h_sum = sum(hanako)
diff = h_sum - t_sum
# If the difference is odd, no exchange works
if diff % 2 != 0:
out.append("-1")
continue
D = diff // 2 # required difference b - a
best_sum = None
best_a = best_b = None
# Try all pairs
for a in taro:
for b in hanako:
if b - a == D:
s = a + b
if best_sum is None or s < best_sum:
best_sum = s
best_a = a
best_b = b
if best_a is None:
out.append("-1")
else:
out.append(f"{best_a} {best_b}")
sys.stdout.write("\n".join(out))
if name == "main":
main()