"use strict";

// start below this line
var line = readline().split(" ");
var n = parseInt(line[0], 10);
var m = parseInt(line[1], 10);
var bigK = parseInt(line[2], 10);

if (bigK % 2 === 1) {
  for (var _ = 0; _ < n; ++_) {
    print(new Array(m).fill(-1).join(" "));
  }
} else {
  var a = new Array(n);

  for (var _2 = 0; _2 < n; ++_2) {
    a[_2] = readline()
      .split(" ")
      .map(function (v) {
        return parseInt(v, 10);
      });
  }

  var b = new Array(n - 1);

  for (var _3 = 0; _3 < n - 1; ++_3) {
    b[_3] = readline()
      .split(" ")
      .map(function (v) {
        return parseInt(v, 10);
      });
  }

  var x = new Array(n).fill(0).map(function () {
    return new Array(m).fill(0);
  });
  bigK >>= 1;

  for (var k = 1; k <= bigK; ++k) {
    var y = new Array(n).fill(0).map(function () {
      return new Array(m).fill(1e8);
    });

    for (var i = 0; i < n; ++i) {
      for (var j = 0; j < m; ++j) {
        if (i > 0) {
          y[i][j] = x[i - 1][j] + 2 * b[i - 1][j];
        }

        if (i < n - 1) {
          y[i][j] = Math.min(y[i][j], x[i + 1][j] + 2 * b[i][j]);
        }

        if (j > 0) {
          y[i][j] = Math.min(y[i][j], x[i][j - 1] + 2 * a[i][j - 1]);
        }

        if (j < m - 1) {
          y[i][j] = Math.min(y[i][j], x[i][j + 1] + 2 * a[i][j]);
        }
      }
    }

    x = y;
  }

  for (var _i = 0; _i < n; ++_i) {
    print(x[_i].join(" "));
  }
}

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    writeArray(arr) {
        arr.forEach((a) => {
            this.write(a);
        });
        this.writeLine('');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
function make2dArray(a, b, fill) {
    return Array.from({ length: a }).map(() => Array.from({ length: b }).map(() => fill));
}
//////////// LIBS
const io = new IO();
function solve() { }
function main() {
    try {
        let n = io.nextNum();
        let m = io.nextNum();
        let k = io.nextNum();
        let rightCost = [];
        let downCost = [];
        for (let i = 0; i < n; i++) {
            rightCost.push([]);
            for (let j = 0; j < m - 1; j++) {
                rightCost[i][j] = io.nextNum();
            }
        }
        for (let i = 0; i < n - 1; i++) {
            downCost.push([]);
            for (let j = 0; j < m; j++) {
                downCost[i][j] = io.nextNum();
            }
        }
        if (k % 2 === 1) {
            let arr = Array.from({ length: m }).fill(-1);
            for (let i = 0; i < n; i++) {
                io.writeArray(arr);
            }
            io.flush();
            return;
        }
        let dp = [];
        const printStep = (step, mul = 1) => {
            for (let i = 0; i < n; i++) {
                for (let j = 0; j < m; j++) {
                    io.write(dp[i][j][step] * mul);
                }
                io.writeLine('');
            }
            io.writeLine('');
        };
        const getXCost = (i, j) => {
            var _a, _b;
            return (_b = (_a = rightCost[i]) === null || _a === void 0 ? void 0 : _a[j]) !== null && _b !== void 0 ? _b : Infinity;
        };
        const getYCost = (i, j) => {
            var _a, _b;
            return (_b = (_a = downCost[i]) === null || _a === void 0 ? void 0 : _a[j]) !== null && _b !== void 0 ? _b : Infinity;
        };
        // console.log({ rightCost, downCost });
        for (let i = 0; i < n; i++) {
            dp[i] = [];
            for (let j = 0; j < m; j++) {
                dp[i][j] = [];
                dp[i][j][1] = Math.min(getXCost(i, j), getXCost(i, j - 1), getYCost(i, j), getYCost(i - 1, j));
                // console.log({
                //   i,
                //   j,
                //   right: getXCost(i, j),
                //   left: getXCost(i - 1, j),
                //   down: getYCost(i, j),
                //   up: getYCost(i, j - 1),
                //   min: dp[i][j][1],
                // });
            }
        }
        const getDp = (i, j, l) => {
            var _a, _b, _c;
            return (_c = (_b = (_a = dp[i]) === null || _a === void 0 ? void 0 : _a[j]) === null || _b === void 0 ? void 0 : _b[l]) !== null && _c !== void 0 ? _c : Infinity;
        };
        // printStep(1);
        let target = k / 2;
        // console.log(dp);
        for (let l = 2; l <= target; l++) {
            for (let i = 0; i < n; i++) {
                for (let j = 0; j < m; j++) {
                    dp[i][j][l] = Math.min(getDp(i, j - 1, l - 1) + getXCost(i, j - 1), getDp(i, j + 1, l - 1) + getXCost(i, j), getDp(i - 1, j, l - 1) + getYCost(i - 1, j), getDp(i + 1, j, l - 1) + getYCost(i, j));
                }
            }
        }
        // for (let j = 0; j < m; j++) {
        //   for (let i = 0; i < n; i++) {
        //     io.write(dp[i][j][2]);
        //   }
        //   io.writeLine('');
        // }
        // io.writeLine('');
        printStep(target, 2);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    writeArray(arr) {
        arr.forEach((a) => {
            this.write(a);
        });
        this.writeLine('');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
function make2dArray(a, b, fill) {
    return Array.from({ length: a }).map(() => Array.from({ length: b }).map(() => fill));
}
//////////// LIBS
const io = new IO();
function solve() { }
function main() {
    try {
        let n = io.nextNum();
        let m = io.nextNum();
        let k = io.nextNum();
        let rightCost = [];
        let downCost = [];
        for (let i = 0; i < n; i++) {
            rightCost.push([]);
            for (let j = 0; j < m - 1; j++) {
                rightCost[i][j] = io.nextNum();
            }
        }
        for (let i = 0; i < n - 1; i++) {
            downCost.push([]);
            for (let j = 0; j < m; j++) {
                downCost[i][j] = io.nextNum();
            }
        }
        if (k % 2 === 1) {
            let arr = Array.from({ length: m }).fill(-1);
            for (let i = 0; i < n; i++) {
                io.writeArray(arr);
            }
            io.flush();
            return;
        }
        let dp = [];
        const printStep = (step, mul = 1) => {
            for (let i = 0; i < n; i++) {
                for (let j = 0; j < m; j++) {
                    io.write(dp[i][j][step] * mul);
                }
                io.writeLine('');
            }
            io.writeLine('');
        };
        const getXCost = (i, j) => {
            if (!rightCost[i]) {
                return Infinity;
            }
            return rightCost[i][j] || Infinity;
        };
        const getYCost = (i, j) => {
            if (!downCost[i]) {
                return Infinity;
            }
            return downCost[i][j] || Infinity;
        };
        // console.log({ rightCost, downCost });
        for (let i = 0; i < n; i++) {
            dp[i] = [];
            for (let j = 0; j < m; j++) {
                dp[i][j] = [];
                dp[i][j][1] = Math.min(getXCost(i, j), getXCost(i, j - 1), getYCost(i, j), getYCost(i - 1, j));
                // console.log({
                //   i,
                //   j,
                //   right: getXCost(i, j),
                //   left: getXCost(i - 1, j),
                //   down: getYCost(i, j),
                //   up: getYCost(i, j - 1),
                //   min: dp[i][j][1],
                // });
            }
        }
        const getDp = (i, j, l) => {
            if (!dp[i]) {
                return Infinity;
            }
            if (!dp[i][j]) {
                return Infinity;
            }
            return dp[i][j][l];
        };
        // printStep(1);
        let target = k / 2;
        // console.log(dp);
        for (let l = 2; l <= target; l++) {
            for (let i = 0; i < n; i++) {
                for (let j = 0; j < m; j++) {
                    dp[i][j][l] = Math.min(getDp(i, j - 1, l - 1) + getXCost(i, j - 1), getDp(i, j + 1, l - 1) + getXCost(i, j), getDp(i - 1, j, l - 1) + getYCost(i - 1, j), getDp(i + 1, j, l - 1) + getYCost(i, j));
                }
            }
        }
        // for (let j = 0; j < m; j++) {
        //   for (let i = 0; i < n; i++) {
        //     io.write(dp[i][j][2]);
        //   }
        //   io.writeLine('');
        // }
        // io.writeLine('');
        printStep(target, 2);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    writeArray(arr) {
        arr.forEach((a) => {
            this.write(a);
        });
        this.writeLine('');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
function make2dArray(a, b, fill) {
    return Array.from({ length: a }).map(() => Array.from({ length: b }).map(() => fill));
}
//////////// LIBS
const io = new IO();
function solve() { }
function main() {
    try {
        let n = io.nextNum();
        let m = io.nextNum();
        let k = io.nextNum();
        let rightCost = [];
        let downCost = [];
        for (let i = 0; i < n; i++) {
            rightCost.push([]);
            for (let j = 0; j < m - 1; j++) {
                rightCost[i][j] = io.nextNum();
            }
        }
        for (let i = 0; i < n - 1; i++) {
            downCost.push([]);
            for (let j = 0; j < m; j++) {
                downCost[i][j] = io.nextNum();
            }
        }
        if (k % 2 === 1) {
            let arr = Array.from({ length: m }).fill(-1);
            for (let i = 0; i < n; i++) {
                io.writeArray(arr);
            }
            io.flush();
            return;
        }
        let dp = [];
        const printStep = (step) => {
            for (let i = 0; i < n; i++) {
                for (let j = 0; j < m; j++) {
                    io.write(dp[i][j][step]);
                }
                io.writeLine('');
            }
            io.writeLine('');
        };
        const getXCost = (i, j) => {
            if (!rightCost[i]) {
                return Infinity;
            }
            return rightCost[i][j] || Infinity;
        };
        const getYCost = (i, j) => {
            if (!downCost[i]) {
                return Infinity;
            }
            return downCost[i][j] || Infinity;
        };
        // console.log({ rightCost, downCost });
        for (let i = 0; i < n; i++) {
            dp[i] = [];
            for (let j = 0; j < m; j++) {
                dp[i][j] = [];
                dp[i][j][1] = Math.min(getXCost(i, j), getXCost(i, j - 1), getYCost(i, j), getYCost(i - 1, j));
                // console.log({
                //   i,
                //   j,
                //   right: getXCost(i, j),
                //   left: getXCost(i - 1, j),
                //   down: getYCost(i, j),
                //   up: getYCost(i, j - 1),
                //   min: dp[i][j][1],
                // });
            }
        }
        const getDp = (i, j, l) => {
            if (!dp[i]) {
                return Infinity;
            }
            if (!dp[i][j]) {
                return Infinity;
            }
            return dp[i][j][l];
        };
        // printStep(1);
        let target = k / 2;
        // console.log(dp);
        for (let l = 2; l <= target; l++) {
            for (let i = 0; i < n; i++) {
                for (let j = 0; j < m; j++) {
                    dp[i][j][l] = Math.min(getDp(i, j - 1, l - 1) + getXCost(i, j - 1), getDp(i, j + 1, l - 1) + getXCost(i, j), getDp(i - 1, j, l - 1) + getYCost(i - 1, j), getDp(i + 1, j, l - 1) + getYCost(i, j));
                }
            }
        }
        // for (let j = 0; j < m; j++) {
        //   for (let i = 0; i < n; i++) {
        //     io.write(dp[i][j][2]);
        //   }
        //   io.writeLine('');
        // }
        // io.writeLine('');
        printStep(target);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    writeArray(arr) {
        arr.forEach((a) => {
            this.write(a);
        });
        this.writeLine('');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
function make2dArray(a, b, fill) {
    return Array.from({ length: a }).map(() => Array.from({ length: b }).map(() => fill));
}
//////////// LIBS
const io = new IO();
function solve() { }
function main() {
    try {
        let n = io.nextNum();
        let m = io.nextNum();
        let k = io.nextNum();
        let rightCost = make2dArray(n - 1, m, 0);
        let downCost = make2dArray(n, m - 1, 0);
        for (let i = 0; i < n - 1; i++) {
            for (let j = 0; j < m; j++) {
                rightCost[i][j] = io.nextNum();
            }
        }
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < m - 1; j++) {
                downCost[i][j] = io.nextNum();
            }
        }
        if (k % 2 === 1) {
            let arr = Array.from({ length: m }).fill(-1);
            for (let i = 0; i < n; i++) {
                io.writeArray(arr);
            }
            io.flush();
            return;
        }
        let dp = [];
        const getXCost = (i, j) => {
            if (i < 0 || j < 0 || i >= n - 1 || j >= m) {
                return Infinity;
            }
            return rightCost[i][j];
        };
        const getYCost = (i, j) => {
            if (i < 0 || j < 0 || i >= n || j >= m - 1) {
                return Infinity;
            }
            return downCost[i][j] || Infinity;
        };
        // console.log({ rightCost, downCost });
        for (let i = 0; i < n; i++) {
            dp[i] = [];
            for (let j = 0; j < m; j++) {
                dp[i][j] = [];
                dp[i][j][1] = Math.min(getXCost(i, j), getXCost(i - 1, j), getYCost(i, j), getYCost(i, j - 1));
                // console.log({
                //   i,
                //   j,
                //   right: getXCost(i, j),
                //   left: getXCost(i - 1, j),
                //   down: getYCost(i, j),
                //   up: getYCost(i, j - 1),
                //   min: dp[i][j][1],
                // });
            }
        }
        const getDp = (i, j, l) => {
            if (!dp[i]) {
                return Infinity;
            }
            if (!dp[i][j]) {
                return Infinity;
            }
            return dp[i][j][l];
        };
        let target = k / 2;
        // console.log(dp);
        for (let l = 2; l <= target; l++) {
            for (let i = 0; i < n; i++) {
                for (let j = 0; j < m; j++) {
                    dp[i][j][l] = Math.min(getDp(i - 1, j, l - 1) + getXCost(i - 1, j), getDp(i + 1, j, l - 1) + getXCost(i, j), getDp(i, j - 1, l - 1) + getYCost(i, j - 1), getDp(i, j + 1, l - 1) + getYCost(i, j));
                }
            }
        }
        // for (let j = 0; j < m; j++) {
        //   for (let i = 0; i < n; i++) {
        //     io.write(dp[i][j][2]);
        //   }
        //   io.writeLine('');
        // }
        // io.writeLine('');
        for (let j = 0; j < m; j++) {
            for (let i = 0; i < n; i++) {
                io.write(dp[i][j][target] * 2);
            }
            io.writeLine('');
        }
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();


(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let s=0;s<t;++s){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const s=n(r(747));let o="",i=[],u=0,l="";const a="local"===process.argv[2],p=t=>{if(a){if(i=s.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),s.default.writeFileSync("output.txt",l),console.log(l),s.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{i=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function h(){return i[u++]}function f(){return h().split(" ").map((t=>parseFloat(t)))}function c(){return h().split("")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:h,nextNumbers:f,nextBigNumbers:function(){return h().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(f());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=f();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){a&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const s=n(r(312));s.default.runEachTest((function(){let[t]=s.default.nextNumbers(),e=s.default.nextNumbersMatrix(2).transpose(),[r,n]=e.sort(((t,e)=>e[0]-t[0])).transpose(),o=0,i=r[0];for(let e=0;e<t&&o+n[e]<r[e];++e)o+=n[e],i=Math.max(o,r[e+1]||0);s.default.puts(i)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var s=e[n]={exports:{}};return t[n].call(s.exports,s,s.exports,r),s.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n] = io.nextNumbers()
//
//   let x = io.nextNumbersMatrix(2).transpose()
//
//   let [a, b] = x.sort((a, b) => b[0] - a[0]).transpose()
//
//   let s = 0
//   let best = a[0]
//
//   // io.debug(a)
//   // io.debug(b)
//
//   for (let i = 0; i < n; ++i) {
//     if (s + b[i] < a[i]) {
//       s += b[i]
//       best = Math.max(s, a[i + 1] || 0)
//     } else {
//       break
//     }
//   }
//
//   io.puts(best)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let s=0;s<t;++s){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const s=n(r(747));let o="",i=[],u=0,l="";const a="local"===process.argv[2],p=t=>{if(a){if(i=s.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),s.default.writeFileSync("output.txt",l),console.log(l),s.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{i=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function h(){return i[u++]}function f(){return h().split(" ").map((t=>parseFloat(t)))}function c(){return h().split("")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:h,nextNumbers:f,nextBigNumbers:function(){return h().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(f());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=f();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){a&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const s=n(r(312));s.default.runEachTest((function(){let[t]=s.default.nextNumbers(),e=s.default.nextNumbersMatrix(2).transpose(),[r,n]=e.sort(((t,e)=>e[0]-t[0])).transpose(),o=0,i=r[0];for(let e=0;e<t&&o+n[e]<r[e];++e)o+=n[e],i=[o,r[e+1]||0].max();s.default.puts(i)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var s=e[n]={exports:{}};return t[n].call(s.exports,s,s.exports,r),s.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n] = io.nextNumbers()
//
//   let x = io.nextNumbersMatrix(2).transpose()
//
//   let [a, b] = x.sort((a, b) => b[0] - a[0]).transpose()
//
//   let s = 0
//   let best = a[0]
//
//   // io.debug(a)
//   // io.debug(b)
//
//   for (let i = 0; i < n; ++i) {
//     if (s + b[i] < a[i]) {
//       s += b[i]
//       best = [s, a[i + 1] || 0].max()
//     } else {
//       break
//     }
//   }
//
//   io.puts(best)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

let input = ''

process.stdin.on('data', (x) => input += x)

process.stdin.on('end', () => {
  const lines = input.trim().split('\n')
  let curLine = 0
  const T = parseInt(lines[curLine++])
  for (let t = 0; t < T; t++) {
    const n = parseInt(lines[curLine++])
    const a = parseIntArray(lines[curLine++])
    const b = parseIntArray(lines[curLine++])
    const restaurant = [...new Array(n)]
      .map((_, idx) => [a[idx], b[idx]])
      .sort(([xa, xb], [ya, yb]) => {
        if (xa !== ya) {
          if (xa < ya) return -1
          if (xa > ya) return 1
          return 0
        }
        if (xb < yb) return -1
        if (xb > yb) return 1
        return 0
      })

    let accSum = b.reduce((x, y) => x + y, 0n)
    let ans = accSum

    restaurant.forEach(([ra, rb]) => {
      accSum -= rb
      const cand = ra > accSum ? ra : accSum
      ans = ans < cand ? ans: cand
    })

    console.log(ans.toString())
  }
})

const parseIntArray = (line) => line.split(' ').map((x) => BigInt(x))

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

    C();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let x = n;
        let res = [4*n];
        let num = 4*n;
        n -= 1;
        let i = 3;
        let f = 2;
        while(n > 0){
                num -= 2;
                let flag = false;
                for(let j = res.length-1; j >= 0; j--){
                    if(res[j] % num === 0){
                        flag = true;
                        break;
                    }
                }
                if(!flag){
                    res.push(num);
                    n--;
                }
        }

        console.log(res.join(' '));
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [a,b] = ti(readline().split(' '));
        let s = readline().split('');
        //console.log(s.length);
        let x = [];
        let i = 0;
        while(i < s.length && s[i] !== '1'){
            i++;
        }

        while(i < s.length){
            if(s[i] === '1')
                x.push(a);
            while(i < s.length && s[i] === '1'){
                i++;
            }

            if(i < s.length && s[i] === '0'){
                x.push(s[i]);
            }
            i++;
        }

        i = 0;
        let sum = x.length !== 0 ? a : 0;
        while(i < x.length){
            if(pi(x[i]) === a){
                let count = 0;
                i++;
                while(i < x.length && pi(x[i]) === 0){
                    count += b;
                    i++;
                }

                if(i < x.length){
                    sum = Math.min(sum+a, sum+count);
                }
            }
        }

        console.log(sum);
    }
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        let b = ti(readline().split(' '));
        let pair = new Array(n);
        for(let i = 0; i < n; i++){
            pair[i] = [a[i],b[i]];
        }
        pair.sort((a,b) => a[0]-b[0]);
        let x = new Array(n);
        for(let i = n-1; i >= 0; i--){
            if(i === n-1){
                x[i] = pair[i][1];
            }else{
                x[i] = x[i+1] + pair[i][1];
            }
        }

        let min = 9999999999999;
        for(let i = 0; i < n-1; i++){
            min = Math.min(min, Math.max(pair[i][0], x[i+1]));
        }

        console.log(Math.min(min, pair[n-1][0], x[0]));
    }
}

function C1443(a1, b1) {
  var n = a1.length;
  var c = [];

  for (var i = 0; i < n; i++) {
    c.push([a1[i], b1[i]]);
  }

  c.sort(function (p, q) {
    return p[0] - q[0];
  });

  for (var _i = n - 2; _i >= 0; _i--) {
    c[_i][1] += c[_i + 1][1];
  }

  var ans = Math.min(c[n - 1][0], c[0][1]);

  for (var _i2 = n - 2; _i2 >= 0; _i2--) {
    ans = Math.min(ans, Math.max(c[_i2][0], c[_i2 + 1][1]));
  }

  return ans;
}

function execute(readline, print) {
  var iter = {
    next: function next() {
      return readline().trim();
    }
  };

  var split = function split(string) {
    return string.split(' ').map(Number);
  };

  var t = Number(iter.next());

  while (t--) {
    iter.next();
    var arr1 = split(iter.next());
    var arr2 = split(iter.next());
    print(C1443(arr1, arr2));
  }
}

execute(readline, print)

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const other = readLine().split(" ").map(Number);
    const own = readLine().split(" ").map(Number);
    const data = [];
    for (let i = 0; i < len; i++) {
      data.push([other[i], own[i]]);
    }
    data.sort((a, b) => b[0] - a[0]);
    let [ownTime, otherTime] = [0, 0];

    for (let i = 0; i < len; i++) {
      let [r, p] = data[i];
      if (ownTime + p < r) ownTime += p;
      else {
        otherTime = r;
        break;
      }
    }
    console.log(Math.max(ownTime, otherTime));
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const other = readLine().split(" ").map(Number);
    const own = readLine().split(" ").map(Number);
    let [ownTime, otherTime] = [0, 0];

    for (let i = 0; i < len; i++) {
      let [r, p] = [other[i], own[i]];
      if (ownTime + p < Math.max(otherTime, r)) {
        ownTime += p;
      } else {
        otherTime = r;
      }
    }
    console.log(Math.max(ownTime, otherTime));
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const other = readLine().split(" ").map(Number);
    const own = readLine().split(" ").map(Number);
    let [ownTime, otherTime] = [0, 0];

    for (let i = 0; i < len; i++) {
      let [r, p] = [other[i], own[i]];
      if (ownTime + p < Math.max(otherTime, r)) {
        ownTime += p;
      } else {
        otherTime = Math.max(otherTime, r);
      }
    }
    console.log(Math.max(ownTime, otherTime));
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const other = readLine().split(" ").map(Number);
    const own = readLine().split(" ").map(Number);
    let [ownTime, otherTime] = [0, 0];

    for (let i = 0; i < len; i++) {
      let [r, p] = [other[i], own[i]];
      if (ownTime + p < Math.max(otherTime, r)) {
        ownTime += p;
      } else {
        otherTime = r;
      }
    }
    const res = Math.max(ownTime, otherTime);
    let ownCount = 0;
    for (let i = 0; i < len; i++) {
      ownCount += own[i];
    }

    console.log(Math.min(res, ownCount, Math.max(...other)));
  }
}

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

    C();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let x = n;
        let res = [4*n];
        let num = 4*n;
        n -= 1;
        let i = 3;
        let f = 2;
        while(n > 0){
                num -= 2;
                let flag = false;
                for(let j = res.length-1; j >= 0; j--){
                    if(res[j] % num === 0){
                        flag = true;
                        break;
                    }
                }
                if(!flag){
                    res.push(num);
                    n--;
                }
        }

        console.log(res.join(' '));
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [a,b] = ti(readline().split(' '));
        let s = readline().split('');
        //console.log(s.length);
        let x = [];
        let i = 0;
        while(i < s.length && s[i] !== '1'){
            i++;
        }

        while(i < s.length){
            if(s[i] === '1')
                x.push(a);
            while(i < s.length && s[i] === '1'){
                i++;
            }

            if(i < s.length && s[i] === '0'){
                x.push(s[i]);
            }
            i++;
        }

        i = 0;
        let sum = x.length !== 0 ? a : 0;
        while(i < x.length){
            if(pi(x[i]) === a){
                let count = 0;
                i++;
                while(i < x.length && pi(x[i]) === 0){
                    count += b;
                    i++;
                }

                if(i < x.length){
                    sum = Math.min(sum+a, sum+count);
                }
            }
        }

        console.log(sum);
    }
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        let b = ti(readline().split(' '));
        a.sort((a,b) => a-b);
        for(let i = n-2; i >= 0; i--)
            b[i] += b[i+1];

        let min = 9999999999999;
        for(let i = 0; i < n-1; i++){
            min = Math.min(min, Math.max(a[i], b[i+1]));
        }

        console.log(Math.min(min, a[n-1], b[0]));
    }
}


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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********
function main() {
    var input = readline().split(" ");
    var players = readline().split(" ");
//   var input = "6 180".split(" ");
//   var players = "90 80 70 60 50 100 2".split(" ");
  players = players.sort((a, b) => b - a);
  let minPoints = input[1],
    left = 0,
    right = players.length;
  while (left + Math.floor(minPoints / players[left]) < right) {
    right -= Math.floor(minPoints / players[left]);
    left++;
  }
  console.log(left);
}

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() {
    /*

    */
    let a = readLine().trim().split(' ').map(string => {return parseInt(string.trim());});
    let N = a[0], D = a[1];
    a = readLine().trim().split(' ').map(string => {return parseInt(string.trim());});
    a.sort((a, b) => b - a); // For descending sort
    let i=0,count=0;
    while(N>0){
        N-=Math.ceil(D/a[i]);
        if(Math.ceil(D/a[i])*a[i] == D){
            N-=1;
        }
        // console.log(D,a[i],N);
        i++;
    }
    if(N<0){
        i--;
    }
    console.log(i);
    }

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

async function solve(r) {
  const rns = async () => {
    return (await r()).split(' ').filter(s => s !== '').map(Number);
  };
  const [n, m] = await rns();
  const a = await rns();
  a.sort((a, b) => a - b);
  let left = 0,
      right = n - 1;
  let res = 0;
  while (left <= right) {
    let num = a[right];
    while (left < right && num <= m) {
      num += a[right];
      left++;
    }
    if (num > m) res++;
    right--;
  }
  return res;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      res[i] = await solve(r);
    }
    return res.join('\n');
  } catch (error) {
    console.log('zdebug' + error);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
async function read() {
  return (await it.next()).value;
}
void async function () {
  const output = await main(read);
  process.stdout.write(output);
}();

'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++];
}
function main(){

var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}
let i=0;let j=players.length;

while(true){
    if(j===0||j<bigger(players[i],d)){break;}
    j=j-bigger(players[i],d)
    i++;

    sol++;

}
console.log(sol);
}

'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++];
}
function main(){

var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}
let i=0;let j=players.length;

while(true){
    if(j===0||j<bigger(players[i],d)){break;}
    j=players.length-bigger(players[i],d)
    i++;

    sol++;

}
console.log(sol);
}

function main(){
var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1)
    players.shift();
    sol++;

}
console.log(sol,sol,sol,1,2,3);

}

function main(){
var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1)
    players.shift();
    sol++;

}
console.log(sol+" ");

}

function main(){
var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1)
    players.shift();
    sol++;

}
console.log(sol);

}

