using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Linq;

using E = System.Linq.Enumerable;

internal partial class Solver {
    public void Run() {
        int t = ni();
        while (t-- > 0) {
            var n = ni();
            var a = ns();
            var b = ns();
            bool fliped = false;
            var ans = new List<int>();
            for (int i = n - 1; i >= 0; i--) {
                if ((a[i] != b[i]) ^ fliped) { // idff
                    ans.Add(i + 1);
                    fliped ^= true;
                }
            }
            cout.WriteLine(new[] { ans.Count }.Concat(ans).JoinToString(" "));
        }
    }
}

// PREWRITEN CODE BEGINS FROM HERE

static public class StringExtensions {
    static public string JoinToString<T>(this IEnumerable<T> source, string separator = " ") {
        return string.Join(separator, source);
    }
}

internal partial class Solver : Scanner {
    public static void Main() {
#if LOCAL
        byte[] inputBuffer = new byte[1000000];
        var inputStream = Console.OpenStandardInput(inputBuffer.Length);
        using (var reader = new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length)) {
            Console.SetIn(reader);
            new Solver(Console.In, Console.Out).Run();
        }
#else
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        new Solver(Console.In, Console.Out).Run();
        Console.Out.Flush();
#endif
    }

#pragma warning disable IDE0052
    private readonly TextReader cin;
    private readonly TextWriter cout;
    private readonly TextWriter cerr;
#pragma warning restore IDE0052

    public Solver(TextReader reader, TextWriter writer)
        : base(reader) {
        cin = reader;
        cout = writer;
        cerr = Console.Error;
    }

    public Solver(string input, TextWriter writer)
        : this(new StringReader(input), writer) {
    }

#pragma warning disable IDE1006
#pragma warning disable IDE0051
    private int ni() { return NextInt(); }
    private int[] ni(int n) { return NextIntArray(n); }
    private long nl() { return NextLong(); }
    private long[] nl(int n) { return NextLongArray(n); }
    private double nd() { return NextDouble(); }
    private double[] nd(int n) { return NextDoubleArray(n); }
    private string ns() { return Next(); }
    private string[] ns(int n) { return NextArray(n); }
#pragma warning restore IDE1006
#pragma warning restore IDE0051
}

#if DEBUG
internal static class LinqPadExtension {
    public static string TextDump<T>(this T obj) {
        if (obj is IEnumerable) return (obj as IEnumerable).Cast<object>().JoinToString().Dump();
        else return obj.ToString().Dump();
    }
    public static T Dump<T>(this T obj) {
        return LINQPad.Extensions.Dump(obj);
    }
}
#endif

public class Scanner {
    private readonly TextReader Reader;
    private readonly CultureInfo ci = CultureInfo.InvariantCulture;

    private readonly char[] buffer = new char[2 * 1024];
    private int cursor = 0, length = 0;
    private string Token;
    private readonly StringBuilder sb = new StringBuilder(1024);

    public Scanner()
        : this(Console.In) {
    }

    public Scanner(TextReader reader) {
        Reader = reader;
    }

    public int NextInt() { return checked((int)NextLong()); }
    public long NextLong() {
        var s = Next();
        long r = 0;
        int i = 0;
        bool negative = false;
        if (s[i] == '-') {
            negative = true;
            i++;
        }
        for (; i < s.Length; i++) {
            r = r * 10 + (s[i] - '0');
#if DEBUG
            if (!char.IsDigit(s[i])) throw new FormatException();
#endif
        }
        return negative ? -r : r;
    }
    public double NextDouble() { return double.Parse(Next(), ci); }
    public string[] NextArray(int size) {
        string[] array = new string[size];
        for (int i = 0; i < size; i++) {
            array[i] = Next();
        }

        return array;
    }
    public int[] NextIntArray(int size) {
        int[] array = new int[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextInt();
        }

        return array;
    }

    public long[] NextLongArray(int size) {
        long[] array = new long[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextLong();
        }

        return array;
    }

    public double[] NextDoubleArray(int size) {
        double[] array = new double[size];
        for (int i = 0; i < size; i++) {
            array[i] = NextDouble();
        }

        return array;
    }

    public string Next() {
        if (Token == null) {
            if (!StockToken()) {
                throw new Exception();
            }
        }
        var token = Token;
        Token = null;
        return token;
    }

    public bool HasNext() {
        if (Token != null) {
            return true;
        }

        return StockToken();
    }

