'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');
    }
});


'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');
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 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);


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 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

'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(' '))

  })
}


//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);
    }
})