function main(){
var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){console.log(2);break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1)
    players.shift();
    sol++;

}

}

function main(){
var num = [6, 180];

var n=num[0];
var d=num[1];
var players= [90, 80, 70, 60, 50, 100];
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){console.log(sol);break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1);
    players.shift();
    sol++;

}

}

function main(){
var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){console.log(sol);break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1)
    players.shift();
    sol++;

}

}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********
function main() {
  var input = readline().split(" ");
  var players = readline().split(" ");
  //   var input = "6 180".split(" ");
  //   var players = "90 80 70 60 50 100 2 2".split(" ");
  players = players.sort((a, b) => b - a);
  let minPoints = input[1],
    left = 0,
    right = players.length;
  while (left + Math.floor(minPoints / players[left]) < right) {
    console.log(left, right, players[left]);
    right -= Math.floor(minPoints / players[left]);
    left++;
  }
}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
  var input = readline().split(" ");
  var players = readline().split(" ");
  //   var input = "60 180".split(" ");
  //   var players = "90 80 70 60 50 100".split(" ");
  let minPoints = input[1];
  let counter = 0;
  players = players.sort((a, b) => b - a);
  while (players.length > Math.ceil(minPoints / players[0])) {
    let wannaPlayer = Math.floor(minPoints / players[0]);
    players.splice(0, 1);
    for (let i = 0; i < wannaPlayer; i++) {
      players.length--;
    }
    counter++;
  }
  console.log(counter);
}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}
// ********** Code Start **********
function main() {
    var input = readline().split(" ");
    var players = readline().split(" ");
//   var input = "6 180".split(" ");
//   var players = "90 80 70 60 50 100 2 2".split(" ");
  let leng = players.length;
  let minPoints = input[1];
  players = players.sort((a, b) => b - a);
  let i = 0;
  while (leng > Math.ceil(minPoints / players[i])) {
    // console.log("leng befor is " + leng);
    // console.log("player" + i + "=" + players[i]);
    leng -= Math.ceil(minPoints / players[i]);
    i++;
  }
  console.log(i);
}
// main();

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}
// ********** Code Start **********
function main() {
  var input = readline().split(" ");
  var players = readline().split(" ");
  //   var input = "6 180".split(" ");
  //   var players = "100 90 80 70 60 50 2 2".split(" ");
  let leng = players.length;
  let minPoints = input[1];
  let counter = 0;
  players = players.sort((a, b) => b - a);
  let i = 0;
  while (leng > 0) {
    // console.log("leng befor is " + leng);
    // console.log("player" + i + "=" + players[i]);
    leng -= Math.ceil(minPoints / players[i]);
    i++;
  }
  console.log(i - 1);
}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
  let input = readline().split(" ");
  let players = readline().split(" ");
  let minPoints = input[1];
  let counter = 0;
  players = players.sort((a, b) => b - a);
  while (players.length - Math.ceil(minPoints / players[0]) > 0) {
    let wannaPlayer = Math.floor(minPoints / players[0]);
    players.splice(0, 1);
    for (let i = 0; i < wannaPlayer; i++) {
      players.length--;
    }
    counter++;
  }
  console.log(counter);
}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
  var input = readline().split(" ");
  var players = readline().split(" ");
  let playersLength = input[0];
  let minPoints = input[1];
  let counter = 0;
  players = players.sort((a, b) => b - a);
  while (players.length - Math.floor(minPoints / players[0]) > 0) {
    let wannaPlayer = Math.floor(minPoints / players[0]);
    players.splice(0, 1);
    for (let i = 0; i < wannaPlayer; i++) {
      players.length--;
    }
    counter++;
  }
  return counter;
}

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() {
    /*

    */
    let a = readLine().trim().split(' ').map(string => {return parseInt(string.trim());});
    let N = a[0], D = a[1];
    a = readLine().trim().split(' ').map(string => {return parseInt(string.trim());});
    a.sort((a, b) => b - a); // For descending sort
    let i=0;
    while(N>0){
        if(D>a[i]){
            N-=Math.ceil(D/a[i]);
        }else{
            N-=1;
        }
        i++;
    }
    i--;
    console.log(i);
    }

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

