There are $$$n$$$ cities in Shaazzzland, numbered from $$$0$$$ to $$$n-1$$$. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa.As the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland.AaParsa has planted $$$m$$$ transport cannons in the cities of Shaazzzland. The $$$i$$$-th cannon is planted in the city $$$a_i$$$ and is initially pointing at city $$$b_i$$$.It is guaranteed that each of the $$$n$$$ cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $$$(a_i, b_i)$$$ are distinct).AaParsa used very advanced technology to build the cannons, the cannons rotate every second. In other words, if the $$$i$$$-th cannon is pointing towards the city $$$x$$$ at some second, it will target the city $$$(x + 1) \mod n$$$ at the next second.As their name suggests, transport cannons are for transportation, specifically for human transport. If you use the $$$i$$$-th cannon to launch yourself towards the city that it's currently pointing at, you'll be airborne for $$$c_i$$$ seconds before reaching your target destination.If you still don't get it, using the $$$i$$$-th cannon at the $$$s$$$-th second (using which is only possible if you are currently in the city $$$a_i$$$) will shoot you to the city $$$(b_i + s) \mod n$$$ and you'll land in there after $$$c_i$$$ seconds (so you'll be there in the $$$(s + c_i)$$$-th second). Also note the cannon that you initially launched from will rotate every second but you obviously won't change direction while you are airborne. AaParsa wants to use the cannons for travelling between Shaazzzland's cities in his grand plan, and he can start travelling at second $$$0$$$. For him to fully utilize them, he needs to know the minimum number of seconds required to reach city $$$u$$$ from city $$$v$$$ using the cannons for every pair of cities $$$(u, v)$$$.Note that AaParsa can stay in a city for as long as he wants.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 600 , n \le m \le n^2)$$$ — the number of cities and cannons correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$ and $$$c_i$$$ $$$( 0 \le a_i , b_i \le n-1 , 1 \le c_i \le 10^9)$$$, denoting the cannon in the city $$$a_i$$$, which is initially pointing to $$$b_i$$$ and travelling by which takes $$$c_i$$$ seconds. It is guaranteed that each of the $$$n$$$ cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $$$(a_i, b_i)$$$ are distinct).

Print $$$n$$$ lines, each line should contain $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line should be equal to the minimum time required to reach city $$$j$$$ from city $$$i$$$.

NoteIn the first example one possible path for going from $$$0$$$ to $$$2$$$ would be:   Stay inside $$$0$$$ and do nothing for $$$1$$$ second.  Use the first cannon and land at $$$2$$$ after $$$1$$$ second.  Note that: we could have used the second cannon in $$$0$$$-th second but it would have taken us $$$3$$$ seconds to reach city $$$2$$$ in that case.

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var os = require('os');

const stdin = process.stdin;
const stdout = process.stdout;
const integerRegex = /-?\d+/g;
const decimalRegex = /-?\d+(?:\.\d+)?/g;
class InputAndOutput {
    constructor() {
        this.lineIndex = 0;
        this.lines = [];
    }
    dried() {
        return this.lineIndex >= this.lines.length;
    }
    readLine() {
        const line = this.lines[this.lineIndex];
        this.lineIndex += 1;
        return line;
    }
    readIntegersOfLine() {
        const line = this.readLine();
        const m = line.match(integerRegex);
        if (m == null)
            return [];
        return m.map(x => Number(x));
    }
    readNumsOfLine() {
        const line = this.readLine();
        const m = line.match(decimalRegex);
        if (m == null)
            return [];
        return m.map(x => Number(x));
    }
    print(content) {
        stdout.write(content);
    }
    async init() {
        const lines = await this.readLines();
        this.lines = lines;
    }
    readLines() {
        const buffers = [];
        return new Promise(resolve => {
            stdin.on('data', (buffer) => buffers.push(buffer));
            stdin.on('end', function () {
                const inputs = buffers.join('');
                const lines = inputs.split(os.EOL);
                resolve(lines);
            });
        });
    }
}
async function __main__(handle) {
    const io = new InputAndOutput();
    await io.init();
    handle(io);
}

function solution1(io) {
    const INF = 1e10 + 1;
    const [N, M] = io.readIntegersOfLine();
    const D = new Array(N);
    const G = new Array(N);
    const visited = new Array(N);
    for (let i = 0; i < N; ++i) {
        G[i] = new Array(N);
        for (let j = 0; j < N; ++j)
            G[i][j] = INF;
    }
    for (let i = 0; i < M; ++i) {
        const [a, b, c] = io.readIntegersOfLine();
        G[a][b] = Math.min(G[a][b], c);
    }
    for (let i = 0; i < N; ++i) {
        for (let j = 0; j < N; ++j) {
            D[j] = G[i][j];
            visited[j] = false;
        }
        while (true) {
            let x = -1;
            for (let j = 0; j < N; ++j) {
                if (visited[j])
                    continue;
                if (x === -1 || D[j] < D[x])
                    x = j;
            }
            if (x === -1)
                break;
            visited[x] = true;
            const nextCity = (x + 1) % N;
            if (D[nextCity] > D[x] + 1)
                D[nextCity] = D[x] + 1;
            for (let j = 0; j < N; ++j) {
                const y = (D[x] + j) % N;
                if (D[y] > D[x] + G[x][j])
                    D[y] = D[x] + G[x][j];
            }
        }
        D[i] = 0;
        io.print(D.join(' '));
        io.print('\n');
    }
}
__main__(function (io) {
    solution1(io);
});

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var os = require('os');

const stdin = process.stdin;
const stdout = process.stdout;
const integerRegex = /-?\d+/g;
const decimalRegex = /-?\d+(?:\.\d+)?/g;
class InputAndOutput {
    constructor() {
        this.lineIndex = 0;
        this.lines = [];
    }
    dried() {
        return this.lineIndex >= this.lines.length;
    }
    readLine() {
        const line = this.lines[this.lineIndex];
        this.lineIndex += 1;
        return line;
    }
    readIntegersOfLine() {
        const line = this.readLine();
        const m = line.match(integerRegex);
        if (m == null)
            return [];
        return m.map(x => Number(x));
    }
    readNumsOfLine() {
        const line = this.readLine();
        const m = line.match(decimalRegex);
        if (m == null)
            return [];
        return m.map(x => Number(x));
    }
    print(content) {
        stdout.write(content);
    }
    async init() {
        const lines = await this.readLines();
        this.lines = lines;
    }
    readLines() {
        const buffers = [];
        return new Promise(resolve => {
            stdin.on('data', (buffer) => buffers.push(buffer));
            stdin.on('end', function () {
                const inputs = buffers.join('');
                const lines = inputs.split(os.EOL);
                resolve(lines);
            });
        });
    }
}
async function __main__(handle) {
    const io = new InputAndOutput();
    await io.init();
    handle(io);
}

function solve() { }
__main__(function (io) {
    const INF = 1e10 + 1;
    const [N, M] = io.readIntegersOfLine();
    const D = new Array(N);
    const G = new Array(N);
    const visited = new Array(N);
    for (let i = 0; i < N; ++i) {
        G[i] = new Array(N);
        for (let j = 0; j < N; ++j)
            G[i][j] = INF;
    }
    for (let i = 0; i < M; ++i) {
        const [a, b, c] = io.readIntegersOfLine();
        G[a][b] = Math.min(G[a][b], c);
    }
    for (let i = 0; i < N; ++i) {
        for (let j = 0; j < N; ++j) {
            D[j] = G[i][j];
            visited[j] = false;
        }
        while (true) {
            let x = -1;
            for (let j = 0; j < N; ++j) {
                if (visited[j])
                    continue;
                if (x === -1 || D[j] < D[x])
                    x = j;
            }
            if (x === -1)
                break;
            visited[x] = true;
            const nextCity = (x + 1) % N;
            if (D[nextCity] > D[x] + 1)
                D[nextCity] = D[x] + 1;
            for (let j = 0; j < N; ++j) {
                const y = (D[x] + j) % N;
                if (D[y] > D[x] + G[x][j])
                    D[y] = D[x] + G[x][j];
            }
        }
        D[i] = 0;
        io.print(D.join(' '));
        io.print('\n');
    }
});

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var os = require('os');

const stdin = process.stdin;
const stdout = process.stdout;
const integerRegex = /-?\d+/g;
const decimalRegex = /-?\d+(?:\.\d+)?/g;
class InputAndOutput {
    constructor() {
        this.lineIndex = 0;
        this.lines = [];
    }
    dried() {
        return this.lineIndex >= this.lines.length;
    }
    readLine() {
        const line = this.lines[this.lineIndex];
        this.lineIndex += 1;
        return line;
    }
    readIntegersOfLine() {
        const line = this.readLine();
        const m = line.match(integerRegex);
        if (m == null)
            return [];
        return m.map(x => Number(x));
    }
    readNumsOfLine() {
        const line = this.readLine();
        const m = line.match(decimalRegex);
        if (m == null)
            return [];
        return m.map(x => Number(x));
    }
    print(content) {
        stdout.write(content);
    }
    async init() {
        const lines = await this.readLines();
        this.lines = lines;
    }
    readLines() {
        const buffers = [];
        return new Promise(resolve => {
            stdin.on('data', (buffer) => buffers.push(buffer));
            stdin.on('end', function () {
                const inputs = buffers.join('');
                const lines = inputs.split(os.EOL);
                resolve(lines);
            });
        });
    }
}
async function __main__(handle) {
    const io = new InputAndOutput();
    await io.init();
    handle(io);
}

function solve() { }
__main__(function (io) {
    const INF = 1e10 + 1;
    const [N, M] = io.readIntegersOfLine();
    const D = new Array(N);
    const G = new Array(N);
    const W = new Array(N);
    const visited = new Array(N);
    for (let i = 0; i < N; ++i) {
        G[i] = [];
        W[i] = new Array(N);
        for (let j = 0; j < N; ++j)
            W[i][j] = INF;
    }
    for (let i = 0; i < M; ++i) {
        const [a, b, c] = io.readIntegersOfLine();
        W[a][b] = Math.min(W[a][b], c);
        G[a].push(b);
    }
    for (let i = 0; i < N; ++i) {
        for (let j = 0; j < N; ++j) {
            D[j] = W[i][j];
            visited[j] = false;
        }
        while (true) {
            let x = -1;
            for (let j = 0; j < N; ++j) {
                if (visited[j])
                    continue;
                if (x === -1 || D[j] < D[x])
                    x = j;
            }
            if (x === -1)
                break;
            visited[x] = true;
            const nextCity = (x + 1) % N;
            if (D[nextCity] > D[x] + 1)
                D[nextCity] = D[x] + 1;
            for (const j of G[i]) {
                const y = (D[x] + j) % N;
                if (D[y] > D[x] + G[x][j])
                    D[y] = D[x] + G[x][j];
            }
        }
        D[i] = 0;
        io.print(D.join(' '));
        io.print('\n');
    }
});

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var os = require('os');

const stdin = process.stdin;
const stdout = process.stdout;
const integerRegex = /-?\d+/g;
const decimalRegex = /-?\d+(?:\.\d+)?/g;
class InputAndOutput {
    constructor() {
        this.lineIndex = 0;
        this.lines = [];
    }
    dried() {
        return this.lineIndex >= this.lines.length;
    }
    readLine() {
        const line = this.lines[this.lineIndex];
        this.lineIndex += 1;
        return line;
    }
    readIntegersOfLine() {
        const line = this.readLine();
        const m = line.match(integerRegex);
        if (m == null)
            return [];
        return m.map(x => Number(x));
    }
    readNumsOfLine() {
        const line = this.readLine();
        const m = line.match(decimalRegex);
        if (m == null)
            return [];
        return m.map(x => Number(x));
    }
    print(content) {
        stdout.write(content);
    }
    async init() {
        const lines = await this.readLines();
        this.lines = lines;
    }
    readLines() {
        const buffers = [];
        return new Promise(resolve => {
            stdin.on('data', (buffer) => buffers.push(buffer));
            stdin.on('end', function () {
                const inputs = buffers.join('');
                const lines = inputs.split(os.EOL);
                resolve(lines);
            });
        });
    }
}
async function __main__(handle) {
    const io = new InputAndOutput();
    await io.init();
    handle(io);
}

function solve() { }
const INF = 1e10 + 1;
const MAX_N = 600 + 10;
const visited = new Array(MAX_N);
const D = new Array(MAX_N);
const G = new Array(MAX_N);
for (let i = 0; i < G.length; ++i)
    G[i] = new Array(MAX_N);
__main__(function (io) {
    const [N, M] = io.readIntegersOfLine();
    for (let i = 0; i < N; ++i) {
        for (let j = 0; j < N; ++j)
            G[i][j] = INF;
        G[i][i] = 0;
    }
    for (let i = 0; i < M; ++i) {
        const [a, b, c] = io.readIntegersOfLine();
        G[a][b] = Math.min(G[a][b], c);
    }
    for (let i = 0; i < N; ++i) {
        for (let j = 0; j < N; ++j) {
            D[j] = G[i][j];
            visited[j] = false;
        }
        while (true) {
            let x = -1;
            for (let j = 0; j < N; ++j) {
                if (visited[j])
                    continue;
                if (x === -1 || D[j] < D[x])
                    x = j;
            }
            if (x === -1)
                break;
            visited[x] = true;
            const d = D[x];
            for (let j = 0; j < N; ++j) {
                const y = (D[x] + j) % N;
                D[y] = Math.min(D[y], d + j);
            }
        }
        io.print(String(D[0]));
        for (let j = 1; j < N; ++j)
            io.print(' ' + D[j]);
        io.print('\n');
    }
});


There is an undirected, connected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. A walk from vertex $$$u$$$ to vertex $$$v$$$ is defined as a sequence of vertices $$$p_1,p_2,\ldots,p_k$$$ (which are not necessarily distinct) starting with $$$u$$$ and ending with $$$v$$$, such that $$$p_i$$$ and $$$p_{i+1}$$$ are connected by an edge for $$$1 \leq i < k$$$.We define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.More formally, let us have $$$[w_1,w_2,\ldots,w_{k-1}]$$$ where $$$w_i$$$ is the weight of the edge between $$$p_i$$$ and $$$p_{i+1}$$$. Then the length of the walk is given by $$$\mathrm{MEX}(\{w_1,\,w_1\& w_2,\,\ldots,\,w_1\& w_2\& \ldots\& w_{k-1}\})$$$, where $$$\&$$$ denotes the bitwise AND operation.Now you must process $$$q$$$ queries of the form u v. For each query, find the minimum possible length of a walk from $$$u$$$ to $$$v$$$.The MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance:   The MEX of $$$\{2,1\}$$$ is $$$0$$$, because $$$0$$$ does not belong to the set.  The MEX of $$$\{3,1,0\}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the set, but $$$2$$$ does not.  The MEX of $$$\{0,3,1,2\}$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the set, but $$$4$$$ does not.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10^5$$$; $$$n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2},10^5\right)}$$$). Each of the next $$$m$$$ lines contains three integers $$$a$$$, $$$b$$$, and $$$w$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$; $$$0 \leq w < 2^{30}$$$) indicating an undirected edge between vertex $$$a$$$ and vertex $$$b$$$ with weight $$$w$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$). Each of the next $$$q$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$, $$$u \neq v$$$), the description of each query.