    private bool StockToken() {
        while (true) {
            sb.Clear();
            while (true) {
                if (cursor >= length) {
                    cursor = 0;
                    if ((length = Reader.Read(buffer, 0, buffer.Length)) <= 0) {
                        break;
                    }
                }
                var c = buffer[cursor++];
                if (33 <= c && c <= 126) {
                    sb.Append(c);
                } else {
                    if (sb.Length > 0) break;
                }
            }

            if (sb.Length > 0) {
                Token = sb.ToString();
                return true;
            }

            return false;
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;

namespace Program
{
    public static class ProblemA
    {
        static bool SAIKI = false;
        static public int numberOfRandomCases = 0;
        static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
        {
        }
        static public void Solve()
        {
            var t = NN;
            for (var i = 0; i < t; i++)
            {
                var n = NN;
                var a = NS.Select(e => e == '1').ToArray(); ;
                var b = NS.Select(e => e == '1').ToArray();
                var ary = a.ToArray();
                var idx = (int)n - 1;
                var ans = new List<long>();
                while (idx >= 0)
                {
                    if (a[0] == b[idx])
                    {
                        ans.Add(1);
                        a[0] = !a[0];
                    }
                    else
                    {
                        ans.Add(idx + 1);
                        var newArray = new List<bool>();
                        for (var j = idx; j >= 0; j--)
                        {
                            newArray.Add(!a[j]);
                        }
                        for (var j = idx + 1; j < n; j++)
                        {
                            newArray.Add(a[j]);
                        }
                        a = newArray.ToArray();
                        --idx;
                    }
                }
                Console.WriteLine(ans.Join(" "));
            }
        }
        class Printer : StreamWriter
        {
            public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
            public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
            public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
        }
        static LIB_FastIO fastio = new LIB_FastIODebug();
        static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); }
        static long NN => fastio.Long();
        static double ND => fastio.Double();
        static string NS => fastio.Scan();
        static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
        static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
        static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
        static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
        static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
        static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
        static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector);
        static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase);
        static string Join<T>(this IEnumerable<T> x, string separator = "") => string.Join(separator, x);
        static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
        static IEnumerator<uint> _xsi = _xsc();
        static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
    }
}
namespace Library {
    class LIB_FastIO
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_FastIO() { str = Console.OpenStandardInput(); }
        readonly Stream str;
        readonly byte[] buf = new byte[1024];
        int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get { return isEof; }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        byte read()
        {
            if (isEof) throw new EndOfStreamException();
            if (ptr >= len)
            {
                ptr = 0;
                if ((len = str.Read(buf, 0, 1024)) <= 0)
                {
                    isEof = true;
                    return 0;
                }
            }
            return buf[ptr++];
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        char Char()
        {
            byte b = 0;
            do b = read();
            while (b < 33 || 126 < b);
            return (char)b;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        virtual public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        virtual public long Long()
        {
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
    }
    class LIB_FastIODebug : LIB_FastIO
    {
        Queue<string> param = new Queue<string>();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_FastIODebug() { }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override string Scan() => NextString();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override long Long() => long.Parse(NextString());
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override double Double() => double.Parse(NextString());
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;

namespace Program
{
    public static class ProblemA
    {
        static bool SAIKI = false;
        static public int numberOfRandomCases = 0;
        static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
        {
        }
        static public void Solve()
        {
            var t = NN;
            for (var i = 0; i < t; i++)
            {
                var n = NN;
                var a = NS.Select(e => e == '1').ToArray(); ;
                var b = NS.Select(e => e == '1').ToArray();
                var ary = a.ToArray();
                var idx = (int)n - 1;
                var ans = new List<long>();
                while (idx >= 0)
                {
                    if (a[0] == b[idx])
                    {
                        ans.Add(1);
                        a[0] = !a[0];
                    }
                    else
                    {
                        ans.Add(idx + 1);
                        var newArray = new List<bool>();
                        for (var j = idx; j >= 0; j--)
                        {
                            newArray.Add(!a[j]);
                        }
                        for (var j = idx + 1; j < n; j++)
                        {
                            newArray.Add(a[j]);
                        }
                        --idx;
                    }
                }
                Console.WriteLine(ans.Join(" "));
            }
        }
        class Printer : StreamWriter
        {
            public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
            public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
            public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
        }
        static LIB_FastIO fastio = new LIB_FastIODebug();
        static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); }
        static long NN => fastio.Long();
        static double ND => fastio.Double();
        static string NS => fastio.Scan();
        static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
        static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
        static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
        static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
        static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
        static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
        static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector);
        static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase);
        static string Join<T>(this IEnumerable<T> x, string separator = "") => string.Join(separator, x);
        static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
        static IEnumerator<uint> _xsi = _xsc();
        static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
    }
}
namespace Library {
    class LIB_FastIO
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_FastIO() { str = Console.OpenStandardInput(); }
        readonly Stream str;
        readonly byte[] buf = new byte[1024];
        int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get { return isEof; }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        byte read()
        {
            if (isEof) throw new EndOfStreamException();
            if (ptr >= len)
            {
                ptr = 0;
                if ((len = str.Read(buf, 0, 1024)) <= 0)
                {
                    isEof = true;
                    return 0;
                }
            }
            return buf[ptr++];
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        char Char()
        {
            byte b = 0;
            do b = read();
            while (b < 33 || 126 < b);
            return (char)b;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        virtual public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        virtual public long Long()
        {
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
    }
    class LIB_FastIODebug : LIB_FastIO
    {
        Queue<string> param = new Queue<string>();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_FastIODebug() { }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override string Scan() => NextString();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override long Long() => long.Parse(NextString());
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override double Double() => double.Parse(NextString());
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;

namespace Program
{
    public static class ProblemA
    {
        static bool SAIKI = false;
        static public int numberOfRandomCases = 0;
        static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
        {
        }
        static public void Solve()
        {
            var t = NN;
            for (var i = 0; i < t; i++)
            {
                var n = NN;
                var a = NS.Select(e => e == '1').ToArray();
                var b = NS.Select(e => e == '1').ToArray();
                var ary = a.ToArray();
                var idx = (int)n - 1;
                var ans = new List<long>();
                while (idx >= 0)
                {
                    if (a[0] == b[idx])
                    {
                        ans.Add(1);
                        a[0] = !a[0];
                    }
                    else
                    {
                        ans.Add(idx + 1);
                        var newArray = new List<bool>();
                        for (var j = idx; j >= 0; j--)
                        {
                            newArray.Add(!a[j]);
                        }
                        for (var j = idx + 1; j < n; j++)
                        {
                            newArray.Add(a[j]);
                        }
                        a = newArray.ToArray();
                        --idx;
                    }
                }
                Console.WriteLine(ans.Count + " " + ans.Join(" "));
            }
        }
        class Printer : StreamWriter
        {
            public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
            public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
            public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
        }
        static LIB_FastIO fastio = new LIB_FastIODebug();
        static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); }
        static long NN => fastio.Long();
        static double ND => fastio.Double();
        static string NS => fastio.Scan();
        static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
        static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
        static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
        static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
        static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
        static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
        static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector);
        static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase);
        static string Join<T>(this IEnumerable<T> x, string separator = "") => string.Join(separator, x);
        static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
        static IEnumerator<uint> _xsi = _xsc();
        static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
    }
}
namespace Library {
    class LIB_FastIO
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_FastIO() { str = Console.OpenStandardInput(); }
        readonly Stream str;
        readonly byte[] buf = new byte[1024];
        int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get { return isEof; }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        byte read()
        {
            if (isEof) throw new EndOfStreamException();
            if (ptr >= len)
            {
                ptr = 0;
                if ((len = str.Read(buf, 0, 1024)) <= 0)
                {
                    isEof = true;
                    return 0;
                }
            }
            return buf[ptr++];
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        char Char()
        {
            byte b = 0;
            do b = read();
            while (b < 33 || 126 < b);
            return (char)b;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        virtual public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        virtual public long Long()
        {
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
    }
    class LIB_FastIODebug : LIB_FastIO
    {
        Queue<string> param = new Queue<string>();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_FastIODebug() { }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override string Scan() => NextString();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override long Long() => long.Parse(NextString());
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override double Double() => double.Parse(NextString());
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using CodeforcesRound658Div1.Extensions;
using CodeforcesRound658Div1.Questions;

namespace CodeforcesRound658Div1.Questions
{
    public class QuestionA : AtCoderQuestionBase
    {
        public override IEnumerable<object> Solve(TextReader inputStream)
        {
            var tests = inputStream.ReadInt();
            for (int t = 0; t < tests; t++)
            {
                var n = inputStream.ReadInt();
                var a = inputStream.ReadLine().Select(ai => ai == '1').ToArray();
                var b = inputStream.ReadLine().Select(bi => bi == '1').ToArray();
                var operations = new Queue<int>();

                for (int i = a.Length - 1; i >= 0; i--)
                {
                    if (a[0] == b[i])
                    {
                        operations.Enqueue(0);
                        Invert(a, 1);
                    }

                    operations.Enqueue(i);
                    Invert(a, i + 1);
                }

                yield return $"{operations.Count} {operations.Select(i => i + 1).Join(" ")}";
            }
        }

        void Invert(bool[] array, int exclusiveLast)
        {
            for (int i = 0; i < exclusiveLast; i++)
            {
                array[i] ^= true;
            }

            var temp = new bool[exclusiveLast];
            for (int i = 0; i < temp.Length; i++)
            {
                temp[i] = array[exclusiveLast - i - 1];
            }

            for (int i = 0; i < temp.Length; i++)
            {
                array[i] = temp[i];
            }
        }
    }
}

namespace CodeforcesRound658Div1
{
    class Program
    {
        static void Main(string[] args)
        {
            IAtCoderQuestion question = new QuestionA();
            var answers = question.Solve(Console.In);

            var writer = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
            Console.SetOut(writer);
            foreach (var answer in answers)
            {
                Console.WriteLine(answer);
            }
            Console.Out.Flush();
        }
    }
}

#region Base Class

namespace CodeforcesRound658Div1.Questions
{

    public interface IAtCoderQuestion
    {
        IEnumerable<object> Solve(string input);
        IEnumerable<object> Solve(TextReader inputStream);
    }

    public abstract class AtCoderQuestionBase : IAtCoderQuestion
    {
        public IEnumerable<object> Solve(string input)
        {
            var stream = new MemoryStream(Encoding.Unicode.GetBytes(input));
            var reader = new StreamReader(stream, Encoding.Unicode);

            return Solve(reader);
        }

        public abstract IEnumerable<object> Solve(TextReader inputStream);
    }
}

#endregion

#region Extensions

namespace CodeforcesRound658Div1.Extensions
{
    public static class StringExtensions
    {
        public static string Join<T>(this IEnumerable<T> source) => string.Concat(source);
        public static string Join<T>(this IEnumerable<T> source, string separator) => string.Join(separator, source);
    }

    public static class TextReaderExtensions
    {
        public static int ReadInt(this TextReader reader) => int.Parse(ReadString(reader));
        public static long ReadLong(this TextReader reader) => long.Parse(ReadString(reader));
        public static double ReadDouble(this TextReader reader) => double.Parse(ReadString(reader));
        public static string ReadString(this TextReader reader) => reader.ReadLine();

        public static int[] ReadIntArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(int.Parse).ToArray();
        public static long[] ReadLongArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(long.Parse).ToArray();
        public static double[] ReadDoubleArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(double.Parse).ToArray();
        public static string[] ReadStringArray(this TextReader reader, char separator = ' ') => reader.ReadLine().Split(separator);

        // Supports primitive type only.
        public static T1 ReadValue<T1>(this TextReader reader) => (T1)Convert.ChangeType(reader.ReadLine(), typeof(T1));

        public static (T1, T2) ReadValue<T1, T2>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            return (v1, v2);
        }

        public static (T1, T2, T3) ReadValue<T1, T2, T3>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            return (v1, v2, v3);
        }

        public static (T1, T2, T3, T4) ReadValue<T1, T2, T3, T4>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            return (v1, v2, v3, v4);
        }

        public static (T1, T2, T3, T4, T5) ReadValue<T1, T2, T3, T4, T5>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
            return (v1, v2, v3, v4, v5);
        }

        public static (T1, T2, T3, T4, T5, T6) ReadValue<T1, T2, T3, T4, T5, T6>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
            var v6 = (T6)Convert.ChangeType(inputs[5], typeof(T6));
            return (v1, v2, v3, v4, v5, v6);
        }

        public static (T1, T2, T3, T4, T5, T6, T7) ReadValue<T1, T2, T3, T4, T5, T6, T7>(this TextReader reader, char separator = ' ')
        {
            var inputs = ReadStringArray(reader, separator);
            var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
            var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
            var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
            var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
            var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
            var v6 = (T6)Convert.ChangeType(inputs[5], typeof(T6));
            var v7 = (T7)Convert.ChangeType(inputs[6], typeof(T7));
            return (v1, v2, v3, v4, v5, v6, v7);
        }
    }
}

#endregion


/* This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. */

#[derive(Default)]
struct Scanner {
    buffer: Vec<String>,
}

impl Scanner {
    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            std::io::stdin().read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn main() {
    let mut scanner = Scanner::default();
    for _ in 0..scanner.next() {
        let n = scanner.next::<usize>();
        let a = scanner
            .next::<String>()
            .chars()
            .map(|c| c == '1')
            .collect::<Vec<_>>();
        let b = scanner
            .next::<String>()
            .chars()
            .map(|c| c == '1')
            .collect::<Vec<_>>();

        let mut p = vec![];

        for i in 1..n {
            if a[i - 1] != a[i] {
                p.push(i);
            }
        }
        if a[n - 1] {
            p.push(n);
        }

        if b[n - 1] {
            p.push(n);
        }
        for i in (1..n).rev() {
            if b[i - 1] != b[i] {
                p.push(i);
            }
        }

        println!(
            "{} {}",
            p.len(),
            p.iter()
                .map(|p| p.to_string())
                .collect::<Vec<_>>()
                .join(" ")
        );
    }
}


use std::collections::VecDeque;

fn solve() {
    let n: usize = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.trim_end().parse().unwrap()
    };
    let mut a: VecDeque<char> = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.trim_end().chars().collect()
    };
    let b: Vec<char> = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.trim_end().chars().collect()
    };

    let mut ans = Vec::new();
    let mut flag = false;
    for i in (0..n).rev() {
        if flag {
            if a.front() == Some(&b[i]) {
                if a.back() != Some(&b[i]) {
                    ans.push(1);
                }
                ans.push(i + 1);
                a.pop_back();
                flag = !flag;
            } else {
                a.pop_front();
            }
        } else {
            if a.back() != Some(&b[i]) {
                if a.front() == Some(&b[i]) {
                    ans.push(1);
                }
                ans.push(i + 1);
                a.pop_front();
                flag = !flag;
        } else {
                a.pop_back();
            }
        }
    }
    let k = ans.len();
    let ans = ans.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(" ");
    println!("{} {}", k, ans);
}