async function solve(r) {
  const rns = async () => {
    return (await r()).split(' ').filter(s => s !== '').map(Number);
  };
  const [n, m] = await rns();
  const a = await rns();
  a.sort((a, b) => a - b);
  let left = 0,
      right = n - 1;
  let res = 0;
  while (left <= right) {
    let num = a[right];
    while (left < right && num < m) {
      num += a[right];
      left++;
    }
    if (num >= m) res++;
    right--;
  }
  return res;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      res[i] = await solve(r);
    }
    return res.join('\n');
  } catch (error) {
    console.log('zdebug' + error);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
async function read() {
  return (await it.next()).value;
}
void async function () {
  const output = await main(read);
  process.stdout.write(output);
}();


const readline = require('readline');

let input = [];

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
});

rl.on('line', lineInput => {
	input.push(lineInput);
});

rl.on('close', () => {
	const test = parseInt(input[0]);
	for (let t=0; t < test; t++) {
		let inputNum = input[2*t+1].split(' ').map((a) => parseInt(a));
		let arr = input[2*t+2].split(' ').map((a) => parseInt(a));
		console.log(solution(inputNum, arr));
	}
});

function solution(nums, arr) {
	let n = nums[0];
	let bul = nums[1];
	arr = arr.sort((a, b) => a-b);
	let sum = 0;
	let count = 0;
	for (let j=n-1; j>=0; j--) {
		sum += arr[j];
		if (sum/(n-j) < bul) {
			break;
		}
		count += 1;
	}
	return count;
}