For each query, print one line containing a single integer — the answer to the query.

NoteThe following is an explanation of the first example.    The graph in the first example. Here is one possible walk for the first query:$$$$$$1 \overset{5}{\rightarrow} 3 \overset{3}{\rightarrow} 2 \overset{1}{\rightarrow} 1 \overset{5}{\rightarrow} 3 \overset{1}{\rightarrow} 4 \overset{2}{\rightarrow} 5.$$$$$$The array of weights is $$$w=[5,3,1,5,1,2]$$$. Now if we take the bitwise AND of every prefix of this array, we get the set $$$\{5,1,0\}$$$. The MEX of this set is $$$2$$$. We cannot get a walk with a smaller length (as defined in the statement).

'use strict';

var readline = require('readline');
var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(n, m, edges, querys) {
  const ps = Array.from({
    length: 30
  }, () => [...new Array(n).keys()]),
        ps1 = Array.from({
    length: 29
  }, () => [...new Array(n).keys()]),
  flag = [];
  const find = (i, p) => {
    if (p[i] !== i) p[i] = find(p[p[i]], p);
    return p[i];
  };
  const union = (i, j, p) => {
    const ri = find(i, p),
          rj = find(j, p);
    if (ri !== rj) p[rj] = ri;
  };
  const h = new Array(n).fill(-1),
        e = [],
        ne = [],
        w = [];
  let idx = 0;
  const add = (i, j, c) => {
    e[idx] = j, w[idx] = c, ne[idx] = h[i], h[i] = idx++;
  };
  for (let [u, v, c] of edges) {
    add(u, v, c);
    add(v, u, c);
  }
  for (let i = 0; i < 30; i++) {
    const p = ps[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i) {
          union(j, l, p);
        }
      }
    }
  }
  for (let i = 0; i < 29; i++) {
    const p1 = ps1[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i + 1) union(j, l, p1);
      }
    }
    const even = [];
    for (let [u, v, c] of edges) {
      if (!(c & 1)) {
        even[find(u, p1)] = 1;
        even[find(v, p1)] = 1;
      }
    }
    for (let i = 0; i < n; i++) {
      if (even[find(i, p1)]) {
        flag[i] = 1;
      }
    }
  }
  let res = [];
  for (let [u, v] of querys) {
    let ans = 2;
    for (let i = 0; i < 30; i++) {
      const p = ps[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 0;
        break;
      }
    }
    if (ans !== 2) {
      res.push(ans);
      continue;
    }
    if (flag[u]) {
      res.push(1);
      continue;
    }
    for (let i = 0; i < 29; i++) {
      const p = ps1[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 1;
        break;
      }
    }
    res.push(ans);
  }
  console.log(res.join('\n'));
}