fn main() {
    let t: usize = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.trim_end().parse().unwrap()
    };
    for _ in 0..t {
        solve();
    }
}


/// Codeforces Round #660 (Div. 2)
/// https://codeforces.com/contest/1388/problem/C

use std::io::{self, BufWriter, Read, Write};

fn main() {
    let stdout = io::stdout();
    let mut output = BufWriter::new(stdout.lock());
    let mut stdin = io::stdin();
    let mut input_str = String::new();
    stdin.read_to_string(&mut input_str).unwrap();

    let mut input_iter = input_str.split_whitespace();

    macro_rules! read(() => (input_iter.next().unwrap().parse().unwrap()));

    let test_cases: usize = read!();

    for _ in 0..test_cases {
        let n: usize = read!();
        let _a: String = read!();
        let _b: String = read!();

        let a: Vec<u32> = _a.chars().map(|x| x.to_digit(10).unwrap()).collect();
        let b: Vec<u32> = _b.chars().map(|x| x.to_digit(10).unwrap()).collect();

        let mut test_case_output = String::new();
        let mut count_ones = 0;

        for i in 0..n {
            let target_idx = n - 1 - i;
            let digit_idx;
            if i % 2 == 0 {
                digit_idx = i / 2;
            } else {
                digit_idx = n - 1 - (i / 2);
            }

            if (i % 2 == 0 && a[digit_idx] == b[target_idx])
            || (i % 2 == 1 && a[digit_idx] != b[target_idx]) {
                test_case_output.push_str("1 ");
                count_ones += 1;
            }
            test_case_output.push_str(&format!("{}", n - i));

            if i != n - 1 {
                test_case_output.push_str(" ");
            }
        }

        writeln!(output, "{} {}", n + count_ones, test_case_output).unwrap();
    }
}


fn main() {
    let t = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        s.trim_end().to_owned().parse::<usize>().unwrap()
    };
    for _ in 0..t {
        let n = {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).unwrap();
            s.trim_end().to_owned().parse::<usize>().unwrap()
        };
        let mut a: Vec<u32> = {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).unwrap();
            s.trim_end()
                .chars()
                .map(|c| match c {
                    '0' => 0,
                    '1' => 1,
                    _ => panic!(),
                })
                .collect()
        };
        let b: Vec<u32> = {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).unwrap();
            s.trim_end()
                .chars()
                .map(|c| match c {
                    '0' => 0,
                    '1' => 1,
                    _ => panic!(),
                })
                .collect()
        };

        let mut ans = vec![];
        for i in (0..n).rev() {
            if a[i] == b[i] {
                continue;
            }
            if a[0] != a[i] {
                ans.push(1);
                a[0] ^= 1;
            }
            ans.push(i + 1);
            a[0..=i].reverse();
            a[0..=i].iter_mut().for_each(|x| *x ^= 1);
        }

        println!(
            "{} {}",
            ans.len(),
            ans.iter()
                .map(|&x| x.to_string())
                .fold(String::new(), |acc, s| if acc.is_empty() {
                    s
                } else {
                    acc + " " + s.as_ref()
                })
        );
    }
}


//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

use std::io::Write;

fn run() {
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    input! {
        t: usize,
        ask: [(usize, bytes, bytes); t],
    }
    for (n, a, b) in ask {
        let mut ans = vec![];
        let mut l = 0;
        let mut r = n;
        let mut pos = 0;
        for (i, &b) in b.iter().enumerate().skip(1).rev() {
            if pos == 0 {
                if a[r - 1] == b {
                    r -= 1;
                } else {
                    if a[l] == b {
                        ans.push(1);
                    }
                    ans.push(i + 1);
                    l += 1;
                    pos ^= 1;
                }
            } else {
                if a[l] != b {
                    l += 1;
                } else {
                    if a[r - 1] != b {
                        ans.push(1);
                    }
                    ans.push(i + 1);
                    r -= 1;
                    pos ^= 1;
                }
            }
        }
        if pos == 0 {
            if a[r - 1] == b[0] {
            } else {
                ans.push(1);
            }
        } else {
            if a[r - 1] != b[0] {
            } else {
                ans.push(1);
            }
        }
        /*
        let mut a = a;
        for &x in ans.iter() {
            for a in a.iter_mut().take(x) {
                *a ^= b'0' ^ b'1';
            }
            a[..x].reverse();
        }
        assert!(a == b);
        */
        let mut s = String::new();
        s.push_str(&format!("{}", ans.len()));
        for a in ans {
            s.push_str(&format!(" {}", a));
        }
        writeln!(out, "{}", s).ok();
    }
}

fn main() {
    run();
}


#![allow(unused_imports, unused_macros)]

use kyoproio::*;
use std::{
    collections::*,
    io::{self, prelude::*},
    iter,
    mem::{replace, swap},
};

fn main() -> io::Result<()> {
    std::thread::Builder::new()
        .stack_size(64 * 1024 * 1024)
        .spawn(|| {
            let stdin = io::stdin();
            let stdout = io::stdout();
            run(KInput::new(stdin.lock()), io::BufWriter::new(stdout.lock()))
        })?
        .join()
        .unwrap();
    Ok(())
}

fn run<I: Input, O: Write>(mut kin: I, mut out: O) {
    macro_rules! output { ($($args:expr),+) => { write!(&mut out, $($args),+).unwrap(); }; }
    macro_rules! outputln {
        ($($args:expr),+) => { output!($($args),+); outputln!(); };
        () => { output!("\n"); if cfg!(debug_assertions) { out.flush().unwrap(); } }
    }

    let t: usize = kin.input();
    'test: for _ in 0..t {
        let n: usize = kin.input();
        let (a, b): (Vec<u8>, Vec<u8>) = kin.input();

        let mut a: VecDeque<u8> = a.into();
        let mut rev = false;
        let mut res = Vec::new();
        for i in (0..n).rev() {
            if !rev {
                if *a.back().unwrap() != b[i] {
                    if i > 0 && *a.front().unwrap() == b[i] {
                        res.push(1);
                    }
                    res.push(i + 1);
                    rev = true;
                }
            } else {
                if *a.front().unwrap() == b[i] {
                    if i > 0 && *a.back().unwrap() != b[i] {
                        res.push(1);
                    }
                    res.push(i + 1);
                    rev = false;
                }
            }
            if !rev {
                a.pop_back();
            } else {
                a.pop_front();
            }
        }

        output!("{}", res.len());
        for p in res {
            output!(" {}", p);
        }
        outputln!();
    }
}

// -----------------------------------------------------------------------------
pub mod kyoproio {
    use std::io::prelude::*;
    pub trait Input {
        fn str(&mut self) -> &str;
        fn input<T: InputParse>(&mut self) -> T {
            T::input(self)
        }
        fn iter<T: InputParse>(&mut self) -> Iter<T, Self> {
            Iter(self, std::marker::PhantomData)
        }
        fn seq<T: InputParse, B: std::iter::FromIterator<T>>(&mut self, n: usize) -> B {
            self.iter().take(n).collect()
        }
    }
    pub struct KInput<R> {
        src: R,
        buf: String,
        pos: usize,
    }
    impl<R: BufRead> KInput<R> {
        pub fn new(src: R) -> Self {
            Self {
                src,
                buf: String::with_capacity(1024),
                pos: 0,
            }
        }
    }
    impl<R: BufRead> Input for KInput<R> {
        fn str(&mut self) -> &str {
            loop {
                if self.pos >= self.buf.len() {
                    self.pos = 0;
                    self.buf.clear();
                    if self.src.read_line(&mut self.buf).expect("io error") == 0 {
                        return &self.buf;
                    }
                }
                let range = self.pos
                    ..self.buf[self.pos..]
                        .find(|c: char| c.is_ascii_whitespace())
                        .map(|i| i + self.pos)
                        .unwrap_or_else(|| self.buf.len());
                self.pos = range.end + 1;
                if range.end > range.start {
                    return &self.buf[range];
                }
            }
        }
    }
    pub struct Iter<'a, T, I: ?Sized>(&'a mut I, std::marker::PhantomData<*const T>);
    impl<'a, T: InputParse, I: Input + ?Sized> Iterator for Iter<'a, T, I> {
        type Item = T;
        fn next(&mut self) -> Option<T> {
            Some(self.0.input())
        }
    }
    pub trait InputParse: Sized {
        fn input<I: Input + ?Sized>(src: &mut I) -> Self;
    }
    impl InputParse for Vec<u8> {
        fn input<I: Input + ?Sized>(src: &mut I) -> Self {
            src.str().as_bytes().to_owned()
        }
    }
    macro_rules! from_str_impl {
        { $($T:ty)* } => {
            $(impl InputParse for $T {
                fn input<I: Input + ?Sized>(src: &mut I) -> Self {
                    src.str().parse::<$T>().expect("parse error")
                }
            })*
        }
    }
    from_str_impl! {
        String char bool f32 f64 isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128
    }
    macro_rules! tuple_impl {
        ($H:ident $($T:ident)*) => {
            impl<$H: InputParse, $($T: InputParse),*> InputParse for ($H, $($T),*) {
                fn input<I: Input + ?Sized>(src: &mut I) -> Self {
                    ($H::input(src), $($T::input(src)),*)
                }
            }
            tuple_impl!($($T)*);
        };
        () => {}
    }
    tuple_impl!(A B C D E F G);
    #[macro_export]
    macro_rules! kdbg {
        ($($v:expr),*) => {
            if cfg!(debug_assertions) { dbg!($($v),*) } else { ($($v),*) }
        }
    }
}