'use strict';

const rl = require('readline')
  .createInterface({ input: process.stdin, output: process.stdout });
const write = (...args) => {
  process.stdout.write(args.join(' '));
};

const lines = [];
rl.on('line', line => {
  lines.push(line);
});

rl.on('close', main);

let rli = 0;
function readline() {
  return lines[rli++];
}

function main() {
  const times = parseInt(readline());
  for(let t = 0; t < times; ++t) {
    const rich = parseInt(readline().split(' ')[1]);
    const moneys = readline().split(' ').map(e => parseInt(e));
    moneys.sort((a,b) => b - a);
    let sum = 0;
    let result = 0;
    for(let i = 0; i < moneys.length; ++i) {
      if((sum + moneys[i])/(result + 1) >= rich) {
        sum = sum + moneys[i];
        result = result + 1;
      } else {
        break;
      }
    }
    write(`${result}\n`);
  }
}

// solved by: asmjaime

t = +readline();
while (t-->0){
    ip = readline().split(' ').map(Number);
    n = ip[0];
    x = ip[1];
    poor = [];
    sum = 0;
    readline().split(' ').map(Number).forEach(a => {
        if (a >= x){
            sum += a;
        } else {
            poor.push(a);
        }
    });

    poor.sort((a,b)=>b-a);

    count = n - poor.length;
    for (i=0;i<poor.length;i++){
        if ((sum + poor[i])/(count+1) >= x){
            sum += poor[i];
            count++;
        } else {
            break;
        }
    }
    print(count);
}