async function main(read) {
  const [n, m] = (await read()).split(' ').map(Number);
  const edges = [],
        querys = [];
  let t = m;
  while (t--) {
    const [u, v, w] = (await read()).split(' ').map(Number);
    edges.push([u - 1, v - 1, w]);
  }
  t = Number(await read());
  while (t--) {
    const [u, v] = (await read()).split(' ').map(Number);
    querys.push([u - 1, v - 1]);
  }
  solve(n, m, edges, querys);
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split('\n');
readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  let i = 0;
  async function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, edges, querys) {
  const ps = Array.from({
    length: 30
  }, () => [...new Array(n).keys()]),
        ps1 = Array.from({
    length: 29
  }, () => [...new Array(n).keys()]),
  flag = [];
  const find = (i, p) => {
    if (p[i] !== i) p[i] = find(p[p[i]], p);
    return p[i];
  };
  const union = (i, j, p) => {
    const ri = find(i, p),
          rj = find(j, p);
    if (ri !== rj) p[rj] = ri;
  };
  const h = new Array(n).fill(-1),
        e = [],
        ne = [],
        w = [];
  let idx = 0;
  const add = (i, j, c) => {
    e[idx] = j, w[idx] = c, ne[idx] = h[i], h[i] = idx++;
  };
  for (let [u, v, c] of edges) {
    add(u, v, c);
    add(v, u, c);
  }
  for (let i = 0; i < 30; i++) {
    const p = ps[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i) {
          union(j, l, p);
        }
      }
    }
  }
  for (let i = 0; i < 29; i++) {
    const p1 = ps1[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i + 1) union(j, l, p1);
      }
    }
    const even = [];
    for (let [u, v, c] of edges) {
      if (!(c & 1)) {
        even[find(u, p1)] = 1;
        even[find(v, p1)] = 1;
      }
    }
    for (let i = 0; i < n; i++) {
      if (even[find(i, p1)]) {
        flag[i] = 1;
      }
    }
  }
  let res = [];
  for (let [u, v] of querys) {
    let ans = 2;
    for (let i = 0; i < 30; i++) {
      const p = ps[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 0;
        break;
      }
    }
    if (ans !== 2) {
      res.push(ans);
      continue;
    }
    if (flag[u]) {
      res.push(1);
      continue;
    }
    for (let i = 0; i < 29; i++) {
      const p = ps1[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 1;
        break;
      }
    }
    res.push(ans);
  }
  console.log(res.join('\n'));
}

async function main(read) {
  const [n, m] = (await read()).split(' ').map(Number);
  const edges = [],
        querys = [];
  let t = m;
  while (t--) {
    const [u, v, w] = (await read()).split(' ').map(Number);
    edges.push([u - 1, v - 1, w]);
  }
  t = Number(await read());
  while (t--) {
    const [u, v] = (await read()).split(' ').map(Number);
    querys.push([u - 1, v - 1]);
  }
  solve(n, m, edges, querys);
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  //
  async function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, edges, querys) {
  const ps = Array.from({
    length: 30
  }, () => [...new Array(n).keys()]),
        ps1 = Array.from({
    length: 29
  }, () => [...new Array(n).keys()]),
  flag = [];
  const find = (i, p) => {
    if (p[i] !== i) p[i] = find(p[p[i]], p);
    return p[i];
  };
  const union = (i, j, p) => {
    const ri = find(i, p),
          rj = find(j, p);
    if (ri !== rj) p[rj] = ri;
  };
  const h = new Array(n).fill(-1),
        e = [],
        ne = [],
        w = [];
  let idx = 0;
  const add = (i, j, c) => {
    e[idx] = j, w[idx] = c, ne[idx] = h[i], h[i] = idx++;
  };
  for (let [u, v, c] of edges) {
    add(u, v, c);
    add(v, u, c);
  }
  for (let i = 0; i < 30; i++) {
    const p = ps[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i) {
          union(j, l, p);
        }
      }
    }
  }
  for (let i = 0; i < 29; i++) {
    const p1 = ps1[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i + 1) union(j, l, p1);
      }
    }
    const even = [];
    for (let [u, v, c] of edges) {
      if (!(c & 1)) {
        even[find(u, p1)] = 1;
        even[find(v, p1)] = 1;
      }
    }
    for (let i = 0; i < n; i++) {
      if (even[find(i, p1)]) {
        flag[i] = 1;
      }
    }
  }
  let res = [];
  for (let [u, v] of querys) {
    let ans = 2;
    for (let i = 0; i < 30; i++) {
      const p = ps[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 0;
        break;
      }
    }
    if (ans !== 2) {
      res.push(ans);
      continue;
    }
    if (flag[u]) {
      res.push(1);
      continue;
    }
    for (let i = 0; i < 29; i++) {
      const p = ps1[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 1;
        break;
      }
    }
    res.push(ans);
  }
  console.log(res.join('\n'));
}