#[derive(Debug)]
pub struct Case(pub u32, pub String, pub String);

mod input {
    use super::Case;
    use std::io;

    fn readl() -> String {
        let mut line = String::new();
        io::stdin()
            .read_line(&mut line)
            .expect("Failed to read line");
        line.trim().to_string()
    }

    fn test_case() -> Case {
        let length: u32 = readl().parse().expect("Error parsing");
        let string_a = readl();
        let string_b = readl();

        Case(length, string_a, string_b)
    }

    pub fn input() -> Vec<Case> {
        let number_of_test_cases = readl().parse().expect("Error parsing");
        let mut input = Vec::new();
        for _ in 0..number_of_test_cases {
            input.push(test_case())
        }
        input
    }
}

mod helper {
    pub fn flip(x: char) -> Result<char, &'static str> {
        match x {
            '0' => Ok('1'),
            '1' => Ok('0'),
            _ => Err("Error, input is not a bit")
        }
    }

    pub fn last_char(x: &str) -> char {
        x.chars().last().unwrap()
    }

    pub fn first_char(x: &str) -> char {
        x.chars().next().unwrap()
    }
}

mod logic {
    use crate::helper::{flip, last_char, first_char};

    pub fn op(binary: &str, length: usize) -> Result<String, &'static str> {
        if length > binary.len() {
            return Err("length is larger than string length")
        }

        let mut result = String::new();
        let prefix: Vec<char> = binary
            .chars()
            .take(length)
            .map(|x| flip(x).expect("Error flipping char"))
            .collect();

        for &i in prefix.iter().rev() {
            result.push(i);
        }

        result.push_str(&binary[length..]);
        Ok(result)
    }

    fn make_last_char_same(src: &str, dest: &str) -> Vec<u32> {
        let last_dest = last_char(dest);
        let len = src.len() as u32;

        if last_char(src) == last_dest {
            return vec![];
        } else if flip(first_char(src)).unwrap() == last_dest {
            return vec![len];
        } else {
            for (i , c) in src.chars().rev().enumerate() {
                if c == last_dest {
                    return vec![len-(i as u32), len];
                }
            }
            unreachable!();
        }
    }

    pub fn make_same(src: &str, dest: &str) -> Vec<u32> {
        let l: usize = src.len();
        let mut temp = String::from(src);
        if src == dest {
            return vec![];
        } else {
            let last: Vec<u32> = make_last_char_same(src, dest);
            for &i in last.iter() {
                temp = op(&temp, i as usize).expect("Error");
            }
            let rest: Vec<u32> = make_same(&temp[..(l-1)], &dest[..(l-1)]);
            [&last[..], &rest[..]].concat()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::logic::{op, make_same};

    #[test]
    fn test_op_1() {
        let t = op("100101", 4).expect("Error");
        assert_eq!(t, "011001", "Source: {}. Length: {}", "1100101", 4);
    }
    #[test]
    fn test_op_2() {
        let t = op("0111100101", 10).expect("Error");
        assert_eq!(t, "0101100001", "Source: {}. Length: {}", "0111100101", 10);
    }
    #[test]
    fn test_op_3() {
        let t = op("10100110110011", 0).expect("Error");
        assert_eq!(t, "10100110110011", "Source: {}. Length: {}", "10100110110011", 0);
    }

    #[test]
    fn test_make_same_1() {
        let src = "0110011011";
        let dest = "1000110100";

        let steps = make_same(src, dest);
        let mut temp = String::from(src);
        for &i in &steps {
            temp = op(&temp, i as usize).expect("Error");
        }
        assert_eq!(&temp, dest, "Source: {}. Dest: {}. Steps: {:?}", src, dest, steps);
    }
    #[test]
    fn test_make_same_2() {
        let src = "10110001001";
        let dest = "10110001000";

        let steps = make_same(src, dest);

        let mut temp = String::from(src);
        for &i in &steps {
            temp = op(&temp, i as usize).expect("Error");
        }
        assert_eq!(&temp, dest, "Source: {}. Dest: {}. Steps: {:?}", src, dest, steps);
    }
}

fn solve(case: Case) -> Vec<u32> {
    let Case(_, src, dest) = case;
    logic::make_same(&src, &dest)
}

fn display(steps: &[u32]) {
    let l = steps.len();
    let mut seq = l.to_string();
    for step in steps {
        seq.push(' ');
        seq.push_str(&step.to_string());
    }
    println!("{}", seq);
}

fn main() {
    let cases = input::input();
    for case in cases {
        display(&solve(case));
    }
}


#![allow(dead_code, unused_macros, unused_imports)]
use std::collections::*;
use std::io;
use std::io::Write;
macro_rules! fprintln {
    ($dst:expr) => (
        $dst.write("\n".as_bytes()).unwrap();
    );
    ($dst:expr, $($arg:tt)*) => ( {
        $dst.write_fmt(format_args!($($arg)*)).unwrap();
        $dst.write("\n".as_bytes()).unwrap();
    }
    );
}

macro_rules! fprintvec {
    ($dst:expr, $arg:expr) => {{
        fprintln!(
            $dst,
            "{}",
            $arg.iter()
                .map(|x| format!("{}", x))
                .collect::<Vec<String>>()
                .join(" ")
        );
    }};
}

macro_rules! parse_input {
    ($t:ident) => {{
        let mut input_line = String::new();
        io::stdin().read_line(&mut input_line).unwrap();
        input_line
            .trim_end_matches("\n")
            .trim_end_matches("\r")
            .parse::<$t>()
            .unwrap()
    }};
}

macro_rules! split_input {
    ($t:ident) => {{
        parse_input!(String)
            .split(" ")
            .map(|z| z.parse::<$t>().unwrap())
            .collect::<Vec<$t>>()
    }};
}

fn inv_pref(v: Vec<usize>, preflen: usize) -> Vec<usize> {
    let mut out = Vec::new();
    for i in 0..preflen {
        out.push(v[preflen - 1 - i] ^ 1);
    }
    for i in preflen..v.len() {
        out.push(v[i]);
    }
    out
}

fn main() {
    let stdout = io::stdout();
    let lock = stdout.lock();
    let mut w = io::BufWriter::new(lock);
    let num_tests = parse_input!(usize);
    // let num_tests = 1;
    for _ in 0..num_tests {
        let limits = split_input!(usize);
        let mut l1 = parse_input!(String)
            .chars()
            .map(|x| if x == '1' { 1 } else { 0 })
            .collect::<Vec<usize>>();
        let l2 = parse_input!(String)
            .chars()
            .map(|x| if x == '1' { 1 } else { 0 })
            .collect::<Vec<usize>>();
        let mut ops = Vec::new();
        for (p, v) in l2.iter().enumerate().rev() {
            if l1[p] == *v {
                continue;
            }
            if l1[0] == *v {
                l1 = inv_pref(l1, 1);
                ops.push(1);
                l1 = inv_pref(l1, p + 1);
                ops.push(p + 1);
            } else {
                l1 = inv_pref(l1, p + 1);
                ops.push(p + 1);
            }
        }
        fprintln!(w, "{}", ops.len());
        fprintvec!(w, ops);
    }
}


use std::io::{self, BufRead};
fn main(){
	let stdin = io::stdin();
	let mut input = stdin.lock();
	let mut line = String::new();
	let mut current = Vec::new();
	let mut needed = Vec::new();
	let mut operations = Vec::new();
	input.read_line(&mut line).unwrap();
	let mut count: i16 = line.trim().parse().unwrap();
	while count > 0{
		input.read_line(&mut line).unwrap();
		line.clear();
		input.read_line(&mut line).unwrap();
		for item in line.trim().chars(){
			current.push(item != '0');
		}
		line.clear();
		input.read_line(&mut line).unwrap();
		for item in line.trim().chars(){
			needed.push(item != '0');
		}
		let mut inversed = false;
		let mut head = 0;
		let mut current_tail = current.len();
		let mut needed_tail = current_tail;
		while needed_tail > 0{
			if inversed{
				current_tail += 1;
			}else{
				current_tail -= 1;
			};
			needed_tail -= 1;
			let needed_item = needed[needed_tail] ^ inversed;
			if current[current_tail] == needed_item{
				continue;
			}
			if current[head] == needed_item{
				operations.push(1);
			}
			operations.push(needed_tail + 1);
			inversed = !inversed;
			head ^= current_tail;
			current_tail ^= head;
			head ^= current_tail;
		}
		current.clear();
		needed.clear();
		print!("{}", operations.len());
		for operation in &operations{
			print!(" {}", operation);
		}
		println!();
		operations.clear();
		count -= 1;
	}
}


package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
)

/*
6
OEYCDK
EYOKCD
KDCEOY
CKHOYE
YOEDKC
DCKYEO
3
IWL
GIW
WLI
*/

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

type priorityQueue [][2]int

func (pq priorityQueue) Len() int {
	return len(pq)
}

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i][1] > pq[j][1]
}

func (pq priorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *priorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.([2]int))
}

func (pq *priorityQueue) Pop() (res interface{}) {
	res = (*pq)[len(*pq)-1]
	*pq = (*pq)[:len(*pq)-1]
	return res
}

var err error

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextDouble() (n float64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func next() (n string) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return ""
		}
	}
}

func Fill(a []int, v int) {
	for i := range a {
		a[i] = v
	}
}

func FillB(a []bool, v bool) {
	for i := range a {
		a[i] = v
	}
}

func Min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

var (
	names map[string]int
	words []string
	withs [][]string
	res   []string
	has   []bool
)