let i = '';
let lines;
process.stdin.on('data', (c) => (i += c));
process.stdin.on('end', () => {
  const { EOL } = require('os');
  lines = i.split(EOL); /*your input text, split by lines*/
  main();
});

function solve(n, x, a) {
  a.sort((a, b) => b - a);
  let sum = 0;
  for(let i = 0; i < n; ++i) {
    sum += a[i];
    if (sum < x * (i + 1)) return i;
  }
  return n;
}

function main() {
  let currentLine = 0;
  const readLine = (_) => lines[currentLine++].split(' ').map((val) => parseInt(val));

  const test = readLine()[0];
  for (let t = 1; t <= test; ++t) {
    const [n, x] = readLine();
    const a = readLine();
    console.log(solve(n, x, a));
  }
}

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var n = one[0];
    var x = one[1];
    var sum = 0;
    var list = nextIntArray();
    list.sort(function(a,b){
    	return a - b;
    });
    for(var j = 0; j < n; j++){
      sum += list[j];
    }
    for(var j = 0; j < n; j++){
      if(sum / (n - j) >= x){
        output[i] = n - j;
        break;
      }
      sum -= list[j];
    }
    if(output[i] == null){
      output[i] = 0;
    }
  }
  myout(myconv(output,9));
}

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});
var lines=[],idx=0;
rl.on('line', line => {
    lines.push(line);
});
rl.on('close',main);
function read(){
    return lines[idx++];
}
function main(){
    var times=parseInt(read());
    while(times--){
        var tmp=read().split(' ');
        var size=parseInt(tmp[0]),mon=parseInt(tmp[1]);
        var arr=read().split(' ').map(s=>parseInt(s));
        arr.sort((a,b)=>{
            return b-a;
        });
        var avg=0,sum=0,num=0,ans=0;
        arr.forEach(idx=>{
            num++;
            if((sum+idx)/num>=mon){
                ans=num;
            }
            sum+=idx;
            avg=sum/num;
        });
        console.log(ans);
    }
}