async function main(read) {
  const [n, m] = (await read()).split(' ').map(Number);
  const edges = [],
        querys = [];
  let t = m;
  while (t--) {
    const [u, v, w] = (await read()).split(' ').map(Number);
    edges.push([u - 1, v - 1, w]);
  }
  t = Number(await read());
  while (t--) {
    const [u, v] = (await read()).split(' ').map(Number);
    querys.push([u - 1, v - 1]);
  }
  solve(n, m, edges, querys);
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  async function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(n, m, edges, querys) {
  const ps = Array.from({
    length: 30
  }, () => [...new Array(n).keys()]),
        ps1 = Array.from({
    length: 29
  }, () => [...new Array(n).keys()]),
  flag = [];
  const find = (i, p) => {
    if (p[i] !== i) p[i] = find(p[p[i]], p);
    return p[i];
  };
  const union = (i, j, p) => {
    const ri = find(i, p),
          rj = find(j, p);
    if (ri !== rj) p[rj] = ri;
  };
  const h = new Array(n).fill(-1),
        e = [],
        ne = [],
        w = [];
  let idx = 0;
  const add = (i, j, c) => {
    e[idx] = j, w[idx] = c, ne[idx] = h[i], h[i] = idx++;
  };
  for (let [u, v, c] of edges) {
    add(u, v, c);
    add(v, u, c);
  }
  for (let i = 0; i < 30; i++) {
    const p = ps[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i) {
          union(j, l, p);
        }
      }
    }
  }
  for (let i = 0; i < 29; i++) {
    const p1 = ps1[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i + 1) union(j, l, p1);
      }
    }
    const even = [];
    for (let [u, v, c] of edges) {
      if (!(c & 1)) {
        even[find(u, p1)] = 1;
        even[find(v, p1)] = 1;
      }
    }
    for (let i = 0; i < n; i++) {
      if (even[find(i, p1)]) {
        flag[i] = 1;
      }
    }
  }
  let res = [];
  for (let [u, v] of querys) {
    let ans = 2;
    for (let i = 0; i < 30; i++) {
      const p = ps[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 0;
        break;
      }
    }
    if (ans !== 2) {
      res.push(ans);
      continue;
    }
    if (flag[u]) {
      res.push(1);
      continue;
    }
    for (let i = 0; i < 29; i++) {
      const p = ps1[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 1;
        break;
      }
    }
    res.push(ans);
  }
  console.log(res.join('\n'));
}

function main(inputs) {
  const [n, m] = inputs[0].trim().split(' ').map(Number);
  const edges = [],
        querys = [];
  let i = 1,
      t = m;
  while (t--) {
    const [u, v, w] = inputs[i++].trim().split(' ').map(Number);
    edges.push([u - 1, v - 1, w]);
  }
  t = Number(inputs[i++].trim());
  while (t--) {
    const [u, v] = inputs[i++].trim().split(' ').map(Number);
    querys.push([u - 1, v - 1]);
  }
  solve(n, m, edges, querys);
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split('\n');
main(inputs);

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, edges, querys) {
  const ps = Array.from({
    length: 30
  }, () => [...new Array(n).keys()]),
        ps1 = Array.from({
    length: 29
  }, () => [...new Array(n).keys()]),
  flag = [];
  const find = (i, p) => {
    if (p[i] !== i) p[i] = find(p[p[i]], p);
    return p[i];
  };
  const union = (i, j, p) => {
    const ri = find(i, p),
          rj = find(j, p);
    if (ri !== rj) p[rj] = ri;
  };
  const h = new Array(n).fill(-1),
        e = [],
        ne = [],
        w = [];
  let idx = 0;
  const add = (i, j, c) => {
    e[idx] = j, w[idx] = c, ne[idx] = h[i], h[i] = idx++;
  };
  for (let [u, v, c] of edges) {
    add(u, v, c);
    add(v, u, c);
  }
  for (let i = 0; i < 30; i++) {
    const p = ps[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i) {
          union(j, l, p);
        }
      }
    }
  }
  for (let i = 0; i < 29; i++) {
    const p1 = ps1[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i + 1) union(j, l, p1);
      }
    }
    const even = [];
    for (let [u, v, c] of edges) {
      if (!(c & 1)) {
        even[find(u, p1)] = 1;
        even[find(v, p1)] = 1;
      }
    }
    for (let i = 0; i < n; i++) {
      if (even[find(i, p1)]) {
        flag[i] = 1;
      }
    }
  }
  let res = [];
  for (let [u, v] of querys) {
    let ans = 2;
    for (let i = 0; i < 30; i++) {
      const p = ps[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 0;
        break;
      }
    }
    if (ans !== 2) {
      res.push(ans);
      continue;
    }
    if (flag[u]) {
      res.push(1);
      continue;
    }
    for (let i = 0; i < 29; i++) {
      const p = ps1[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 1;
        break;
      }
    }
    res.push(ans);
  }
  console.log(res.join('\n'));
}

async function main(read) {
  const [n, m] = (await read()).split(' ').map(Number);
  const edges = [],
        querys = [];
  let t = m;
  while (t--) {
    const [u, v, w] = (await read()).split(' ').map(Number);
    edges.push([u - 1, v - 1, w]);
  }
  t = Number(await read());
  while (t--) {
    const [u, v] = (await read()).split(' ').map(Number);
    querys.push([u - 1, v - 1]);
  }
  solve(n, m, edges, querys);
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
function read() {
  return new Promise(function (resolve, reject) {
    rl.on('line', line => resolve(line.trim()));
  });
}
main(read);

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(n, m, edges, querys) {
  const ps = Array.from({
    length: 30
  }, () => [...new Array(n).keys()]),
        ps1 = Array.from({
    length: 29
  }, () => [...new Array(n).keys()]),
  flag = [];
  const find = (i, p) => {
    if (p[i] !== i) p[i] = find(p[p[i]], p);
    return p[i];
  };
  const union = (i, j, p) => {
    const ri = find(i, p),
          rj = find(j, p);
    if (ri !== rj) p[rj] = ri;
  };
  const h = new Array(n).fill(-1),
        e = [],
        ne = [],
        w = [];
  let idx = 0;
  const add = (i, j, c) => {
    e[idx] = j, w[idx] = c, ne[idx] = h[i], h[i] = idx++;
  };
  for (let [u, v, c] of edges) {
    add(u, v, c);
    add(v, u, c);
  }
  for (let i = 0; i < 30; i++) {
    const p = ps[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i) {
          union(j, l, p);
        }
      }
    }
  }
  for (let i = 0; i < 29; i++) {
    const p1 = ps1[i];
    for (let j = 0; j < n; j++) {
      for (let k = h[j]; k !== -1; k = ne[k]) {
        const l = e[k];
        if (l < j) continue;
        if (w[k] & 1 << i + 1) union(j, l, p1);
      }
    }
    for (let [u, v, c] of edges) {
      if (!(c & 1)) {
        flag[find(u, p1)] = 1;
        flag[find(v, p1)] = 1;
      }
    }
  }
  let res = [];
  for (let [u, v] of querys) {
    let ans = 2;
    for (let i = 0; i < 30; i++) {
      const p = ps[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 0;
        break;
      }
    }
    if (ans !== 2) {
      res.push(ans);
      continue;
    }
    if (flag[u]) {
      res.push(1);
      continue;
    }
    for (let i = 0; i < 29; i++) {
      const p = ps1[i];
      const ru = find(u, p),
            rv = find(v, p);
      if (ru === rv) {
        ans = 1;
        break;
      }
    }
    res.push(ans);
  }
  console.log(res.join('\n'));
}

