We need to solve the problem: given two strings s and t of length n consisting only of 'a' and 'b', we can perform any number of operations: each operation we choose an index pos1 in s and pos2 in t, and swap s[pos1] with t[pos2]. Goal: make s and t equal (i.e., for each i from 1 to n, s[i] == t[i] after operations). Need minimum number of operations, and output any optimal sequence; if impossible, output -1.
We need to find minimal swaps between two strings to make them equal.
Observation: Each operation swaps a character from s with a character from t. Since both strings contain only 'a' and 'b', we can think about mismatches.
Let’s define mismatched positions: For index i (1-indexed), if s[i] != t[i], then we have a mismatch. There are two types: either s[i] = 'a', t[i] = 'b' (call this type ab) or s[i] = 'b', t[i] = 'a' (type ba). Let’s denote count of ab mismatches as x, and ba mismatches as y.
Goal: after operations, we want s[i] = t[i] for all i. Since swapping characters between s and t changes both strings, we need to resolve mismatches.
We can also think about overall counts: total number of 'a's in s plus t should be even? Actually each string individually has length n, but total number of 'a's across both strings must be 2n? Actually each string length n; total characters in both strings is 2n. For them to be made equal, I suspect it's necessary that the total number of 'a' across both strings is even? Let's derive.
After making both strings equal, say final string u (both equal to u). Then u has exactly n characters. The total number of 'a's in s and t originally is count_a(s) + count_a(t). After operations, that total remains the same because we are just swapping characters between s and t, not changing the multiset of characters across both strings. In final state, both strings equal u, so total number of 'a's is 2 * count_a(u). Therefore count_a(s) + count_a(t) must be even. More precisely, must be equal to 2 * something, i.e., it must be even. So if count_a(s) + count_a(t) is odd, impossible. Similarly count_b(s) + count_b(t) = 2n - (count_a(s)+count_a(t)) must also be even (automatically even if 2n even, but if count_a sum odd then count_b sum odd as well). So necessary condition: total number of 'a' across both strings is even. Is it also sufficient? We'll see.
Also, after making equal, each string must have exactly half of total 'a's? Since both strings identical, each must have exactly (count_a(s)+count_a(t))/2 'a's. So that number must be integer, which is the even condition.
Now, the operation: swapping s[pos1] with t[pos2]. This can be used to correct mismatches efficiently.
Let's model the problem as we have two strings. At each index i, if s[i] != t[i], we have a "discrepancy". We can fix discrepancies by swapping characters. Observe that if we have two indices i and j such that s[i] = 'a', t[i] = 'b' (type ab) and s[j] = 'b', t[j] = 'a' (type ba), we can fix both with a single operation: swap s[i] with t[j]? Let's see: initially, s[i]='a', t[i]='b'; s[j]='b', t[j]='a'. If we swap s[i] with t[j], then s[i] becomes 'a'? Actually t[j] is 'a', so s[i] becomes 'a' (same as before, so no change?), wait careful:
- Swap s[i] and t[j]. After swap:
- s[i] becomes old t[j] = 'a'
- t[j] becomes old s[i] = 'a'? Actually old s[i] = 'a', so t[j] becomes 'a'.
But we want s[i] to equal t[i] and s[j] = t[j]. Currently after swap, we have:
- s[i] = 'a', t[i] = 'b' (unchanged)
- s[j] = 'b' (unchanged), t[j] = 'a' (now 'a' from s[i]? Actually after swap, t[j] = 'a', but s[j] is still 'b', so s[j] != t[j] (still mismatch type ba? Actually s[j]='b', t[j]='a' -> ba). So both mismatches remain.
That didn't fix. Perhaps swap s[i] with t[i]? That would be direct swapping of the mismatched pair, but that would correct that specific index but might affect others? If we swap s[i] with t[i] at a mismatched index, then after swap s[i] becomes t[i] (original) and t[i] becomes s[i] (original). Since originally s[i]!=t[i], after swap they become swapped: s[i] = original t[i], t[i] = original s[i]; they are still not equal unless the original s[i] and t[i] are swapped? Actually check: original s[i]=a, t[i]=b. Swap s[i] and t[i] -> s[i]=b, t[i]=a. Still s[i]!=t[i]. So that just flips the type (ab becomes ba). That doesn't resolve either. So direct swap at same index is not useful; it just changes the type.
So we need to consider cross swaps: maybe swap s[i] (from ab) with t[j] (from ba) where i and j are positions. After swapping s[i] (a) with t[j] (a) (since t[j] is 'a' in ba mismatch) would produce s[i] becomes 'a' (same), t[j] becomes 'a' (same) — no change. Actually swapping two a's does nothing. So we need to swap a with b. So we need to swap s[i] (a) from an ab mismatch with t[j] (b) from something else? But t[j] from ba mismatch is 'a', not 'b'. So we need a b in t that we can swap. Alternatively, we could swap s[i] (a) with t[j] where t[j] = b. If t[j] is from an ab mismatch? At position j with ab mismatch, we have s[j]=a, t[j]=b. So t[j] is b. So swapping s[i] (a) from one ab mismatch with t[j] (b) from another ab mismatch would turn: s[i] becomes b (good? after swap s[i]=b, but t[i] is b (since original t[i]=b from ab mismatch) — check: at i ab: s[i]=a, t[i]=b. After swapping s[i] with t[j] (b), s[i] becomes b, so now s[i]==t[i]==b; t[j] becomes a (old s[i]=a). At position j: originally s[j]=a, t[j]=b; after swap t[j] becomes a, so s[j]==a, t[j]==a? Actually t[j] becomes a, s[j] remains a, so now s[j]==t[j]==a. So both mismatches i and j are resolved! Great! So swapping s[i] from an ab mismatch with t[j] from another ab mismatch resolves both mismatches in one operation. Similarly, swapping s[i] from a ba mismatch (s[i]=b) with t[j] from another ba mismatch (t[j]=a) resolves both? Let's check: ba mismatch: s[i]=b, t[i]=a. Swap s[i] (b) with t[j] (a) from another ba mismatch. After: s[i] becomes a (old t[j]=a) -> now s[i]==t[i]==a (since t[i]=a); t[j] becomes b (old s[i]=b) -> s[j]=b (original), t[j]=b -> s[j]==t[j]==b. So resolves both. So we can pair same-type mismatches (ab with ab or ba with ba) to fix two mismatches with one swap.
What about swapping ab with ba mismatches? Suppose we have i: ab (s[i]=a, t[i]=b) and j: ba (s[j]=b, t[j]=a). Consider swapping s[i] (a) with t[j] (a) -> both a, no change. Or swapping s[i] with t[i]? Already saw useless. Or swapping s[i] with t[j] where t[j] is a? That does nothing. Or swapping s[j] (b) with t[i] (b) -> both b, no change. Or swapping s[i] with t[i]? No. So cross-type mismatch cannot be fixed directly with one swap. But perhaps we can use two swaps to fix them, maybe by first converting one type to the other then pairing. Actually we could swap s[i] (a) with t[k] where k is something else, but likely it's optimal to pair same-type mismatches and handle leftover mismatches of opposite types separately.
Now, what about using positions that are already matching? Suppose we have a match: s[p] = t[p] = a, and we have a mismatched ab at i. Could we use that match to help? Possibly, but it might increase operations. However, we aim for minimum number of operations. The pairing of same-type mismatches uses 1 operation for 2 mismatches, which is optimal because each operation can change at most two positions to become correct? Let's think: In one swap, we change s[pos1] and t[pos2]. We want to make s and t equal at all indices. The effect of a swap can resolve up to 2 mismatches, as seen. Could it resolve more than 2? Possibly if pos1 equals pos2? But we saw swapping same index doesn't fix; it just flips mismatch. That might reduce the number of mismatches if combined? But maybe not. So optimal strategy is to maximize the number of operations that fix two mismatches at once. So we want to pair up mismatches of same type. After pairing all possible same-type mismatches, we will have either 0 or 1 leftover mismatch of each type? Since we can only pair in groups of two. So if x and y are counts of ab and ba mismatches respectively, we can pair within each type: number of operations from pairing ab's = floor(x/2), pairing ba's = floor(y/2). After that, remaining mismatches: x%2 ab and y%2 ba.
If both x%2 and y%2 are 0, we are done. If one of them is 1 and the other is 1, then we have one ab and one ba left. How can we resolve these? They cannot be fixed directly with one swap. Perhaps we need two swaps? Let's analyze.
Suppose we have one ab mismatch at index i and one ba mismatch at index j. We want both positions to become matching. We can try to perform two operations. For instance: swap s[i] (a) with t[i] (b)? That would make s[i]=b, t[i]=a, turning ab into ba; but then we have two ba mismatches? Actually after that, we have ba at i and ba at j. Then we can pair the two ba with one swap: swap s[i] (b) with t[j] (a) resolves both. So total 2 operations. But we could also do other sequences. However, is it always possible? Yes. So handling one ab and one ba takes 2 operations.
But could we do it in 1 operation? Perhaps by swapping s[i] with t[k] where k is some index that currently matches? Let's test: Suppose we have a match at k: s[k]=t[k]=a. At i ab: s[i]=a, t[i]=b; j ba: s[j]=b, t[j]=a. If we swap s[i] (a) with t[k] (a), then s[i] becomes a (unchanged), t[k] becomes a (unchanged), no effect. Not helpful. If we swap s[i] (a) with t[j] (a) also no change. If we swap s[i] (a) with t[l] where t[l] is b (maybe from another match? If match is b? s[l]=t[l]=b, then t[l]=b) then after swap: s[i] becomes b, so s[i]==t[i]==b resolved; t[l] becomes a, so at l we have s[l]=b, t[l]=a -> becomes ba mismatch. So we resolve i but create a ba at l. So net mismatches: we started with ab and ba; after operation we have ba at j and new ba at l? Actually originally we had ab at i, ba at j, and match at l (both b). After swapping s[i] with t[l] (b), s[i]=b (matches t[i]=b, good), t[l]=a (now s[l]=b, t[l]=a -> ba mismatch). So now mismatches: ba at j and ba at l (two ba). Then we can pair them in one swap, total 2 operations. So still 2. Could we use two swaps but maybe sometimes only 1? Could there be a single swap that resolves both? Consider swapping s[i] (a) with t[j] (a) does nothing. Swapping s[j] (b) with t[i] (b) does nothing. So not possible. So minimum operations for one ab and one ba is 2.
Thus total minimum operations = floor(x/2) + floor(y/2) + 2*( (x%2) * (y%2) )? Actually if both remainders are 1, we need 2 more ops. But is that always the minimum? Let's check if we can sometimes do better by using matches? Possibly we could use a match to resolve both with 2 operations as above anyway. So the number of operations required is (x//2 + y//2) + ( (x%2) * 2? Actually if x%2 = 1 and y%2 = 1, then we need extra 2 operations. But is it always possible to perform these extra 2 operations? Yes, as long as there exists at least one match or something? Let's examine: For the case of one ab and one ba, we need to convert one of them to the other type and then pair. The method we gave used the two mismatched indices themselves: first swap s[i] and t[i] (or s[j] and t[j]) to convert type, then swap s[i] and t[j] (or similar) to fix both. But swapping s[i] with t[i] does not require any external index; it's valid. So we can always do: operation1: swap s[i] with t[i]? Actually check: start i: ab, j: ba. Option: swap s[i] (a) with t[i] (b). After that, i becomes: s[i]=b, t[i]=a -> ba. So now we have two ba mismatches (i and j). Then operation2: swap s[i] (b) with t[j] (a). After that, i: s[i]=a? Wait: after op2: swap s[i] (b) with t[j] (a). At that moment, s[i] is b, t[j] is a. After swap: s[i] becomes a, t[j] becomes b. Now check: i: s[i]=a, t[i]=a (since t[i] is a from after op1? Actually after op1, t[i]=a? Wait careful:
Initial:
i: s_i = a, t_i = b.
j: s_j = b, t_j = a.
Op1: swap s_i and t_i.
After op1:
s_i = b, t_i = a. (i becomes ba)
j unchanged: s_j = b, t_j = a. (ba)
Now both i and j are ba.
Op2: swap s_i (b) with t_j (a).
After op2:
s_i = a, t_j = b.
Now:
i: s_i = a, t_i = a => match.
j: s_j = b, t_j = b => match.
Great! So 2 ops work. So we have a sequence using only indices i and j. So no need for external matches. So it's always possible.
Thus total minimum operations = x//2 + y//2 + 2 * (x % 2) (since x%2 == y%2 if both odd? Actually if x%2=1 and y%2=1, then 2; if one is 1 and the other 0, then after pairing same types we have one leftover mismatch. But can we fix a single leftover mismatch? If x%2=1 and y%2=0, we have one ab left, but no ba. Is it possible to resolve? Let's think.
If there is only one mismatched position of type ab (and no ba), can we make strings equal? After pairing all other mismatches, we have an odd count of ab mismatches. Let's check global conditions. The total number of mismatches is x + y. But also global counts of a and b. For strings to be equal, total number of a in s plus t must be even, which we already required. If x%2=1 and y%2=0, then the number of ab mismatches is odd, ba mismatches even. Does this satisfy global condition? We can derive a relationship between counts and mismatches.
Let count_a(s) = A_s, count_a(t) = A_t. For each index, if s[i]=t[i], then both are either aa or bb. Let M_aa = number of indices where both are a; M_bb = both b. For mismatches: ab count = x, ba count = y.
Then A_s = M_aa + x (since at ab, s is a; at ba, s is b; at aa, s is a; at bb, s is b contributes 0 to a). Actually:
- At aa positions: s has a -> contributes 1.
- At bb positions: s has b -> contributes 0.
- At ab positions: s has a -> contributes 1.
- At ba positions: s has b -> contributes 0.
So A_s = M_aa + x.
Similarly A_t = M_aa + y? Because at aa, t is a; at ba, t is a? Let's compute:
- aa: t has a -> 1
- bb: t has b -> 0
- ab: t has b -> 0
- ba: t has a -> 1
Thus A_t = M_aa + y.
So A_s + A_t = 2M_aa + x + y. For equal strings, we need A_s = A_t = n - (something)? Actually after equalizing, both strings become identical, so each must have exactly (A_s + A_t)/2 = M_aa + (x+y)/2 a's. That must be integer, so (x+y) must be even. But we already have condition that total a sum must be even, which is equivalent to (x+y) even because 2M_aa is even. So x+y must be even.
Now if x%2=1 and y%2=0, then x+y is odd -> impossible. So such scenario cannot happen under the necessary condition. Similarly if x%2=0 and y%2=1, x+y odd -> impossible. Therefore, if the total a sum condition holds (i.e., x+y even), then x and y have same parity. Because x+y even => x%2 == y%2. So after the necessary condition, we will have either both even or both odd. Both even means we can pair all mismatches within same type and be done (total ops = x/2 + y/2). Both odd means one leftover of each type, and we need 2 extra ops. So the condition for possibility is that x and y have same parity, which is equivalent to total number of a across both strings being even.
But wait: could there be other impossibilities? For example, if the strings are like "a" and "b", n=1, x=1? Actually s='a', t='b' => ab mismatch => x=1, y=0 => x+y=1 odd => impossible. That matches output -1. So indeed the condition is necessary and seems sufficient given we can always find a sequence of operations to achieve equality when parity condition holds. We should confirm with examples. Example 3: n=8, s="babbaabb", t="abababaa". Let's compute mismatches. s: b a b b a a b b? Actually write indices 1..8:
s: b a b b a a b b? Wait string "babbaabb": positions: 1:b, 2:a, 3:b, 4:b, 5:a, 6:a, 7:b, 8:b? Actually "babbaabb" -> b a b b a a b b? Let's check: "babbaabb" length 8. Spell: b a b b a a b b? That seems: b (1), a (2), b (3), b (4), a (5), a (6), b (7), b (8). t: "abababaa": a b a b a b a a? Actually: a (1), b (2), a (3), b (4), a (5), b (6), a (7), a (8). So compare:
i=1: s=b, t=a => ba -> y=1
i=2: s=a, t=b => ab -> x=1
i=3: s=b, t=a => ba -> y=2
i=4: s=b, t=b => match (bb)
i=5: s=a, t=a => match (aa)
i=6: s=a, t=b => ab -> x=2
i=7: s=b, t=a => ba -> y=3
i=8: s=b, t=a => ba? t[8]=a, s[8]=b => ba -> y=4? Actually s[8]=b, t[8]=a => ba so y=4. Wait recount: y = positions 1,3,7,8 => 4. x = positions 2,6 => 2. So x=2 (even), y=4 (even). Total mismatches 6, x/2 + y/2 = 1+2=3 ops. That's what output says: 3 operations. So matches.
Example 1: n=4, s="abab", t="aabb". Compute:
s: a b a b
t: a a b b
i=1: a vs a -> match
i=2: b vs a -> ba? s=b, t=a => ba -> y=1
i=3: a vs b -> ab -> x=1
i=4: b vs b -> match
Thus x=1, y=1 (both odd). So ops = floor(1/2)+floor(1/2)=0 + 2 extra =2. Output 2 operations. Indeed.
Thus the minimal number of operations formula: k = (x//2 + y//2) + (x % 2) * 2? But when x%2=1, y%2=1, extra 2; when both 0, extra 0. So k = (x+y)/2? Let's check: (x+y)/2 would be (2)/2=1? Actually x=1,y=1 => (1+1)/2=1, but we need 2. So not that. Actually x//2 + y//2 + 2*(x%2). Since x%2==y%2, 2*(x%2) = 2 if odd else 0. So total = (x+y)/2 + (x%2)? Because (x+y)/2 = (x//2 + y//2) + (x%2 + y%2)/2 = (x//2 + y//2) + (x%2) (since x%2=y%2). So total = (x+y)/2 + (x%2). For x=1,y=1: (2)/2+1=1+1=2. Good. For even: (x+y)/2 +0 = (x+y)/2. For x=2,y=4: (6)/2=3. So formula works. But careful: (x+y)/2 is integer only when x+y even, which is guaranteed if same parity.
Now we also need to produce an actual sequence of operations achieving this minimum. So we must construct operations: pair up ab mismatches with each other, pair up ba mismatches with each other, and if there is one of each left, perform two operations as described (or some other method that also works).
Now, the challenge: we need to output the indices used in each operation. We can choose any optimal sequence. So we need to find lists of mismatched positions.
Let’s denote arrays:
ab_positions: list of indices i where s[i]='a' and t[i]='b'.
ba_positions: list of indices i where s[i]='b' and t[i]='a'.
Now, for pairing ab mismatches, we need to swap s[i] with t[j] for two distinct i, j from ab_positions. This resolves both. But we have to be careful: after swapping s[i] and t[j], both positions become matched. So we can output operation (i, j) where i and j are indices in s and t respectively. But note: The operation swaps s[pos1] with t[pos2]. In our plan for ab pairing, we swap s[i] (from ab) with t[j] (from another ab). That is an operation with pos1 = i, pos2 = j. That works because t[j] is at index j (which is a mismatched ab position). After swap, s[i] becomes t[j] (which is 'b'), and t[j] becomes s[i] (which is 'a'). Check: For i in ab: s[i]='a', t[i]='b'. For j in ab: s[j]='a', t[j]='b'. After swapping s[i] and t[j]: s[i] = 'b' (old t[j]), so now s[i] = t[i] = 'b' (since t[i]='b') -> matches. t[j] = 'a' (old s[i]), so t[j] = s[j] = 'a' -> matches. So both resolved.
Thus for each pair (i, j) of two ab positions, we output (i, j). Similarly for ba positions: we swap s[i] (from ba) with t[j] (from another ba). In ba: s[i]='b', t[i]='a'; s[j]='b', t[j]='a'. After swapping s[i] and t[j]: s[i] becomes 'a' (old t[j]='a'), so s[i]=t[i]='a'? t[i]='a', so matches. t[j] becomes 'b' (old s[i]='b'), so t[j]=s[j]='b', matches. So output (i, j). Works.
Now for the leftover one ab and one ba: say i in ab, j in ba. We need two operations. One sequence:
- swap s[i] with t[i] (or s[j] with t[j]? Actually we need to be careful: swapping s[i] with t[i] changes both strings at index i. That's allowed? Yes, we can choose any positions pos1 in s and pos2 in t; they can be the same index or different. So operation (i, i) is valid? The problem says: choose index pos1 in s, index pos2 in t, and swap s_{pos1} with t_{pos2}. It doesn't forbid pos1 == pos2. So we can swap s[i] with t[i] directly. That is allowed. So we can perform (i, i) as first operation. That transforms i from ab to ba. Then both mismatches become ba. Then we can pair them with operation (i, j) (swap s[i] with t[j]) to fix both. But careful: After first operation (i,i), we have s[i] becomes original t[i] = 'b', t[i] becomes original s[i] = 'a'. So now both i and j are ba. Then we do operation (i, j) swapping s[i] (now 'b') with t[j] ('a')? Wait after first op, t[j] remains 'a' (original). So swapping s[i] ('b') with t[j] ('a') gives: s[i] becomes 'a', t[j] becomes 'b'. Then we have s[i] = 'a', t[i] = 'a' (since after first op t[i] = 'a'), so match at i; s[j] = 'b', t[j] = 'b', match at j. So that works. So output operations: (i, i) and (i, j).
Alternatively, we could do (j, j) then (i, j) or other variants. But we must ensure that the operations are minimal and valid.
But is it allowed to output (i, i)? The problem says choose index pos1 in s, index pos2 in t, and swap. It doesn't say they have to be distinct. So yes.
However, could there be a case where we cannot use (i,i) because after the first operation (i,i) we might affect other mismatches? Since we only have these two left, it's fine. Also we could use a different approach: swap s[i] with t[j] first? But that does nothing because s[i]='a', t[j]='a' -> no change. So not useful. Or swap s[j] with t[i]? s[j]='b', t[i]='b' -> no change. So the sequence above is valid.
But is there a possibility that using (i,i) and (i,j) is always valid? Yes, because i and j are indices. They could be equal? But i and j are distinct because one is ab and one is ba; they could be same index? Actually can an index be both ab and ba? No, because at a given index s[i] and t[i] are fixed, so it's either match, ab, or ba. So i != j.
Thus we can always handle odd leftover pair this way.
Edge case: If after pairing we have exactly one leftover of each? Yes, when x and y both odd. The formula gives 2 extra ops.
Now we also need to output operations in order. Since we may need to track the strings if we are simulating? Actually we don't need to simulate; we can just output the indices as per the plan; but we must ensure that the plan is correct based on original strings and the operations are applied sequentially. However, if we output a sequence of operations, they will be applied in order. Our reasoning assumed the state after previous operations. So we must ensure that the operations we output indeed transform the strings to equal when applied sequentially to the original strings. Since we derived a sequence that works, it's fine. But we must be careful when we pair mismatches: if we perform swaps among multiple pairs, the order may matter if we are using indices that might be affected by previous swaps. However, the pairing operations are independent if we choose disjoint indices? In our plan, each operation uses two indices from the mismatched sets. If we pair up ab positions: we pair two indices i and j. This operation affects s[i] and t[j]. After this operation, both i and j become matches. Since we don't use i or j again in other operations (if we ensure each index appears in at most one operation), the operations are independent. So it's safe to output them in any order. Similarly for ba positions. For the leftover pair, we use i (ab) and j (ba). Our sequence: first (i, i) affects s[i] and t[i]; second (i, j) affects s[i] and t[j]. After the first operation, i becomes ba (mismatch). The second operation then uses s[i] and t[j]. This is fine. But note: If we also had other operations earlier (like pairing other mismatches), those indices are not used again. So overall sequence: we can do all pairing operations first (ab with ab, ba with ba) and then handle the leftover odd pair with two operations. But careful: after we pair ab's and ba's, the leftover mismatches are exactly one ab and one ba. However, if we perform the pairing operations first, we must ensure that the indices used in leftover are not used in those pairings. So we need to partition the mismatches: we take the ab list, pair them up; if x is even, all are paired; if odd, one remains. Similarly for ba. So for odd leftover, we have one ab index i and one ba index j that are not used in pairings. Then we apply the two operations.
But is there any interaction? The pairing operations use indices within the same type; they are disjoint from the leftover indices. So fine.
Now, we also need to output minimum number of operations. So algorithm:
- Read n, s, t.
- Compute ab_positions = [], ba_positions = [].
For i from 1 to n:
if s[i] == 'a' and t[i] == 'b': ab_positions.append(i)
elif s[i] == 'b' and t[i] == 'a': ba_positions.append(i)
- Let x = len(ab_positions), y = len(ba_positions).
- If (x + y) % 2 != 0: print -1 and exit. (Equivalent to total a count even condition.)
Because if x+y odd, impossible.
Note: Actually we also need to check that (count_a(s) + count_a(t)) % 2 == 0; but x+y odd means impossible as shown; but we could also check that condition directly; either works.
- Compute operations list.
Initialize ops = [].
Pair ab positions: while len(ab_positions) >= 2:
i = ab_positions.pop()
j = ab_positions.pop()
ops.append( (i, j) ) # swap s[i] with t[j]
Pair ba positions similarly: while len(ba_positions) >= 2:
i = ba_positions.pop()
j = ba_positions.pop()
ops.append( (i, j) )
Now after these loops, ab_positions and ba_positions each have either 0 or 1 element.
If both have 1:
i = ab_positions[0]
j = ba_positions[0]
ops.append( (i, i) ) # first op
ops.append( (i, j) ) # second op
Else: both 0, done.
- Print len(ops) and each operation on separate lines: pos1 pos2.
But is this always optimal? Yes, because each operation can fix at most 2 mismatches, and the described strategy achieves that bound for each group.
Now, we must confirm that the operation (i, j) when pairing ab's indeed resolves both mismatches. But careful: In our plan, we output (i, j) meaning swap s[i] with t[j]. However, note that in the description of pairing ab's, we assumed we swap s[i] with t[j] where both i and j are ab positions. But what about the order of popping? For example, we pop two indices i and j. We output (i, j). However, could it be that i and j are the same? No, because we pop two distinct indices. So it's fine.
But we need to verify that after performing these swaps in sequence, the strings become equal. However, if we perform all pairing swaps first, they are independent and each resolves its two positions. However, we must be careful that a pairing swap might affect the status of other positions that are not directly involved. Since it only swaps s[i] with t[j], the only positions that change are s[i] and t[j]. So it could affect the match status at positions i and j. But we have already removed these indices from further consideration. So it's fine. For the leftover case, we do two operations: (i,i) and (i,j). Let's verify that after doing the pairing operations first, we have leftover i (ab) and j (ba). Then we apply (i,i). That changes s[i] and t[i]. After that, i might become ba mismatch? Actually before first leftover op, we have i: s[i]='a', t[i]='b' (ab). j: s[j]='b', t[j]='a' (ba). Also note that earlier pairing operations have not involved i or j, so they remain as originally. Now operation (i,i): swap s[i] and t[i] -> after swap: s[i] = 'b', t[i] = 'a'. So now at i, we have s[i]='b', t[i]='a' (ba). At j unchanged: ba. So both are ba. Then operation (i,j): swap s[i] and t[j]. s[i] is 'b', t[j] is 'a'. After swap: s[i] = 'a', t[j] = 'b'. Now check: i: s[i]='a', t[i]='a' (since t[i] stayed 'a' after first op) -> match; j: s[j]='b', t[j]='b' -> match. So success.
But wait: after first operation (i,i), t[i] becomes 'a' (original s[i]='a'), s[i] becomes 'b' (original t[i]='b'). So t[i] = 'a', s[i] = 'b'. So i becomes ba. Then second operation swaps s[i] (b) with t[j] (a). That yields s[i]=a, t[j]=b. Then t[i] remains a, s[j] remains b. All good.
Thus the sequence works.
Now, about the minimality: Each operation can change at most 2 mismatches? Let's argue lower bound. Initially we have m = x + y mismatches. Each operation can change the status of at most two indices? It can affect the match status at pos1 in s and at pos2 in t. It can potentially fix up to two mismatches, but it could also create mismatches. However, any operation can reduce the total number of mismatches by at most 2. Initially mismatches m. After each operation, mismatches can reduce by at most 2. So at least ceil(m/2) operations? Actually we need to get to 0 mismatches. Since we can reduce by at most 2 per operation, we need at least ceil(m/2) operations. But our solution uses (x+y)/2 + (x%2) operations. Let's compare: m = x+y. If m even, ceil(m/2) = m/2. Our solution uses m/2 operations. Good. If m odd? Actually m odd cannot happen because x+y must be even for possibility; but if m odd, it's impossible. So for possible cases, m is even. However, our solution uses m/2 + 1 operations when both x and y odd? Wait m = x+y, if x and y both odd, then m is even (odd+odd = even). For example x=1,y=1 => m=2. Ceil(m/2)=1, but our solution uses 2 operations. So there is a discrepancy: The lower bound based on mismatches reduction might not be tight because maybe no operation can reduce mismatches by 2 when the mismatches are of opposite types. Indeed, if we have one ab and one ba (m=2), can we reduce mismatches by 2 in one operation? As we argued, no single operation can fix both; the maximum reduction is 1? Let's test: Starting with ab at i, ba at j. Can we reduce mismatches by 2 in one operation? If we try any swap:
- Swap s[i] with t[j]: both a and a? s[i]=a, t[j]=a => no change, mismatches remain 2.
- Swap s[j] with t[i]: s[j]=b, t[i]=b => no change.
- Swap s[i] with t[i]: that changes both at i: after swap, i becomes ba, j remains ba => mismatches still 2 (both ba) — number unchanged.
- Swap s[j] with t[j]: i remains ab, j becomes ab => still 2.
- Swap s[i] with t[k] where k is a matching position: that may fix i but create mismatch at k. So net mismatches could be 2 still or increase? So maximum reduction maybe 0? Actually after swapping with a matched position, we could reduce by 1 if we pick a match of same type? Let's think: We want to reduce total mismatches. Starting with 2 mismatches, can we get to 1 or 0? Possibly: swap s[i] (a) with t[k] where k is a match with both a? Then s[i] becomes a (unchanged), t[k] becomes a (unchanged) -> no change. Swap with match where both b: s[i]=a, t[k]=b => after swap s[i]=b (now matches t[i]=b, fixed), t[k]=a (but s[k]=b originally, so now mismatch ba). So we replaced one mismatch with another: still 2. So no reduction. Similarly swapping with other types yields at most 0 reduction. So indeed with one ab and one ba, we need at least 2 operations. So lower bound is not simply ceil(m/2); we need a more refined bound. Our solution matches the lower bound for this case (2 ops). For m=2, the minimal number is 2.
Thus our solution is optimal.
Now we need to implement. n up to 2e5, so we can collect positions and output operations.
One nuance: Could there be a scenario where using operations that involve indices from both types in a different order might reduce operations further? Suppose we have many mismatches and we could combine cross-type resolutions in some clever way to achieve less than floor(x/2)+floor(y/2)+2? But we argued that any operation can at most reduce the number of mismatches by 2, and only if it swaps two mismatched positions of the same type (ab-ab or ba-ba). But could an operation reduce mismatches by 2 while involving one ab and one ba? We saw it doesn't. Could an operation reduce mismatches by 2 while involving one mismatched and one matched? Possibly could fix the mismatched but create a mismatch of opposite type, net 0. So indeed only same-type mismatches can be fixed in pairs. So the minimal number is indeed: we can pair as many same-type mismatches as possible; each pair uses 1 op for 2 mismatches; leftover one of each type must be resolved in 2 ops. So it's optimal.
Thus algorithm stands.
Now we just implement.
Edge Cases:
- n=0? Not possible, n>=1.
- Strings equal from start: x=y=0 => 0 ops, print 0? Should we output 0 and then nothing? Problem says "In the first line print k — the minimum number of operations required to make the strings equal." If k=0, we just print 0, and no further lines. That's acceptable.
- Inputs with only mismatches of one type but with even count, e.g., x=2,y=0. That is possible only if A_s + A_t even? Let's verify: x=2,y=0 => A_s = M_aa + 2, A_t = M_aa + 0 => sum = 2 M_aa + 2 even, ok. So strings like s="aa", t="bb"? Actually s="aa", t="bb": then at each position ab? i1: a vs b => ab; i2: a vs b => ab. So x=2, y=0. Our algorithm pairs the two ab's: operation (i1, i2) solves both. Let's test: s[1]='a', s[2]='a'; t[1]='b', t[2]='b'. Swap s[1] with t[2]: after: s[1] = 'b', t[2] = 'a'. Now s[1]='b', t[1]='b' match; s[2]='a', t[2]='a' match. Works. So good.
- What about x=0,y=2 similarly.
- What about x=2,y=2: we will pair two ab and two ba, total 2 ops? Actually x//2=1, y//2=1 => 2 ops. Check example: maybe? Works.
- For large n, we need to store positions.
Implementation details:
- We'll read n, s, t.
- We'll iterate i from 0 to n-1 (0-indexed) but output indices should be 1-indexed. So we'll store i+1 in lists.
- Use two lists: ab = [], ba = [].
- For each i: if s[i]=='a' and t[i]=='b': ab.append(i+1); elif s[i]=='b' and t[i]=='a': ba.append(i+1).
- Then check: if (len(ab) + len(ba)) % 2 != 0: print -1; return.
- Then ops = [].
- While len(ab) >= 2: i1 = ab.pop(); i2 = ab.pop(); ops.append((i1, i2)).
- While len(ba) >= 2: i1 = ba.pop(); i2 = ba.pop(); ops.append((i1, i2)).
- If len(ab) == 1 (and len(ba)==1): i=ab[0]; j=ba[0]; ops.append((i, i)); ops.append((i, j)).
- Print len(ops). For each op, print op[0] op[1].
But careful: In the pairing for ab, we use (i, j) meaning swap s[i] with t[j]. However, note that the positions i and j are both from ab list. That is correct. But could there be any issue if we use pop to get indices? The order of operations may matter if we later use the same index in the leftover operations. But we separate: we pair all but possibly one from each list; we don't reuse indices. So it's fine.
But we must consider: In the pairing operation for ab, we are swapping s[i] with t[j]. But is it necessary that both i and j are ab positions? Yes, because they are from the ab list, meaning at those indices originally s='a', t='b'. However, after we perform some operations earlier, the state at those indices might change due to previous swaps. But if we schedule all operations in the order we output, we need to ensure that when we perform a swap (i, j) for ab pairing, at that moment, s[i] and t[j] are indeed what we expect (i.e., s[i] is 'a' and t[j] is 'b')? Actually the state may have been altered by previous operations that involve i or j. But we guarantee that each index appears in at most one operation (except the leftover case where i appears twice). For the pairing operations, we use each index exactly once. So before the operation, no previous operation involved i or j. Therefore, the strings at those indices are as in the original input? But careful: Could there be an operation that affects s[i] or t[j] indirectly? Only swaps involving i in s or j in t would affect them. Since we haven't used i or j before, they remain original. So yes, s[i] and t[j] are original. So the operation works as intended.
But what about the ordering of pairing operations among themselves? They are independent, so any order works.
Now for leftover: we use i from ab and j from ba. These indices have not been used in previous operations because we only paired within ab and ba and left one from each. So they are untouched. So the first operation (i,i) swaps s[i] and t[i]; after that s[i] becomes original t[i] (='b') and t[i] becomes original s[i] (='a'). The second operation (i,j) swaps s[i] (now 'b') with t[j] (original 'a'?). But is t[j] original? j hasn't been used before. t[j] original is 'a'? Actually j is from ba list, so original t[j]='a'? Wait ba: s[j]='b', t[j]='a'. So t[j] original is 'a'. Yes. So after (i,i), s[i]='b', t[i]='a'. Then (i,j) swaps s[i] ('b') with t[j] ('a'). After that, s[i] becomes 'a', t[j] becomes 'b'. So final matches. So it works.
But note: The second operation uses t[j] which is still original because we haven't touched j. Good.
Thus the plan is correct.
Now we need to ensure minimality: For the leftover case, we use two ops; could we do it in one op using a different approach? As argued, no. So it's optimal.
Now we must verify that condition (len(ab)+len(ba))%2==0 is necessary and sufficient. But we should also check a potential hidden impossibility: what if there are zero mismatches? Then it's fine.
Also, what if n=1 and s[0]=a, t[0]=a? then x=y=0, ops=0. Print 0. That's acceptable.
Now confirm with example 1: n=4, ab=[3? Wait indices: s="abab" (1-index: 1:a,2:b,3:a,4:b), t="aabb" (1:a,2:a,3:b,4:b). Mismatches: i=2: s=b,t=a -> ba -> ba list=[2]; i=3: s=a,t=b -> ab list=[3]. So ab=[3], ba=[2]. Both odd. So after pairing (none), leftover i=3, j=2. ops: (3,3) then (3,2). That matches sample output: they had operations: 3 3 and 3 2. Yes, they used (3,3) and (3,2). Good.
Example 3: n=8, ab=[2,6]? Actually we computed earlier: ab indices: 2 (a vs b), 6 (a vs b) -> ab=[2,6]; ba indices: [1,3,7,8]? Actually from earlier: 1,3,7,8. So ba=[1,3,7,8]. Pair ab: pop 6 and 2 -> operation (6,2) maybe? But sample output shows operations: 2 6, 1 3, 7 8. So they paired ab: (2,6) indeed. They paired ba: they paired (1,3) and (7,8). So they used (1,3) and (7,8). That's fine.
Thus our algorithm matches sample.
Now, potential pitfalls: The order of operations in the list might affect correctness if we later use an index that has been modified in a previous operation that was not intended. But we have ensured that each index appears at most once in pairing ops, and leftover uses i twice, but it's okay.
One more check: In pairing for ba, we use operation (i, j) where i and j are ba indices. However, we must verify that swapping s[i] (b) with t[j] (a) indeed resolves both, given original states. Since we haven't used these indices before, s[i] is originally 'b', t[j] originally 'a', good.
So algorithm seems straightforward.
But what about the case where we have many mismatches but only one type (x>0, y=0) and x even? Then we can pair all ab mismatches. But is that always valid? Let's test with an example: s="aa", t="bb". x=2,y=0. Pair: swap s[1] with t[2]? That we did. Works. But what about s="ab", t="ba"? s[1]=a vs t[1]=b -> ab; s[2]=b vs t[2]=a -> ba. So x=1,y=1, odd both. That is the leftover case.
Now, is there any scenario where we need to consider using matches to reduce number of operations? For example, if x=2,y=0, we used 1 operation; could we have done 0? No. Could we have done differently? No.
Thus the algorithm is correct.
Now we need to implement carefully. Complexity O(n). Output up to about n/2 + 1 operations? In worst case, mismatches could be n (if all positions mismatched) and if half are ab and half ba? Actually maximum mismatches is n. For each pair we use 1 operation, so at most n/2 ops from pairing plus possibly 2 extra. So total ops <= n/2 + 2. With n=2e5, output size up to 100001? That's fine.
Now, we must be careful about indexing: if we store positions as 1-indexed, output accordingly.
Implementation steps:
def solve():
import sys
input = sys.stdin.readline
n = int(input().strip())
s = input().strip()
t = input().strip()
ab = []
ba = []
for i, (sc, tc) in enumerate(zip(s, t), start=1):
if sc == 'a' and tc == 'b':
ab.append(i)
elif sc == 'b' and tc == 'a':
ba.append(i)
if (len(ab) + len(ba)) % 2 == 1:
print(-1)
return
ops = []
# pair ab
while len(ab) >= 2:
i = ab.pop()
j = ab.pop()
ops.append(f"{i} {j}")
# pair ba
while len(ba) >= 2:
i = ba.pop()
j = ba.pop()
ops.append(f"{i} {j}")
# now handle leftover
if len(ab) == 1: # then ba also 1
i = ab