func dfs(ind int) {
	if has[ind] {
		return
	}
	has[ind] = true
	for i := len(withs[ind]) - 1; i >= 0; i-- {
		dfs(names[withs[ind][i]])
	}
	res = append(res, words[ind])
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	if false {
		name := "in"
		file1, err := os.Open(name + ".in")
		if err != nil {
			log.Fatal(err)
		}
		// file2, err := os.Create(name + ".out")
		// if err != nil {
		// 	log.Fatal(err)
		// }
		in = bufio.NewReaderSize(file1, 8192)
		// out = bufio.NewWriterSize(file2, 8192)
	}
	defer out.Flush()

	for cases := nextInt(); cases > 0; cases-- {
		n := nextInt()
		a, b := next(), next()
		ord := make([]int, n)
		for i := 0; i <= (n-1)/2; i++ {
			ord[2*i] = i
		}
		for i, curr := n-1, 1; curr < n; i, curr = i-1, curr+2 {
			ord[curr] = i
		}
		res := []int{}
		for i := 0; i < n; i++ {
			x, v := n-1-i, byte(0)
			if i%2 == 1 {
				v = a[ord[i]] ^ 1
			} else {
				v = a[ord[i]]
			}
			if v == b[x] {
				res = append(res, 1)
			}
			res = append(res, x+1)
		}
		printf("%d", len(res))
		for _, v := range res {
			printf(" %d", v)
		}
		printf("\n")
	}
}


package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.nextInt(); t > 0; t-- {
		n := io.nextInt()
		a, b := []byte(io.next()), []byte(io.next())

		i, j, inv, dir := 0, n-1, byte(0), 1
		ops := []int{}
		for k := n - 1; k >= 0; k-- {
			if a[j]^inv != b[k] {
				if a[i]^inv == b[k] {
					ops = append(ops, 1)
					a[i] ^= 1
				}
				ops = append(ops, k+1)
				i, j = j, i+dir
				dir = -dir
				inv ^= 1
			} else {
				j -= dir
			}
		}
		io.print(len(ops), " ")
		io.printlnInts(ops...)
	}
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	return n
}

func (f *fastIO) nextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.nextInt()
	}
	return a
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *fastIO) printInts(a ...int) {
	if len(a) > 0 {
		f.print(a[0])
		for _, x := range a[1:] {
			f.print(" ", x)
		}
	}
}

func (f *fastIO) printlnInts(a ...int) {
	f.printInts(a...)
	f.println()
}


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1381A2(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T, n int
	var a, b []byte
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &a, &b)
		ans := []interface{}{}
		for i, c := range a {
			if i > 0 && c != a[i-1] {
				ans = append(ans, i)
			}
		}
		if a[n-1] != b[n-1] {
			ans = append(ans, n)
		}
		for i := len(b) - 2; i >= 0; i-- {
			if b[i] != b[i+1] {
				ans = append(ans, i+1)
			}
		}
		Fprint(out, len(ans), " ")
		Fprintln(out, ans...)
	}
}

func main() { CF1381A2(os.Stdin, os.Stdout) }


for _ in range(input()):
    n=input()
    a=raw_input()
    b=raw_input()
    pos=[]
    current='0'
    other='1'
    size=0
    if a[0]=='1':
        pos.append(0)
        current='1'
        other='0'
    for i in range(n):
        if a[i]==current:
            size+=1
        else:
            pos.append(size)
            current,other=other,current
            size=1
    pos.append(size)
    ans=[]
    flag=0
    cc=0
    if len(pos)%2==0:
        flag=1
    for i in range(len(pos)-flag):
        if pos[i]==0:
            continue
        else:
            cc+=pos[i]
            ans.append(cc)
    forb=[]
    sz=0
    for i in range(n-1,-1,-1):
        if b[i]=='0':
            if sz==0:
                star=i+1
            sz+=1
        else:
            if sz!=0:
                if sz==star:
                    ans.append(star)
                else:
                    ans.append(star)
                    ans.append(star-sz)
                sz=0
    if sz!=0:
        ans.append(sz)

    print len(ans),
    for i in ans:
        print i,
    print


import atexit
import io
import sys
import math
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).next
_OUTPUT_BUFFER = io.BytesIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
def dist(a,b):
    return abs(a[0]-b[0])+abs(a[1]-b[1])
def takla():
    for _ in range(int(input())):
      n=int(input())
      a=input()
      b=input()
      reverse = False
      i=0
      k=n-1
      moves=[]
      j=n-1
      while j>=0:

        if not reverse:
          if a[i]==b[j]:
            moves.append(1)
            moves.append(abs(j)+1)
            i+=1
            i,k=k,i
            reverse = True
          else:
            moves.append(abs(j)+1)
            i+=1
            i,k=k,i
            reverse = True
        else:
          if a[i]!=b[j]:
            moves.append(1)
            moves.append(abs(j)+1)
            i-=1
            i,k=k,i
            reverse = False
          else:
            moves.append(abs(j)+1)
            i-=1
            i,k=k,i
            reverse = False
        j-=1
      print len(moves),
      for i in moves:
        print i,
      print

if __name__ == "__main__":
	  takla()


from collections import *
import sys
try: inp = raw_input
except: inp = input
def err(s):
    sys.stderr.write('{}\n'.format(s))

def ni():
    return int(inp())

def nl():
    return [int(_) for _ in inp().split()]

T = ni()

def swap(s):
    return ['0' if c == '1' else '1' for c in s]

def solve(a, b):
    out = []
    for i in range(len(a) - 1, -1, -1):
        if a[i] == b[i]:
            continue
        if a[0] != b[i]:
            out.append(i+1)
            a = swap(a[:i+1][::-1]) + a[i+1:]
        else:
            out.append(1)
            out.append(i+1)
            a[0] = swap(a[0])[0]
            a = swap(a[:i+1][::-1]) + a[i+1:]
    return out

for _ in range(T):
    N = ni()
    a = list(inp())
    b = list(inp())
    out = solve(a, b)
    print(' '.join(map(str, [len(out)] + out)))


import sys
range = xrange
input = raw_input

inp = sys.stdin.read().split(); ii = 0
out = []

t = int(inp[ii]); ii += 1
for _ in range(t):
    n = int(inp[ii]); ii += 1
    A = [ord(c) - ord('0') for c in inp[ii]]; ii += 1
    B = [ord(c) - ord('0') for c in inp[ii]]; ii += 1

    parA = A[0]
    O1 = []
    O2 = []
    for i in range(n):
        if A[i] != parA:
            O1.append(i)
            parA ^= 1
    parB = B[0]
    for i in range(n):
        if B[i] != parB:
            O2.append(i)
            parB ^= 1

    if parA != parB:
        O1.append(n)

    O1 += reversed(O2)

    #for i in O1:
    #    flipper = A[:i]
    #    flipper = [1 - f for f in reversed(flipper)]
    #    A[:i] = flipper
    #print A
    #print B
    #assert A == B

    out.append(len(O1))
    out += O1
print '\n'.join(str(x) for x in out)


import io
import os

from collections import Counter, defaultdict, deque

def solve(N, A, B):
    #print()
    #print()
    def f(A):
        p = []
        front = []
        i = 0
        #print('A', A)
        while i < N:
            x = A[i]
            if not front:
                front.append([x, 1])
            elif front[-1][0] != x:
                if len(front) == 1:
                    front.append([x, 1])
                else:
                    assert len(front) == 2
                    #print('flip', front[0][1])
                    p.append(front[0][1])
                    front[0][0] ^= 1
                    front[0][1] = front[0][1] + front[1][1]
                    front[1][0] = x
                    front[1][1] = 1
                    assert front[0][0] != front[1][0]
            else:
                assert front[-1][0] == x
                front[-1][1] += 1
            i += 1
            #print(*[[y] * c for y, c in front], A[i:])
        if len(front) == 2:
            #print('flip', front[0][1])
            p.append(front[0][1])
            front[0][0] ^= 1
        #print('parity', front[0][0])
        return front[0][0], p

    parity1, p1 = f(A)
    parity2, p2 = f(B)
    if parity1 != parity2:
        p1.append(N)
    p2 = deque(p2)
    while p1 and p2 and p1[-1] == p2[-1]:
        p1.pop()
        p2.pop()
    p2 = list(p2)[::-1]
    #assert len(p1) + len(p2) <= 2 * N
    return str(len(p1) + len(p2)) + ' ' + ' '.join([str(x) for x in p1 + p2])

if __name__ == "__main__":
    input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

    T = int(input())
    for t in range(T):
        N, = [int(x) for x in input().split()]
        A = list(map(int, input().decode().rstrip()))
        B = list(map(int, input().decode().rstrip()))
        ans = solve(N, A, B)
        print(ans)


import io
import os

from collections import Counter, defaultdict, deque

def solve(N, A, B):
    def f(A):
        p = []
        front = []
        i = 0
        while i < N:
            x = A[i]
            if not front:
                front.append([x, 1])
            elif front[-1][0] != x:
                if len(front) == 1:
                    front.append([x, 1])
                else:
                    assert len(front) == 2
                    p.append(front[0][1])
                    p.append(1)
                    front[0][0] ^= 1
                    front[0][1] = front[0][1] + front[0][1]
                    front[1][0] = x
                    front[1][1] = 1
                    assert front[0][0] != front[1][0]
            else:
                assert front[-1][0] == x
                front[-1][1] += 1
            i += 1
            # print(front, A[:i])
        if len(front) == 2:
            p.append(front[0][1])
            front[0][0] ^= 1
            front[0][1] = front[0][1] + front[0][1]
            front[1][0] = x
            front[1][1] = 1
        return front[0][0], p

    parity1, p1 = f(A)
    parity2, p2 = f(B)
    if parity1 != parity2:
        p1.append(N)
    p2 = deque(p2)
    while p1 and p2 and p1[-1] == p2[-1]:
        p1.pop()
        p2.pop()
    p2 = list(p2)[::-1]

    #assert len(p1) + len(p2) <= 2 * N
    return str(len(p1) + len(p2)) + ' ' + ' '.join([str(x) for x in p1 + p2])