function main(inputs) {
  const [n, m] = inputs[0].trim().split(' ').map(Number);
  const edges = [],
        querys = [];
  let i = 1,
      t = m;
  while (t--) {
    const [u, v, w] = inputs[i++].trim().split(' ').map(Number);
    edges.push([u - 1, v - 1, w]);
  }
  t = Number(inputs[i++].trim());
  while (t--) {
    const [u, v] = inputs[i++].trim().split(' ').map(Number);
    querys.push([u - 1, v - 1]);
  }
  solve(n, m, edges, querys);
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split('\n');
main(inputs);


A permutation is a sequence of $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ are permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ are not.Polycarp was presented with a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. However, when Polycarp came home, he noticed that in his pocket, the permutation $$$p$$$ had turned into an array $$$q$$$ according to the following rule:   $$$q_i = \max(p_1, p_2, \ldots, p_i)$$$. Now Polycarp wondered what lexicographically minimal and lexicographically maximal permutations could be presented to him.An array $$$a$$$ of length $$$n$$$ is lexicographically smaller than an array $$$b$$$ of length $$$n$$$ if there is an index $$$i$$$ ($$$1 \le i \le n$$$) such that the first $$$i-1$$$ elements of arrays $$$a$$$ and $$$b$$$ are the same, and the $$$i$$$-th element of the array $$$a$$$ is less than the $$$i$$$-th element of the array $$$b$$$. For example, the array $$$a=[1, 3, 2, 3]$$$ is lexicographically smaller than the array $$$b=[1, 3, 4, 2]$$$.For example, if $$$n=7$$$ and $$$p=[3, 2, 4, 1, 7, 5, 6]$$$, then $$$q=[3, 3, 4, 4, 7, 7, 7]$$$ and the following permutations could have been as $$$p$$$ initially:   $$$[3, 1, 4, 2, 7, 5, 6]$$$ (lexicographically minimal permutation);  $$$[3, 1, 4, 2, 7, 6, 5]$$$;  $$$[3, 2, 4, 1, 7, 5, 6]$$$;  $$$[3, 2, 4, 1, 7, 6, 5]$$$ (lexicographically maximum permutation). For a given array $$$q$$$, find the lexicographically minimal and lexicographically maximal permutations that could have been originally presented to Polycarp.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$q_1, q_2, \ldots, q_n$$$ ($$$1 \le q_i \le n$$$). It is guaranteed that the array $$$q$$$ was obtained by applying the rule from the statement to some permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output two lines:    on the first line output $$$n$$$ integers — lexicographically minimal permutation that could have been originally presented to Polycarp;  on the second line print $$$n$$$ integers — lexicographically maximal permutation that could have been originally presented to Polycarp;

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

// Make a Snippet for the code above this and then write your logic in main();
var mod = 998244353n
var maxN = 10e6 + 1

function main() {
  var x = parseInt(readline())
  //
  Array(parseInt(x)).fill(1).map((t, iii) => {
    var n = parseInt(readline())
    var a = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    });

    var fixed = new Array(n).fill(false)
    fixed[0] = true
    for (let i = 1; i < n; i++) {
      if(a[i]!==a[i-1]) fixed[i] = true

    }

    var set1 = new RBTree(function(a, b) { return a - b; })
    var set2 = new RBTree(function(a, b) { return a - b; })
    var ans1 = new Array(n).fill(0)
    var ans2 = new Array(n).fill(0)
    for (let i = 1; i <= n; i++) {
      set1.insert(i)
      set2.insert(i)
    }

    for (let i = 0; i < n; i++) {
      if(fixed[i]){
        ans1[i] = a[i]
        ans2[i] = a[i]
        set1.remove(a[i])
        set2.remove(a[i])
      }
    }

    for (let i = 0; i < n; i++) {
      if(!fixed[i]){
        ans1[i] = set1.min()
        set1.remove(ans1[i])
        ans2[i] = set2.upperBound(a[i]).prev()
        set2.remove(ans2[i])
        // set1.remove(ans1[i])
      }
    }

    console.log(ans1.join(' '))
    console.log(ans2.join(' '))
  })
}

// start binary search tree

function TreeBase() {}

// removes all nodes from the tree
TreeBase.prototype.clear = function() {
  this._root = null;
  this.size = 0;
};

// returns node data if found, null otherwise
TreeBase.prototype.find = function(data) {
  var res = this._root;

  while(res !== null) {
    var c = this._comparator(data, res.data);
    if(c === 0) {
      return res.data;
    }
    else {
      res = res.get_child(c > 0);
    }
  }

  return null;
};

// returns iterator to node if found, null otherwise
TreeBase.prototype.findIter = function(data) {
  var res = this._root;
  var iter = this.iterator();

  while(res !== null) {
    var c = this._comparator(data, res.data);
    if(c === 0) {
      iter._cursor = res;
      return iter;
    }
    else {
      iter._ancestors.push(res);
      res = res.get_child(c > 0);
    }
  }

  return null;
};

// Returns an iterator to the tree node at or immediately after the item
TreeBase.prototype.lowerBound = function(item) {
  var cur = this._root;
  var iter = this.iterator();
  var cmp = this._comparator;

  while(cur !== null) {
    var c = cmp(item, cur.data);
    if(c === 0) {
      iter._cursor = cur;
      return iter;
    }
    iter._ancestors.push(cur);
    cur = cur.get_child(c > 0);
  }

  for(var i=iter._ancestors.length - 1; i >= 0; --i) {
    cur = iter._ancestors[i];
    if(cmp(item, cur.data) < 0) {
      iter._cursor = cur;
      iter._ancestors.length = i;
      return iter;
    }
  }

  iter._ancestors.length = 0;
  return iter;
};

// Returns an iterator to the tree node immediately after the item
TreeBase.prototype.upperBound = function(item) {
  var iter = this.lowerBound(item);
  var cmp = this._comparator;

  while(iter.data() !== null && cmp(iter.data(), item) === 0) {
    iter.next();
  }

  return iter;
};

// returns null if tree is empty
TreeBase.prototype.min = function() {
  var res = this._root;
  if(res === null) {
    return null;
  }

  while(res.left !== null) {
    res = res.left;
  }

  return res.data;
};

// returns null if tree is empty
TreeBase.prototype.max = function() {
  var res = this._root;
  if(res === null) {
    return null;
  }

  while(res.right !== null) {
    res = res.right;
  }

  return res.data;
};

// returns a null iterator
// call next() or prev() to point to an element
TreeBase.prototype.iterator = function() {
  return new Iterator(this);
};

// calls cb on each node's data, in order
TreeBase.prototype.each = function(cb) {
  var it=this.iterator(), data;
  while((data = it.next()) !== null) {
    if(cb(data) === false) {
      return;
    }
  }
};

// calls cb on each node's data, in reverse order
TreeBase.prototype.reach = function(cb) {
  var it=this.iterator(), data;
  while((data = it.prev()) !== null) {
    if(cb(data) === false) {
      return;
    }
  }
};

function Iterator(tree) {
  this._tree = tree;
  this._ancestors = [];
  this._cursor = null;
}

Iterator.prototype.data = function() {
  return this._cursor !== null ? this._cursor.data : null;
};

// if null-iterator, returns first node
// otherwise, returns next node
Iterator.prototype.next = function() {
  if(this._cursor === null) {
    var root = this._tree._root;
    if(root !== null) {
      this._minNode(root);
    }
  }
  else {
    if(this._cursor.right === null) {
      // no greater node in subtree, go up to parent
      // if coming from a right child, continue up the stack
      var save;
      do {
        save = this._cursor;
        if(this._ancestors.length) {
          this._cursor = this._ancestors.pop();
        }
        else {
          this._cursor = null;
          break;
        }
      } while(this._cursor.right === save);
    }
    else {
      // get the next node from the subtree
      this._ancestors.push(this._cursor);
      this._minNode(this._cursor.right);
    }
  }
  return this._cursor !== null ? this._cursor.data : null;
};