var range = readline();

for(var i=0;i<range;i++) {
    var input = readline().split(" ").map(x=> parseInt(x));
    var saving = readline().split(" ").map(x => parseInt(x));

    saving.sort((a,b) => b - a);
    var minAverage = input[1];
    var sum = 0;
    var count = 0;

    for(var j=0;j<saving.length;j++) {
        sum = sum + saving[j];
        var avg = sum / (j+1);

        if(avg >= minAverage) {
            count++;
        } else {
            break;
        }
    }

    print(count);
}

t = +readline();
while (t-->0){
    ip = readline().split(' ').map(Number);
    n = ip[0];
    x = ip[1];
    poor = [];
    sum = 0;
    readline().split(' ').map(Number).forEach(a => {
        if (a >= x){
            sum += a;
        } else {
            poor.push(a);
        }
    })
    count = n - poor.length;
    for (i=0;i<poor.length;i++){
        if ((sum + poor[i])/(count+1) >= x){
            sum += poor[i];
            count++;
        } else {
            break;
        }
    }
    print(count);
}

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var n = one[0];
    var x = one[1];
    var sum = 0;
    var list = nextIntArray();
    list.sort(function(a,b){
    	return a - b;
    });
    for(var j = 0; j < n; j++){
      sum += list[j];
    }
    for(var j = 0; j < n; j++){
      if(sum / (n - j) >= x){
        output[i] = n - j;
        break;
      }
      sum -= list[i];
    }
    if(output[i] == null){
      output[i] = 0;
    }
  }
  myout(myconv(output,9));
}


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

    E();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [a,b] = ti(readline().split(' '));

        if(a === b){
            console.log(0);
            continue;
        }

        let d = Math.abs(a-b);
        if(d <= 10){
            console.log(1);
            continue;
        }else{
            if(d % 10 !== 0)
                console.log(1 + Math.floor(d/10));
            else
                console.log(d / 10);
        }
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [a,b,x,y,n] = ti(readline().split(' '));

        if(a > b){
            let temp = a;
            a = b;
            b = temp;
            temp = x;
            x = y;
            y = temp;
        }

        if(b - y >= n){
            b -= n;
            console.log(a*b);
        }else{
            n -= (b-y);
            b = y;
            if(a-x >= n){
                a -= n;
            }else{
                a = x;
            }

            console.log(a*b);
        }
    }
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,x,y] = ti(readline().split(' '));

        let min = 99999999999999;
        let res = null;
        for(let i = 1; i <= x; i++){
            for(let j = 0; j <= y-x; j++){
                let inclX = false;
                let inclY = false;
                let op = new Array(n);
                for(let k = 0; k < n; k++){
                    if(k === 0){
                        op[k] = i;
                    }else{
                        op[k] = op[k-1] + j;
                    }

                    if(op[k] === x)
                        inclX = true;

                    if(op[k] === y)
                        inclY = true;
                }

                if(inclX && inclY){
                    if(min > op[n-1]){
                        min = op[n-1];
                        res = op;
                    }
                }
            }
        }

        for(let num of res)
            console.log(num);
    }
}