if __name__ == "__main__":
    input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

    T = int(input())
    for t in range(T):
        N, = [int(x) for x in input().split()]
        A = list(map(int, input().decode().rstrip()))
        B = list(map(int, input().decode().rstrip()))
        ans = solve(N, A, B)
        print(ans)


for _ in range(int(input())):
    n=int(input())
    a=input()
    b=input()
    l=[]
    for i in range(n):
        if a[i]!=b[i]:
            l+=[i+1,1,i+1]
    print(len(l),*l)


def op(p, c):
    pref = c[:p].copy()
    for i in range(p-1, -1, -1):
        c[i] = (pref[p-i-1] + 1) % 2
   #print(c, ":", p)

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, list(input())))
    b = list(map(int, list(input())))
    array = []
    cnt = [0]*n

    for i in range(n-1, -1, -1):
        if b[i] == a[0]:
            array.append(1)
            op(1, a)
        array.append(i+1)
        op(i+1, a)
    #print(a)
    print(len(array), *array)


def op(p, c):
    for i in range(p-1, -1, -1):
        c[i] = (c[p-i-1] + 1) % 2
   #print(c, ":", p)

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, list(input())))
    b = list(map(int, list(input())))
    array = []
    for i in range(n-1, -1, -1):
        if a[i] != b[i]:
            if b[i] == a[0]:
                array.append(1)
                op(1, a)
            array.append(i+1)
            op(i+1, a)
    print(len(array), *array)


def op(p, c):
    pref = c[:p].copy()
    for i in range(p-1, -1, -1):
        c[i] = (pref[p-i-1] + 1) % 2
   #print(c, ":", p)

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, list(input())))
    b = list(map(int, list(input())))
    array = []
    for i in range(n-1, -1, -1):
        if a[i] != b[i]:
            if b[i] == a[0]:
                array.append(1)
                op(1, a)
            array.append(i+1)
            op(i+1, a)
    print(a)
    print(len(array), *array)


def op(p, c):
    pref = c[:p].copy()
    for i in range(p-1, -1, -1):
        c[i] = (pref[p-i-1] + 1) % 2
   #print(c, ":", p)

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, list(input())))
    b = list(map(int, list(input())))
    array = []
    for i in range(n-1, -1, -1):
        if a[i] != b[i]:
            if b[i] == a[0]:
                array.append(1)
                op(1, a)
            array.append(i+1)
            op(i+1, a)
    #print(a)
    print(len(array), *array)


for _ in range(int(input())):
    n = int(input())
    a= input()
    b= input()
    res = []
    for i in range(n):
        if a[i]!=b[i]:
            res.append(i+1)
            res.append(1)
            res.append(i+1)
    print(len(res),*res)


t = int(input())
for _ in range(t):
    n = int(input())
    a = input()
    b = input()
    ops1 = []
    ops2 = []
    for i in range(len(a)-1):
        if a[i] != a[i+1]:
            ops1.append(i+1)
            if a[i] == '0':
                prefix = '1'*(i+1)
            else:
                prefix = '0'*(i+1)
            a = prefix + a[i+1:]

    for i in range(len(b)-1):
        if b[i] != b[i+1]:
            ops2.append(i+1)
            if b[i] == '0':
                prefix = '1'*(i+1)
            else:
                prefix = '0'*(i+1)
            b = prefix + b[i+1:]
    ops2 = list(reversed(ops2))
    if a[0] != b[0]:
        ops1.append(n)
    print(*ops1, *ops2)


t = int(input())
for _ in range(t):
    n = int(input())
    a = input()
    b = input()
    ops1 = []
    ops2 = []
    for i in range(len(a)-1):
        if a[i] != a[i+1]:
            ops1.append(i+1)
            if a[i] == '0':
                prefix = '1'*(i+1)
            else:
                prefix = '0'*(i+1)
            a = prefix + a[i+1:]

    for i in range(len(b)-1):
        if b[i] != b[i+1]:
            ops2.append(i+1)
            if b[i] == '0':
                prefix = '1'*(i+1)
            else:
                prefix = '0'*(i+1)
            b = prefix + b[i+1:]
    ops2 = list(reversed(ops2))
    if a[0] != b[0]:
        ops1.append(n)
    print(len(ops1) + len(ops2), *ops1, *ops2)


t = int(input())
for _ in range(t):
    n = int(input())
    a = input()
    b = input()
    steps = []
    if a == b:
        print (0)
        continue
    for i in range(n-1,-1,-1):
        if a[i]!=b[i]:
            steps.append(i+1)
            steps.append(1)
            steps.append(i+1)
    print (len(steps),*steps)


t = int(input())
for _ in range(t):
    n = int(input())
    a = input()
    b = input()
    steps = []
    if a == b:
        print (0)
        continue
    for i in range(n-1,-1,-1):
        if a[i]!=b[i]:
            steps.append(i+1)
            steps.append(1)
            steps.append(i+1)
    print (*steps)


for _ in range(int(input())):
    n=int(input())
    s=input()
    for i in range(n):
        if s[i]==s[-1-i]:
            print(1)
        print(n-i)


for _ in range(int(input())):
    n=int(input())
    s=input()
    sm=input()
    a=list(s)
    asm=list(sm[::-1])
    i=0
    l=[]
    while i<n and list(sm)!=a:
        if a[0]==sm[n-i-1]:
            if a[0]=='0':
                a[0]='1'
            else:
                a[0]='0'
            l.append(1)
        for x in range(n-i):
            if a[x]=='1':
                a[x]='0'
            else:
                a[x]='1'
        a[:n-i]=a[n-i-1::-1]
        l.append(n-i)
        i+=1
    print(len(l),*l)


for _ in range(int(input())):
    n=int(input())
    s=input()
    sm=input()
    for i in range(n):
        if s[i]==sm[-1-i]:
            print(1,end=" ")
        print(n-i,end=" ")
    print('\n')


for _ in range(int(input())):
    n=int(input())
    s=input()
    sm=input()
    a=[]
    for i in range(n):
        if a[0]==sm[n-i-1]:
            a.append(1)
        else:
            a.append(n-i)
    print(len(a),*a)


for _ in range(int(input())):
    n=int(input())
    s=input()
    sm=input()
    a=[]
    i=0
    while i<n and list(sm)!=a:
        if s[0]==sm[n-i-1]:
            a.append(1)
        a.append(n-i)
        i+=1
    print(len(a),*a)


for _ in range(int(input())):
    n=int(input())
    s=input()
    for i in range(n):
        if s[i]==s[-1-i]:
            print(1,end=" ")
        print(n-i,end=" ")
    print('\n')


for _ in range(int(input())):
    n=int(input())
    s=input()
    sm=input()
    a=[]
    for i in range(n):
        if s[0]==sm[n-i-1]:
            a.append(1)
        else:
            a.append(n-i)
    print(len(a),*a)


for _ in range(int(input())):
    n=int(input())
    s=input()
    s_=s[::-1]
    print(s+'\n'+s_)
    for i in range(n):
        if s[i]==s[-1-i]:
            print(1)
        print(n-i)


def convert_to_1(s):
    L=[]
    for i in range(len(s)-1):
        if s[i]!=s[i+1]:L.append(i+1)
    if s[-1]=='0':L.append(len(s))
    return L
for i in ' '*(int(input())):
    n=int(input())
    s1=input()
    s2=input()
    L1=convert_to_1(s1)
    L2=convert_to_1(s2)
    L=L1+L2[::-1]
    print(len(L),end=' ')
    for i in L:print(i,end=' ')
    print()


def run():
	import sys
	sys.stdin = open('/home/punit/Documents/Cpp Programs/input.txt', 'r')
	sys.stdout = open('/home/punit/Documents/Cpp Programs/output.txt', 'w')
	from math import ceil,sqrt,floor

# run()
for _ in range(int(input())):
	n = int(input())
	f = input()
	s = input()
	for i in range(n-1,0,-1):
		if f[i]!=s[i]:
			if s[i]==f[0]:
				print(1,end=" ")
				print(i+1,end=" ")
			else:
				print(i+1,end=" ")
	if s[0]!=f[0]:
		print(1,end=" ")
	if s==f:
		print(0,end=" ")
	print()


def run():
	import sys
	sys.stdin = open('/home/punit/Documents/Cpp Programs/input.txt', 'r')
	sys.stdout = open('/home/punit/Documents/Cpp Programs/output.txt', 'w')
	from math import ceil,sqrt,floor

# run()
for _ in range(int(input())):
	n = int(input())
	f = input()
	s = input()
	ans=[]
	for i in range(n):
		if f[i]!=s[i] and i==0:
			ans.append(i+1)
			ans.append(i+1)
			ans.append(i+1)
		elif f[i]!=s[i]:
			ans.append(i+1)
			ans.append(1)
			ans.append(i+1)
	print(len(ans),*ans)


import os
import sys
#input = sys.stdin.buffer.readline
input = sys.stdin.readline
#sys.setrecursionlimit(int(3e5))
from collections import deque
from queue import PriorityQueue
import math
import copy
#  list(map(int, input().split()))
#####################################################################################