// if null-iterator, returns last node
// otherwise, returns previous node
Iterator.prototype.prev = function() {
  if(this._cursor === null) {
    var root = this._tree._root;
    if(root !== null) {
      this._maxNode(root);
    }
  }
  else {
    if(this._cursor.left === null) {
      var save;
      do {
        save = this._cursor;
        if(this._ancestors.length) {
          this._cursor = this._ancestors.pop();
        }
        else {
          this._cursor = null;
          break;
        }
      } while(this._cursor.left === save);
    }
    else {
      this._ancestors.push(this._cursor);
      this._maxNode(this._cursor.left);
    }
  }
  return this._cursor !== null ? this._cursor.data : null;
};

Iterator.prototype._minNode = function(start) {
  while(start.left !== null) {
    this._ancestors.push(start);
    start = start.left;
  }
  this._cursor = start;
};

Iterator.prototype._maxNode = function(start) {
  while(start.right !== null) {
    this._ancestors.push(start);
    start = start.right;
  }
  this._cursor = start;
};

function Node(data) {
  this.data = data;
  this.left = null;
  this.right = null;
}

Node.prototype.get_child = function(dir) {
  return dir ? this.right : this.left;
};

Node.prototype.set_child = function(dir, val) {
  if(dir) {
    this.right = val;
  }
  else {
    this.left = val;
  }
};

function Node(data) {
  this.data = data;
  this.left = null;
  this.right = null;
  this.red = true;
}

Node.prototype.get_child = function(dir) {
  return dir ? this.right : this.left;
};

Node.prototype.set_child = function(dir, val) {
  if(dir) {
    this.right = val;
  }
  else {
    this.left = val;
  }
};

function RBTree(comparator) {
  this._root = null;
  this._comparator = comparator;
  this.size = 0;
}

RBTree.prototype = new TreeBase();

// returns true if inserted, false if duplicate
RBTree.prototype.insert = function(data) {
  var ret = false;

  if(this._root === null) {
    // empty tree
    this._root = new Node(data);
    ret = true;
    this.size++;
  }
  else {
    var head = new Node(undefined); // fake tree root

    var dir = 0;
    var last = 0;

    // setup
    var gp = null; // grandparent
    var ggp = head; // grand-grand-parent
    var p = null; // parent
    var node = this._root;
    ggp.right = this._root;

    // search down
    while(true) {
      if(node === null) {
        // insert new node at the bottom
        node = new Node(data);
        p.set_child(dir, node);
        ret = true;
        this.size++;
      }
      else if(is_red(node.left) && is_red(node.right)) {
        // color flip
        node.red = true;
        node.left.red = false;
        node.right.red = false;
      }

      // fix red violation
      if(is_red(node) && is_red(p)) {
        var dir2 = ggp.right === gp;

        if(node === p.get_child(last)) {
          ggp.set_child(dir2, single_rotate(gp, !last));
        }
        else {
          ggp.set_child(dir2, double_rotate(gp, !last));
        }
      }

      var cmp = this._comparator(node.data, data);

      // stop if found
      if(cmp === 0) {
        break;
      }

      last = dir;
      dir = cmp < 0;

      // update helpers
      if(gp !== null) {
        ggp = gp;
      }
      gp = p;
      p = node;
      node = node.get_child(dir);
    }

    // update root
    this._root = head.right;
  }

  // make root black
  this._root.red = false;

  return ret;
};

// returns true if removed, false if not found
RBTree.prototype.remove = function(data) {
  if(this._root === null) {
    return false;
  }

  var head = new Node(undefined); // fake tree root
  var node = head;
  node.right = this._root;
  var p = null; // parent
  var gp = null; // grand parent
  var found = null; // found item
  var dir = 1;

  while(node.get_child(dir) !== null) {
    var last = dir;

    // update helpers
    gp = p;
    p = node;
    node = node.get_child(dir);

    var cmp = this._comparator(data, node.data);

    dir = cmp > 0;

    // save found node
    if(cmp === 0) {
      found = node;
    }

    // push the red node down
    if(!is_red(node) && !is_red(node.get_child(dir))) {
      if(is_red(node.get_child(!dir))) {
        var sr = single_rotate(node, dir);
        p.set_child(last, sr);
        p = sr;
      }
      else if(!is_red(node.get_child(!dir))) {
        var sibling = p.get_child(!last);
        if(sibling !== null) {
          if(!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) {
            // color flip
            p.red = false;
            sibling.red = true;
            node.red = true;
          }
          else {
            var dir2 = gp.right === p;

            if(is_red(sibling.get_child(last))) {
              gp.set_child(dir2, double_rotate(p, last));
            }
            else if(is_red(sibling.get_child(!last))) {
              gp.set_child(dir2, single_rotate(p, last));
            }

            // ensure correct coloring
            var gpc = gp.get_child(dir2);
            gpc.red = true;
            node.red = true;
            gpc.left.red = false;
            gpc.right.red = false;
          }
        }
      }
    }
  }

  // replace and remove if found
  if(found !== null) {
    found.data = node.data;
    p.set_child(p.right === node, node.get_child(node.left === null));
    this.size--;
  }

  // update root and make it black
  this._root = head.right;
  if(this._root !== null) {
    this._root.red = false;
  }

  return found !== null;
};

function is_red(node) {
  return node !== null && node.red;
}

function single_rotate(root, dir) {
  var save = root.get_child(!dir);

  root.set_child(!dir, save.get_child(dir));
  save.set_child(dir, root);

  root.red = true;
  save.red = false;

  return save;
}

function double_rotate(root, dir) {
  root.set_child(!dir, single_rotate(root.get_child(!dir), !dir));
  return single_rotate(root, dir);
}

//end binary search tree

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		let n = rn();
		let q = rna();

		let mnavl = [], mxavl = [];
		let ansmn = [], ansmx = [];
		let mx = 0;
		for (let i = 0, k = 0; i < n; i++) {
			if (q[i] > mx) {
				ansmn.push(q[i]);
				ansmx.push(q[i]);
				mx++;
				while (mx < q[i]) {
					mnavl.push(mx);
					mxavl.push(mx);
					mx++;
				}
			} else {
				ansmn.push(mnavl[k++]);
				ansmx.push(mxavl.pop());
			}
		}
		console.log(ansmn.join(' '));
		console.log(ansmx.join(' '));
	}
}

const solve = a => {
  const res = [];
  const cache = new Set();
  for (let i = 0; i < a.length; i++) {
    res.push(null);
    if (i === 0 || a[i] !== a[i - 1]) {
      res[i] = a[i];
      cache.add(res[i]);
    }
  }

  const min = [...res];
  let count = 1;
  for (let i = 0; i < a.length; i++) {
    if (res[i] !== null) continue;
    while (cache.has(count)) count++;
    min[i] = count;
    count++;
  }

  const max = [...res];
  const stack = [];
  for (let i = 0; i < a.length; i++) {
    if (i === 0) {
      for (let j = 1; j < res[i]; j++) stack.push(j);
    } else if (a[i] !== a[i - 1]) {
      for (let j = a[i - 1] + 1; j < a[i]; j++) stack.push(j);
    }

    if (res[i] !== null) continue;
    max[i] = stack.pop();
  }

  return [min, max];
};

const main = () => {
  let t = readInt();
  while (t--) {
    const n = readInt();
    const a = readListInt();
    const [min, max] = solve(a);
    console.log(min.join(" "));
    console.log(max.join(" "));
  }
};

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
  inputString += inputStdin;
});