function D(){
    let t = pi(readline());
    let getSum = (str) => {
        let sum = 0;
        for(let i = 0; i < str.length; i++){
            sum += pi(str[i]);
        }
        return sum;
    }

    while(t > 0){
        t--;

        let [n, s] = ti(readline().split(' '));
        let str = JSON.stringify(n);
        let sum = getSum(str);
        let count = 0;
        let p = 0;
        while(sum > s){
            let m = Math.pow(10, p+1);
            let num = pi(str.substring(str.length-1-p,str.length));
            count += (m-num);
            n += (m-num);
            let c = pi(str[str.length-1-p]);
            sum -= (c-1);
            p++;
            str = JSON.stringify(n);
        }

        console.log(count);
    }
}

function E(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,k] = ti(readline().split(' '));
        let x = ti(readline().split(' '));
        let y = readline();
        x.sort((a,b) => a-b);
        let left = new Array(n);
        let right = new Array(n);
        let p1 = 0;
        let p2 = 0;

        if(n === 1){
            console.log(1);
            continue;
        }

        for(let i = 0; i < x.length; i++){
            while(p1 <= i && x[i] - x[p1] > k){
                p1++;
            }

            while(p2 < n && x[p2] - x[i] <= k){
                p2++;
            }

            p2 -= 1;

            left[i] = i-p1+1;
            right[i] = x[p2] - x[i] > k ? p2-i : p2-i+1;
        }
        // console.log(left);
        // console.log(right);

        for(let i = 1; i < n; i++){
            left[i] = Math.max(left[i], left[i-1]);
        }

        for(let i = n-2; i >= 0; i--){
            right[i] = Math.max(right[i], right[i+1]);
        }

        let max = 0;

        for(let i = 0; i < n-1; i++)
            max = Math.max(max, left[i] + right[i+1]);

        console.log(max);
    }
}

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i <= b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = a; i >= b; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function Arr(a, b, cb, prev) {
  let p = prev || 0;
  if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);
  return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

function max(a, b) {
  if (a > b) return a;
  return b;
}