class AC(object):
    def fan(self, s, pos):
        for i in range(pos+1):
            if(s[i] == '0'):
                s[i] = '1'
            else:
                s[i] = '0'
        pass

    def __init__(self):
        t = int(input())
        for _ in range(t):
            n = int(input())
            a = list(input())
            b = list(input())
            ans = []

            for pos in range(n)[::-1]:
                if(b[pos] == a[0]):
                    ans.append(1)
                    self.fan(a, 0)
                pass
                ans.append(pos+1)
                self.fan(a, pos)
                a = a[:pos+1][::-1]+ a[pos+1:]
            pass
            print(len(ans), end = ' ')
            print(' '.join(map(str, ans)))
        pass

    def main(self):

        pass

if __name__ == "__main__":
    ac = AC()
    ac.main()
    pass


i = int(input())
while(i>0):
    i = i-1
    c = int(input())
    d = input()
    e = input()
    z = c
    o =0
    p =[]
    a = []
    b = []
    for n in range(c):
        a.append(int(d[n]))
        b.append(int(e[n]))
    while(z):
        if(a[z-1]==b[z-1]):
            z = z-1
        elif(a[0] == b[z-1]):
            p.append(1)
            p.append(z)
            o = o+2
            z = z - 1
            c = a[1:z+1]
            for j in range(z):
                if(c[z-1-j]==1):
                    a[j] = 0
                else:
                    a[j]= 1

        else:
            p.append(z)
            o = o+1
            z = z - 1
            c = a[1:z + 1]
            for j in range(z):
                if (c[z - 1 - j] == 1):
                    a[j] = 0
                else:
                    a[j] = 1
    print(o,end=" ")
    for u in range(len(p)):
        print(p[u],end=" ")


import sys
input = sys.stdin.readline
from collections import deque

t = int(input())
for _ in range(t):
    n = int(input())
    a = input()
    b = input()

    q = deque([i for i in range(n)])
    rev = False
    ans = []
    for i in range(n)[::-1]:
        if rev:
            a_ind = q[0]
            if a[a_ind] != b[i]:
                q.popleft()
                continue
            else:
                if a[q[-1]] == b[i]:
                    ans.append(i + 1)
                else:
                    ans.append(1)
                    ans.append(i + 1)
                q.pop()
                rev = False
        else:
            a_ind = q[-1]
            if a[a_ind] == b[i]:
                continue
                q.pop()
            else:
                if a[q[0]] != b[i]:
                    ans.append(i + 1)
                else:
                    ans.append(1)
                    ans.append(i + 1)
                q.popleft()
                rev = True
    print(len(ans), *ans)


import sys
input = sys.stdin.readline
from collections import deque

t = int(input())
for _ in range(t):
    n = int(input())
    a = input()
    b = input()

    q = deque([i for i in range(n)])
    rev = False
    ans = []
    for i in range(n)[::-1]:
        if rev:
            a_ind = q[0]
            if a[a_ind] != b[i]:
                q.popleft()
                continue
            else:
                if a[q[-1]] == b[i]:
                    ans.append(i + 1)
                else:
                    ans.append(1)
                    ans.append(i + 1)
                q.pop()
                rev = False
        else:
            a_ind = q[-1]
            if a[a_ind] == b[i]:
                q.pop()
                continue
            else:
                if a[q[0]] != b[i]:
                    ans.append(i + 1)
                else:
                    ans.append(1)
                    ans.append(i + 1)
                q.popleft()
                rev = True
    print(len(ans), *ans)


t = int(input())
for i in range(t):
	f=lambda: map(int, input().split(' '))
	n = int(input())
	a = input()
	b = input()
	s = ''
	flag = 0
	for i in range(n):
		if a[i]!=b[i]:
			flag = 1
			break
	if flag == 0:
		print(0)
	else:

		for i in range(len(b)-1,-1,-1):
			if b[i]=='0':
				s+='1'
			else:
				s+='0'
		k = []
		for i in range(0,n-1):
			if a[i]!=a[i+1]:
				k.append(i+1)
		j = []
		for i in range(0,n-1):
			if s[i]!=s[i+1]:
				j.append(i+1)

		if s[-1]!=a[-1]:
			j.append(n)

		j.reverse()

		k = k +j
		k.append(n)
		k = [len(k)]+k

		for i in k:
			print(i , end=" ")


import sys
input = sys.stdin.readline

T = int(input())

# def check(A, B, ops):
#     for op in ops:
#         # print('op', op)
#         # print('A', A)
#         A = ['1' if el == '0' else '0' for el in A[:op]][::-1] + A[op:]
#         # print('A after', A)

#     if A != B:
#         print(A, B, ops)
#         assert False