process.stdin.on("end", () => {
  inputString = inputString
    .trim()
    .split("\n")
    .map(string => string.trim());
  main();
});

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(s));
};

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
let input = [];
rl.on('line', line => {
    input.push(line);
})
rl.on('close', line => {
    var t = Number(input[0]);
    var j = 1;
    for (let i = 0; i < t; i++) {
        var len = Number(input[j]);
        j++;
        var arr = input[j].split(" ").map((i) => {
            return Number(i);
        })
        j++;
        function findMin(arr, len) {
            var result = new Array(len).fill(0);
            result[0] = arr[0];
            var set = new Set();
            set.add(arr[0]);
            for (var i = 1; i < arr.length; i++) {
                if (arr[i] !== arr[i - 1]) {
                    result[i] = arr[i];
                    set.add(arr[i]);
                }
            }
            var count = 1;
            for (var i = 0; i < result.length; i++) {
                if (result[i] === 0) {
                    result[i] = count;
                    count++;
                }
                while (set.has(count)) {
                    count++;
                }
            }
            return result.join(" ");
        }
        function findMax(arr, len) {
            var result = new Array(len).fill(0);
            result[0] = arr[0];
            var set = new Set();
            set.add(arr[0]);
            for (var i = 1; i < arr.length; i++) {
                if (arr[i] !== arr[i - 1]) {
                    result[i] = arr[i];
                    set.add(arr[i]);
                }
            }
            var list = [];
            var count = 1;
            for (var i = 0; i < result.length; i++) {
                if (result[i] !== 0) {
                    while (count < result[i]) {
                        if (!set.has(count)) {
                            list.push(count);
                        }
                        count++;
                    }
                    count++;
                } else {
                    result[i] = list.pop();
                }
            }
            return result.join(" ");
        }
        console.log(findMin(arr, len));
        console.log(findMax(arr, len));
    }
})

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

// Make a Snippet for the code above this and then write your logic in main();
var mod = 998244353n
var maxN = 10e6 + 1

function main() {
  var x = parseInt(readline())
  //
  Array(parseInt(x)).fill(1).map((t, iii) => {
    var n = parseInt(readline())
    var a = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    });

    var answer = new Array(n).fill(0)
    var used = new Array(n).fill(false)
    var count = 1
    var met = 1
    answer[0] = a[0];
    used[a[0]] = true
    for (let i = 1; i < n; i++) {
      if (a[i] !== a[i - 1]) {
        answer[i] = a[i]
        used[a[i]] = true
      }
    }
    var count = 1
    for (let i = 0; i < n; i++) {
      if (answer[i] === 0) {
        while (used[count]) count++
        answer[i] = count
        used[count] = true
      }
    }
    console.log(answer.join(' '))

    answer = new Array(n).fill(0)
    var used = new Array(n).fill(false)
    var count = 1
    var met = 1
    answer[0] = a[0];
    used[a[0]] = true
    for (let i = 1; i < n; i++) {
      if (a[i] !== a[i - 1]) {
        answer[i] = a[i]
        used[a[i]] = true
      }
    }
    var lower = 0
    var count = a[0]-1
    var prev = a[0]-1
    var max = a[0]
    for (let i = 0; i < n; i++) {
      if (answer[i] === 0) {
        answer[i] = count
        count--
      } else {
        // console.log(count, lower)
        if(count === lower){
          lower = prev
          count = answer[i]-1
        }
        prev = answer[i]
      }
    }
    console.log(answer.join(' '))

  })
}


To celebrate your birthday you have prepared a festive table! Now you want to seat as many guests as possible.The table can be represented as a rectangle with height $$$h$$$ and width $$$w$$$, divided into $$$h \times w$$$ cells. Let $$$(i, j)$$$ denote the cell in the $$$i$$$-th row and the $$$j$$$-th column of the rectangle ($$$1 \le i \le h$$$; $$$1 \le j \le w$$$).Into each cell of the table you can either put a plate or keep it empty.As each guest has to be seated next to their plate, you can only put plates on the edge of the table — into the first or the last row of the rectangle, or into the first or the last column. Formally, for each cell $$$(i, j)$$$ you put a plate into, at least one of the following conditions must be satisfied: $$$i = 1$$$, $$$i = h$$$, $$$j = 1$$$, $$$j = w$$$.To make the guests comfortable, no two plates must be put into cells that have a common side or corner. In other words, if cell $$$(i, j)$$$ contains a plate, you can't put plates into cells $$$(i - 1, j)$$$, $$$(i, j - 1)$$$, $$$(i + 1, j)$$$, $$$(i, j + 1)$$$, $$$(i - 1, j - 1)$$$, $$$(i - 1, j + 1)$$$, $$$(i + 1, j - 1)$$$, $$$(i + 1, j + 1)$$$.Put as many plates on the table as possible without violating the rules above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each of the following $$$t$$$ lines describes one test case and contains two integers $$$h$$$ and $$$w$$$ ($$$3 \le h, w \le 20$$$) — the height and the width of the table.

For each test case, print $$$h$$$ lines containing $$$w$$$ characters each. Character $$$j$$$ in line $$$i$$$ must be equal to $$$1$$$ if you are putting a plate into cell $$$(i, j)$$$, and $$$0$$$ otherwise. If there are multiple answers, print any. All plates must be put on the edge of the table. No two plates can be put into cells that have a common side or corner. The number of plates put on the table under these conditions must be as large as possible. You are allowed to print additional empty lines.

NoteFor the first test case, example output contains the only way to put $$$6$$$ plates on the table.For the second test case, there are many ways to put $$$4$$$ plates on the table, example output contains one of them.Putting more than $$$6$$$ plates in the first test case or more than $$$4$$$ plates in the second test case is impossible.

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var dy = [-1,-1,-1,0,1,1,1,0];
	var dx = [-1,0,1,1,1,0,-1,-1];
	while(hasNext()){
		var H = nextInt();
		var W = nextInt();
		var list = new Array(H);
		for(var i = 0; i < H; i++){
			list[i] = new Array(W);
		}
		for(var i = 0; i < H; i++){
			if(list[i][0] == null){
				list[i][0] = "1";
				for(var j = 0; j < dy.length; j++){
					var y = i + dy[j];
					var x = 0 + dx[j];
					if(y >= 0 && y < H && x >= 0 && x < W){
						list[y][x] = "0";
					}
				}
			}
			if(list[i][W - 1] == null){
				list[i][W - 1] = "1";
				for(var j = 0; j < dy.length; j++){
					var y = i + dy[j];
					var x = (W - 1) + dx[j];
					if(y >= 0 && y < H && x >= 0 && x < W){
						list[y][x] = "0";
					}
				}
			}
		}
		myerr(list);
		for(var i = 0; i < W; i++){
			if(list[0][i] == null){
				list[0][i] = "1";
				for(var j = 0; j < dy.length; j++){
					var y = 0 + dy[j];
					var x = i + dx[j];
					if(y >= 0 && y < H && x >= 0 && x < W){
						list[y][x] = "0";
					}
				}
			}
			if(list[H - 1][i] == null){
				list[H - 1][i] = "1";
				for(var j = 0; j < dy.length; j++){
					var y = (H - 1) + dy[j];
					var x = i + dx[j];
					if(y >= 0 && y < H && x >= 0 && x < W){
						list[y][x] = "0";
					}
				}
			}
		}
		for(var i = 0; i < H; i++){
			for(var j = 0; j < W; j++){
				if(list[i][j] == null){
					list[i][j] = "0";
				}
			}
		}
		for(var i = 0; i < H; i++){
			myout(myconv(list[i], 0));
		}
		myout("");
	}
}

let i = '';