(async () => {
  await inputPromise;
  let inp = input.split(/\D+/).map(v => +v); r = 0;
  let t = inp[r++];
  For(1, t, i => {
    let [n, k] = inp.slice(r, r = r + 2);
    let x = inp.slice(r, r = r + n).sort((a, b) => a - b);
    let y = inp.slice(r, r = r + n);
    var f = []
    var start = 0;
    For(0, n - 1, i => {
      while (x[i] - x[start] > k) start++;
      f[i] = i - start + 1;
    });
    var fm = Arr(0, n - 1, (i, p) => Math.max(p, f[i]));
    var f2 = Arr(0, n - 1, i => f[i] + (fm[i - f[i]] || 0));
    console.log(Math.max(...f2));
  })
})();


'use strict';

function solve(n, a) {
  a = a.map(num => num - 1);
  let res = [],
      set = new Set([...new Array(n).keys()]);
  const g = Array.from({
    length: n
  }, () => []);
  for (let [i, j] of a.entries()) {
    if (set.has(j)) {
      res[i] = j;
      set.delete(j);
    }
    g[j].push(i);
  }
  const nums = [...set];
  for (let i = 0; i < n; i++) {
    if (res[i] === undefined) {
      const num = nums.pop();
      if (num === i) {
        for (let j of g[a[i]]) {
          if (j !== i) {
            res[i] = a[i];
            res[j] = num;
            break;
          }
        }
      } else {
        res[i] = num;
      }
    }
  }
  let len = 0;
  for (let i = 0; i < n; i++) {
    if (res[i] === a[i]) len++;
  }
  return `${len}\n${res.map(num => num + 1).join(' ')}`;
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res.push(solve(n, a));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', () => {
  inputs = str.split('\n').values();
  main(read);
});

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--) {
		const n = rn();
		const a = rna();

		a.unshift(0);

		let ans = 0;
		const taken = Array(n+1);
		const asgnd = Array(n+1);
		for (let i = 1; i <= n; i++) {
			if (!taken[a[i]]) {
				asgnd[i] = a[i];
				taken[a[i]] = true;
				ans++;
			}
		}

		const avl = [];
		for (let i = 1; i <= n ; i++)
			if (!taken[i]) avl.push(i);

		for (let i = 1, k = 0; i <= n; i++) {
			if (!asgnd[i]) {
				const x = avl.pop();
				if (i == x) {
					if (!avl.length) {
						let j = 1;
						while (a[j] != a[i] && j != i) j++;
						asgnd[j] = i;
						asgnd[i] = a[i];
					} else {
						asgnd[i] = avl.pop();
						avl.push(x);
					}
				} else {
					asgnd[i] = x;
				}
			}
		}

		console.log(ans);
		console.log(asgnd.slice(1).join(' '));
	}
}

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--) {
		const n = rn();
		const a = rna();

		a.unshift(0);

		let ans = 0;
		const taken = Array(n+1);
		const asgnd = Array(n+1);
		for (let i = 1; i <= n; i++) {
			if (!taken[a[i]]) {
				asgnd[i] = a[i];
				taken[a[i]] = true;
				ans++;
			}
		}

		const avl = [];
		for (let i = 1; i <= n ; i++) {
			if (!taken[i]) {
				avl.push(i);
			}
		}

		for (let i = 1; i <= n; i++) {
			if (!asgnd[i]) {
				const x = avl.pop();
				if (i == x) {
					if (!avl.length) {
						let j = 1;
						while (a[j] != a[i] && j != i) {
							j++;
						}
						asgnd[j] = i;
						asgnd[i] = a[i];
					} else {
						asgnd[i] = avl.pop();
						avl.push(x);
					}
				} else {
					asgnd[i] = x;
				}
			}
		}

		console.log(ans);
		console.log(asgnd.slice(1).join(' '));
	}
}

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--) {
		const n = rn();
		const a = rna();

		a.unshift(0);

		let ans = 0;
		const taken = Array(n+1);
		const asgnd = Array(n+1);
		for (let i = 1; i <= n; i++) {
			if (!taken[a[i]]) {
				asgnd[i] = a[i];
				taken[a[i]] = true;
				ans++;
			}
		}

		const avl = Array(n+1);
		for (let i = 1; i <= n ; i++) {
			if (!taken[i]) {
				avl.push(i);
			}
		}

		for (let i = 1; i <= n; i++) {
			if (!asgnd[i]) {
				const x = avl.pop();
				if (i == x) {
					if (!avl.length) {
						let j = 1;
						while (a[j] != a[i] && j != i) {
							j++;
						}
						asgnd[j] = i;
						asgnd[i] = a[i];
					} else {
						asgnd[i] = avl.pop();
						avl.push(x);
					}
				} else {
					asgnd[i] = x;
				}
			}
		}

		console.log(ans);
		console.log(asgnd.slice(1).join(' '));
	}
}

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--) {
		const n = rn();
		const a = rna();

		a.unshift(0);

		let ans = 0;
		const taken = Array(n+1);
		const asgnd = Array(n+1);
		for (let i = 1; i <= n; i++) {
			if (!taken[a[i]]) {
				asgnd[i] = a[i];
				taken[a[i]] = true;
				ans++;
			}
		}

		const avl = [];
		for (let i = 1; i <= n ; i++)
			if (!taken[i]) avl.push(i);

		for (let i = 1, k = 0; i <= n; i++) {
			if (!asgnd[i]) {
				const x = avl.pop();
				if (i == x) {
					//if (!avl.length) {
						//let j = 1;
						//while (a[j] != a[i] && j != i) j++;
						//asgnd[j] = i;
						//asgnd[i] = a[i];
					//} else {
						asgnd[i] = avl.pop();
						avl.push(x);
					//}
				} else {
					asgnd[i] = x;
				}
			}
		}

		console.log(ans);
		console.log(asgnd.slice(1).join(' '));
	}
}

'use strict';

function solve(n, a) {
  let res = [],
      set = new Set(Array.from({
    length: n
  }, (_, i) => i + 1));
  for (let [i, num] of a.entries()) {
    if (set.has(num)) {
      res[i] = num;
      set.delete(num);
    }
  }
  let len = n - set.size;
  const nums = [...set];
  for (let i = 0; i < n; i++) {
    if (res[i] === undefined) {
      res[i] = nums.pop();
    }
  }
  return `${len}\n${res.join(' ')}`;
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res.push(solve(n, a));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', () => {
  inputs = str.split('\n').values();
  main(read);
});