for t in range(T):
    N = int(input())

    A = input()[:-1]
    B = input()[:-1]
    # simuA = list(A)

    answer = []

    el0 = A[0]
    for i in range(N-1, -1, -1):
        # print('i', i)
        # print('A is', simuA)
        # print('el0', el0)
        if el0 == B[i]:
            answer.append(1)
            # simuA[0] = '0' if simuA[0] == '1' else '1'
            # print('B[i] is', B[i])
            # print('simuA is', simuA)
        answer.append(i+1)
        # simuA = ['1' if el == '0' else '0' for el in simuA[:i+1]][::-1] + simuA[i+1:]
        # print('simuA is', simuA)
        if i == N-1:
            el0 = '0' if A[i] == '1' else '1'
        elif (N-i) % 2:
            el0 = '0' if A[N-1-(N-i-1)//2] == '1' else '1'
        else:
            # print('Setting el0 because pair', N-i, A[(N-i)//2])
            el0 = A[(N-i)//2]

    print(len(answer), ' '.join(map(str, answer)))

    # check(list(A), list(B), answer)


import sys
input = sys.stdin.readline
from collections import deque

t=int(input())
for tests in range(t):
    n=int(input())

    a=input().strip()
    b=input().strip()

    Q=deque(a)

    L=[]
    while Q:
        L.append(Q.popleft())

        if Q:
            L.append(Q.pop())

    ANS=[]
    for i in range(n):
        if i%2==0:
            if L[i]==b[-1-i]:
                ANS.append(1)
        else:
            if L[i]!=b[-1-i]:
                ANS.append(1)

        ANS.append(n-i)

    print(len(ANS),*ANS)


from sys import stdin
t = int(input())

#a = [1,2,3,4,5]
#for i in range(len(a)//2):
   # a[i],a[4-i] = a[4-i],a[i]

#print(a)
input = stdin.readline
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().strip()]
    b = [int(i) for i in input().strip()]
    ans = []
    for i in range(n-1,-1,-1):
        if a[i]!=b[i]:
            if a[0]!=a[i] or i==0:
                ans.append(1)
                a[0]^=1
                if i==0:
                    continue
            ans.append(i+1)
            for j in range((i+1)//2):
                if a[j] == a[i-j]:
                    if j!=i-j:
                        a[j]^=1
                    a[i-j]^=1
    print(len(ans),*ans)


from sys import stdin
t = int(input())

#a = [1,2,3,4,5]
#for i in range(len(a)//2):
   # a[i],a[4-i] = a[4-i],a[i]

#print(a)
input = stdin.readline
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().strip()]
    b = [int(i) for i in input().strip()]
    ans = []
    for i in range(n-1,-1,-1):
        if a[i]!=b[i]:
            if a[0]!=a[i]:
                ans.append(1)
            ans.append(i+1)
            for j in range((i+1)//2):
                if a[i] == a[n-1-j]:
                    if i!=n-1-j:
                        a[i]^=1
                    a[n-1-j]^=1
    print(len(ans),end=" ")
    print(*ans,sep=" ")


from sys import stdin
t = int(input())

#a = [1,2,3,4,5]
#for i in range(len(a)//2):
   # a[i],a[4-i] = a[4-i],a[i]

#print(a)
input = stdin.readline
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().strip()]
    b = [int(i) for i in input().strip()]
    ans = []
    for i in range(n-1,-1,-1):
        if a[i]!=b[i]:
            if a[0]!=a[i]:
                ans.append(1)
            ans.append(i+1)
            for j in range((i+1)//2):
                if a[j] == a[i+1-1-j]:
                    if j!=i+1-1-j:
                        a[j]^=1
                    a[i+1-1-j]^=1
    print(len(ans),end=" ")
    print(*ans,sep=" ")


from sys import stdin
t = int(input())

#a = [1,2,3,4,5]
#for i in range(len(a)//2):
   # a[i],a[4-i] = a[4-i],a[i]

#print(a)
input = stdin.readline
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().strip()]
    b = [int(i) for i in input().strip()]
  #  print(a,b)
    ans = []
    for i in range(n-1,-1,-1):
        if a[i]!=b[i]:
            if a[0]!=a[i] or i==0:
                ans.append(1)
                a[0]^=1
                if i==0:
                    continue
            ans.append(i+1)
   #         print((i+1)//2)
            for j in range((i+1)//2+(1-i%2)):
    #            print("a",a)
    #            print("b",b)
                if a[j] == a[i-j]:
                    if j!=i-j:
                        a[j]^=1
                    a[i-j]^=1
  #      print("a",a)
   #     print("b",b)
#    print(a,b)
    assert a==b
    print(len(ans),*ans)


from sys import stdin
t = int(input())

#a = [1,2,3,4,5]
#for i in range(len(a)//2):
   # a[i],a[4-i] = a[4-i],a[i]

#print(a)
input = stdin.readline
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().strip()]
    b = [int(i) for i in input().strip()]
    ans = []
    for i in range(n-1,-1,-1):
        if a[i]!=b[i]:
            if a[0]!=a[i]:
                ans.append(1)
            ans.append(i+1)
            for j in range((i+1)//2):
                if a[j] == a[n-1-j]:
                    if j!=n-1-j:
                        a[j]^=1
                    a[n-1-j]^=1
    print(len(ans),end=" ")
    print(*ans,sep=" ")


T = int(input())

def flip(el):
    if el=='1':
        return '0'
    else:
        return '1'
def oper(arr):
    return [flip(el) for el in arr[::-1]]
def solve(a,b):
    ans = ''
    opc = 0
    for i in range(0,n):
        #print(n-i-1,a,b)
        if a[n-i-1]!=b[n-i-1]:
            #print(n-i-1)
            if a[0]==a[n-i-1]:

                ans+=str(n-i) + ' '
                a = oper(a[:n-i])
                opc += 1
            else:
                ans+='1' + ' ' + str(n-i) + ' '
                a = oper(a[:n-i])
                opc +=2
        else:
            continue
    return ans,opc

while T>0:

    n = int(input())

    a = [(el) for el in input()]
    b = [(el) for el in input()]

    if a!=b:

        ans,opc = solve(a,b)

        if n==1:
            print('1 1')
        else:
            print(str(opc) + ' ' + ans)

    else:
        print(0)

    T-=1


from sys import stdin
import math
inp = lambda : stdin.readline().strip()

t = int(inp())
for _ in range(t):
    n = int(inp())
    a = inp()
    b = inp()
    eq = []
    fin = []
    if n == 1:
        if a == b:
            print(0)
        else:
            print("1 1")
    else:
        for i in range(n-1):
            if a[i] != a[i+1]:
                eq.append(i+1)
        for i in range(n-2, -1, -1):
            if b[i] != b[i+1]:
                fin.append(i+1)
        if a[-1] != b[-1] and eq[len(eq)-1] != n:
            eq.append(n)
        print(len(eq)+len(fin), end = " ")
        print(*eq, end = " ")
        print(*fin)


from sys import stdin
inp = lambda : stdin.readline().strip()

n = int(inp())
a = [int(x) for x in inp().split()]
ans = 0
for i in range(n):
    if i > 0:
        if a[i] + a[i-1] == 5:
            print("Infinite")
            break
        elif a[i] == 2 and a[i-1] == 1:
            ans += 3
        elif a[i] == 3 and a[i-1] == 1:
            ans += 4
        elif a[i] == 1:
            if a[i-1] == 2:
                ans += 3
            if a[i-1] == 3:
                ans += 4
    if i > 1:
        if a[i] == 2 and a[i-2] == 3:
            ans-=1
else:
    print("Finite")
    print(ans)


from sys import stdin
import math
inp = lambda : stdin.readline().strip()

t = int(inp())
for _ in range(t):
    n = int(inp())
    a = inp()
    b = inp()
    eq = []
    fin = []
    if n == 1:
        if a == b:
            print(0)
        else:
            print("1 1")
    else:
        for i in range(n-1):
            if a[i] != a[i+1]:
                eq.append(i+1)
        for i in range(n-1, -1, -1):
            if i < n-1:
                if b[i] != b[i+1]:
                    fin.append(i+1)
        if a[n-1] != b[n-1] and eq[len(eq)-1] != n:
            eq.append(n)
        print(len(eq)+len(fin), end = " ")
        print(*eq, end = " ")
        print(*fin)


from sys import stdin
import math
inp = lambda : stdin.readline().strip()

t = int(inp())
for _ in range(t):
    n = int(inp())
    a = inp()
    b = inp()
    eq = []
    fin = []
    if n == 1:
        if a == b:
            print(0)
        else:
            print("1 1")
    else:
        for i in range(n-1):
            if a[i] != a[i+1]:
                eq.append(i+1)
        for i in range(n-2, -1, -1):
            if b[i] != b[i+1]:
                fin.append(i+1)
        if a[-1] != b[-1]:
            eq.append(n)
        print(len(eq)+len(fin), end = " ")
        print(*eq, end = " ")
        print(*fin)


for _ in range(int(input())):
    n=int(input())
    a=input()
    b=input()
    a=[int(a[i]) for i in range(n)]
    b=[int(b[i]) for i in range(n)]
    count=0
    res=[]
    for i in range(n-1,-1,-1):
        if a[i]!=b[i]:
            if a[0]!=b[i]:
                count+=1
                res.append(i+1)
                newa=[a[j] for j in range(n)]
                for j in range(i,-1,-1):
                    id=i-j
                    newa[j]=(1+a[id])%2
                a=newa
            else:
                count+=1
                res.append(1)
                a[0]=(1+a[0])%2
                count+=1
                res.append(i+1)
                newa=[a[j] for j in range(n)]
                for j in range(i,-1,-1):
                    id=i-j
                    newa[j]=(1+a[id])%2
                a=newa
    res=[count]+res
    print(*res)


list_input = lambda: list(map(int, input().split()))
int_input = lambda: int(input())

def count_vals(l):
    d = {}
    for i in l:
        d[i] = d.get(i, 0) + 1
    return d

def bit_inv(b):
    if b == '1':
        return '0'
    else:
        return '1'

def opp(s, n):
    for i in range((n + 1) // 2):
        # print(s[i], s[n-i])
        s[i], s[n-i] = bit_inv(s[n-i]), bit_inv(s[i])

    if (n + 1) % 2:
        s[(n + 1) // 2] = bit_inv(s[(n + 1) // 2])

    # print(n, ''.join(s))
    return s

def solve(a, b, n):
    l = []
    for i in range(n-1, 0, -1):
        x = a[0]
        if x == b[i]:
            a[0] = bit_inv(a[0])
            l.append(1)
            l.append(i+1)
        else:
            l.append(i+1)

        # a[0] = bit_inv(a[i])
        # print(i, a[0])
        a = opp(a, i)
        # print(a)

    if a[0] != b[0]:
        l.append(1)
        a[0] = bit_inv(a[0])

    return l

#
#
# for _ in range(int_input()):
#     n = int_input()
#     a = list(input())
#     b = list(input())
#
#     l = []
#     for i in range(n-1, 0, -1):
#         x = a[0]
#         if x == b[i]:
#             l.append(1)
#             l.append(i+1)
#         else:
#             l.append(i+1)
#         a[0] = bit_inv(a[i])
#         print(i, a[0])
#
#
#     if a[0] != b[0]:
#         l.append(1)
#         a[0] = bit_inv(a[0])
#
#     print(len(l), end=" ")
#     print(*l)

for _ in range(int(input())):
    n = int_input()
    a = list(input())
    b = list(input())

    l = solve(a, b, n)

    print(len(l), end=" ")
    print(*l)


list_input = lambda: list(map(int, input().split()))
int_input = lambda: int(input())

def count_vals(l):
    d = {}
    for i in l:
        d[i] = d.get(i, 0) + 1
    return d

def bit_inv(b):
    if b == '1':
        return '0'
    else:
        return '1'

def opp(s, n):
    for i in range((n + 1) // 2):
        print(s[i], s[n-i])
        s[i], s[n-i] = bit_inv(s[n-i]), bit_inv(s[i])

    if (n + 1) % 2:
        s[(n + 1) // 2] = bit_inv(s[(n + 1) // 2])

    # print(n, ''.join(s))
    return s

def solve(a, b, n):
    l = []
    for i in range(n-1, 0, -1):
        x = a[0]
        if x == b[i]:
            a[0] = bit_inv(a[0])
            l.append(1)
            l.append(i+1)
        else:
            l.append(i+1)

        # a[0] = bit_inv(a[i])
        # print(i, a[0])
        a = opp(a, i)
        # print(a)

    if a[0] != b[0]:
        l.append(1)
        a[0] = bit_inv(a[0])

    return l

#
#
# for _ in range(int_input()):
#     n = int_input()
#     a = list(input())
#     b = list(input())
#
#     l = []
#     for i in range(n-1, 0, -1):
#         x = a[0]
#         if x == b[i]:
#             l.append(1)
#             l.append(i+1)
#         else:
#             l.append(i+1)
#         a[0] = bit_inv(a[i])
#         print(i, a[0])
#
#
#     if a[0] != b[0]:
#         l.append(1)
#         a[0] = bit_inv(a[0])
#
#     print(len(l), end=" ")
#     print(*l)

for _ in range(int(input())):
    n = int_input()
    a = list(input())
    b = list(input())

    l = solve(a, b, n)

    print(len(l), end=" ")
    print(*l)


from sys import stdin, stdout

# 0 1 2 3 4 5 6 7 8 9
# 9 8 7 6 5 4 3 2 1 (0) 9
# 1 2 3 4 5 6 7 8 (9)   8
# 8 7 6 5 4 3 2 (1)     7
# 2 3 4 5 6 7 (8)       6
# 7 6 5 4 3 (2)         5
# ..........
t = int(stdin.readline())
for _ in range(t):
    n = int(stdin.readline())
    a = stdin.readline().strip()
    b = stdin.readline().strip()

    ans = []
    idx = 0
    flip = False
    for i in range(n-1, -1, -1):
        if (not flip and a[idx] == b[i]) or (flip and a[idx] != b[i]):
            ans.append(1)
        ans.append(i+1)

        if flip:
            idx -= i
        else:
            idx += i

        flip = not flip

    stdout.write(str(len(ans)) + ' ')
    if len(ans) > 0:
        stdout.write(' '.join(map(str, ans)) + '\n')


#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <set>
#include <stack>
#include <string>
#include <sstream>
#include <map>

#define MohammadAmin main()
#define ll long long int
#define MAX( A, B ) ( A > B ? A : B )

using namespace std;

int MohammadAmin{
    map<string, ll> mp;
    ll n;
    cin >> n;
    string s;
    for ( ll i = 0; i  < n; i++ ) {
        cin >> s;
        mp[s]++;
        if ( mp[s] > 1 ) {
            cout << s << mp[s] - 1 << endl;
            continue;
        }
        cout << "OK" << endl;
    }
    return 0;
}