function insertOne(x, y, arr) {
    let willInsert = true;

    if (arr[x-1] !== undefined && arr[x-1][y-1] !== undefined && arr[x-1][y-1] === 1) {
        willInsert = false;
    }
    if (arr[x] !== undefined && arr[x][y-1] !== undefined && arr[x][y-1] === 1) {
        willInsert = false;
    }
    if (arr[x+1] !== undefined && arr[x+1][y-1] !== undefined && arr[x+1][y-1] === 1) {
        willInsert = false;
    }

    if (arr[x-1] !== undefined && arr[x-1][y] !== undefined && arr[x-1][y] === 1) {
        willInsert = false;
    }
    if (arr[x] !== undefined && arr[x][y] !== undefined && arr[x][y] === 1) {
        willInsert = false;
    }
    if (arr[x+1] !== undefined && arr[x+1][y] !== undefined && arr[x+1][y] === 1) {
        willInsert = false;
    }

    if (arr[x-1] !== undefined && arr[x-1][y+1] !== undefined && arr[x-1][y+1] === 1) {
        willInsert = false;
    }
    if (arr[x] !== undefined && arr[x][y+1] !== undefined && arr[x][y+1] === 1) {
        willInsert = false;
    }
    if (arr[x+1] !== undefined && arr[x+1][y+1] !== undefined && arr[x+1][y+1] === 1) {
        willInsert = false;
    }

    if (willInsert) {
        return 1;
    }
    return 0;
}

function createArrayWithZeros(width, height) {
    const arr = [];
    for(let i = 0; i < height; i++) {
        arr[i] = [];
        for(let j = 0; j < width; j++) {
            arr[i][j] = 0;
        }
    }
    return arr;
}

function printArr(width, height, arr) {
    for(let i = 0; i < height; i++) {
        let string = '';
        for(let j = 0; j < width; j++) {
            string += arr[i][j];
        }
        console.log(string);
    }
    console.log('\n');
}

process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    const size = lines[0];
    for(let j = 1; j <= size; j++) {
        let num = lines[j];
        const sizes = num.split(' ');
        const height = sizes[0];
        const width = sizes[1];
        const table = createArrayWithZeros(width, height);

        for(let x = 0; x < height; x++) {
            for(let y = 0; y < width; y++) {
                if (x === 0 || y === 0 || x === height-1 || y === width-1) {
                  table[x][y] = insertOne(x, y, table);
                }
            }
        }

        printArr(width, height, table);
    }
})

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function main() {
    const n = Number(readline());

    for(let i = 0; i < n; i ++) {
        const [h, w] = readline().split(" ").map(Number);

        let result = "";

        for(let j = 0; j < h; j++){
            for(let k = 0; k < w; k++){
                if(j == 0 || j == h-1) {
                    if(k % 2 == 0) result += "1";
                    else result += "0";
                } else if (j % 2 != 0 || j == 1 || j == h-2) {
                    result += "0";
                } else if (k == 0 || k == w-1) {
                    result += "1";
                } else {
                    result += "0";
                }
            }
            console.log(result);
            result = "";
        }

        console.log(" ");
    }
}

let input = '';
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => {
  const {EOL} = require('os');
  const lines = input.split(EOL);
  const count = parseInt(lines[0]);
  for (let i = 1; i <= count; ++i) {
    solve(lines[i]);
  }
});

function solve(question) {
  let [, h, w] = question.match(/(\d+) (\d+)/);
  h = parseInt(h);
  w = parseInt(w);

  for (let y = 0; y < h; ++y) {
    line = '';
    if (h % 2 === 0 && y === h - 2) {
      for (let x = 0; x < w; ++x) {
        line += '0';
      }
    } else if (y % 2 === 0 || y === h - 1) {
      for (let x = 0; x < w; ++x) {
        if (w % 2 === 0 && x === w - 2) {
          line += '0';
        } else if ((x === 0 || x === w - 1 || y === 0 || y === h - 1) && (x % 2 === 0 || x === w - 1)) {
          line += '1';
        } else {
          line += '0';
        }
      }
    } else {
      for (let x = 0; x < w; ++x) {
        line += '0';
      }
    }
    console.log(line);
  }
  console.log();
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var dy = [-1,-1,-1,0,1,1,1,0];
	var dx = [-1,0,1,1,1,0,-1,-1];
	while(hasNext()){
		var H = nextInt();
		var W = nextInt();
		var list = new Array(H);
		for(var i = 0; i < H; i++){
			list[i] = new Array(W);
		}
		for(var i = 0; i < H; i++){
			if(list[i][0] == null){
				list[i][0] = "1";
				for(var j = 0; j < dy.length; j++){
					var y = i + dy[j];
					var x = 0 + dx[j];
					if(y >= 0 && y < H && x >= 0 && x < W){
						list[y][x] = "0";
					}
				}
			}
			if(list[i][W - 1] == null){
				list[i][W - 1] = "1";
				for(var j = 0; j < dy.length; j++){
					var y = i + dy[j];
					var x = (W - 1) + dx[j];
					if(y >= 0 && y < H && x >= 0 && x < W){
						list[y][x] = "0";
					}
				}
			}
		}
		for(var i = 0; i < W; i++){
			if(list[0][i] == null){
				list[0][i] = "1";
				for(var j = 0; j < dy.length; j++){
					var y = 0 + dy[j];
					var x = j + dx[j];
					if(y >= 0 && y < H && x >= 0 && x < W){
						list[y][x] = "0";
					}
				}
			}
			if(list[H - 1][i] == null){
				list[H - 1][i] = "1";
				for(var j = 0; j < dy.length; j++){
					var y = (H - 1) + dy[j];
					var x = j + dx[j];
					if(y >= 0 && y < H && x >= 0 && x < W){
						list[y][x] = "0";
					}
				}
			}
		}
		for(var i = 0; i < H; i++){
			for(var j = 0; j < W; j++){
				if(list[i][j] == null){
					list[i][j] = "0";
				}
			}
		}
		for(var i = 0; i < H; i++){
			myout(myconv(list[i], 0));
		}
		myout("");
	}
}

let i = '';

function insertOne(x, y, arr) {
    let willInsert = true;

    if (arr[x-1] !== undefined && arr[x-1][y-1] !== undefined && arr[x-1][y-1] === 1) {
        willInsert = false;
    }
    if (arr[x] !== undefined && arr[x][y-1] !== undefined && arr[x][y-1] === 1) {
        willInsert = false;
    }
    if (arr[x+1] !== undefined && arr[x+1][y-1] !== undefined && arr[x+1][y-1] === 1) {
        willInsert = false;
    }

    if (arr[x-1] !== undefined && arr[x-1][y] !== undefined && arr[x-1][y] === 1) {
        willInsert = false;
    }
    if (arr[x] !== undefined && arr[x][y] !== undefined && arr[x][y] === 1) {
        willInsert = false;
    }
    if (arr[x+1] !== undefined && arr[x+1][y] !== undefined && arr[x+1][y] === 1) {
        willInsert = false;
    }

    if (arr[x-1] !== undefined && arr[x-1][y+1] !== undefined && arr[x-1][y+1] === 1) {
        willInsert = false;
    }
    if (arr[x] !== undefined && arr[x][y+1] !== undefined && arr[x][y+1] === 1) {
        willInsert = false;
    }
    if (arr[x+1] !== undefined && arr[x+1][y+1] !== undefined && arr[x+1][y+1] === 1) {
        willInsert = false;
    }

    if (willInsert) {
        return 1;
    }
    return 0;
}

function createArrayWithZeros(width, height) {
    const arr = [];
    for(let i = 0; i < height; i++) {
        arr[i] = [];
        for(let j = 0; j < width; j++) {
            arr[i][j] = 0;
        }
    }
    return arr;
}
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    const size = lines[0];
    for(let j = 1; j <= size; j++) {
        let num = lines[j];
        const sizes = num.split(' ');
        const height = sizes[0];
        const width = sizes[1];
        const table = createArrayWithZeros(width, height);

        for(let x = 0; x < height; x++) {
            for(let y = 0; y < width; y++) {
                if (x === 0 || y === 0 || x === height-1 || y === width-1) {
                  table[x][y] = insertOne(x, y, table);
                }
            }
        }

        console.log(table);
    }
})