limit = readline(), inputs = readline().split(" ").map(Number);
i = 0, n = inputs.length - 1, temp = undefined;

function swap(arr, x, y)
{
    temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}

for(i; i < n; i++, n--)
    if((i+1) % 2 != 0)
        swap(inputs, i, n);

print(inputs.join(" "));

var num = parseInt(readline()),
arr = readline().split(' ').map(function(i) {return parseInt(i); }),
tmp = null;

for (var i = 0; i < num; i++) {
    if (i === Math.floor(num/2)) break;
    if (i % 2 === 1) continue;
    tmp = arr[i];
    arr[i] = arr[num - 1 - i];
    arr[num - 1 - i] = tmp;
}

print(arr.join(' '));

var num = readline();
var arr = readline().split(' ').map(function (i){
    return parseInt(i)
});

var tmp;

for (var i = 0; i < num; i++) {
    if (i === Math.floor(num/2)) break;
    if (i % 2 !== 0) continue;
    tmp = arr[i];
    arr[i] = arr[num - 1 - i];
    arr[num - 1 - i] = tmp;
}

print(arr.join(' '));

readline();
var set = readline().split(" ").map(Number);
var q = set.length;
var out = [];
var a = 0;
for (var i = 0; i < q; i++) {
	if (q - i === q / 2) {
		a = 1;
	}
	out.push(set[(i + a) % 2 === 0 ? q - 1 - i : i]);
}
print(out.join(" "));

function main() {
    readline();
    var data = readline().split(' ').map(Number);
    var n = data.length;
    var i=0;
    while(i<data.length/2){
        if(i%2 == 0){
            var a = data[i];
            data[i] = data[n-i-1];
            data[n-i-1] = a;
        }
        i++
    }
    return print(data.join(' '));
}

main()

limit = readline(), inputs = readline().split(" ").map(Number);
i = 0, n = inputs.length - 1, temp = undefined;

for(i; i < n; i+=2, n-=2)
{
    temp = inputs[i];
    inputs[i] = inputs[n];
    inputs[n] = temp;
}

print(inputs.join(" "));

var num = readline();
var arr = readline().split(' ').map(function (i){
    return parseInt(i)
});

var tmp;

for (var i = 0; i < num; i++) {
    if (i === Math.floor(num/2) - 1) break;
    if (i % 2 !== 0) continue;
    tmp = arr[i];
    arr[i] = arr[num - i];
    arr[num - i] = tmp;
}

print(arr.join(' '));

var num = readline();
var arr = readline().split(' ').map(function (i){
    return parseInt(i)
});

var tmp;

for (var i = 0; i < num; i++) {
    if (i === Math.floor(num/2) - 1) break;
    tmp = arr[i];
    arr[i] = arr[num - i];
    arr[i] = arr[num - i];
}

print(arr.join(' '));

var num = readline();
var arr = readline().split(' ').map(function (i){
    return parseInt(i)
});

var tmp;

for (var i = 0; i < num; i++) {
    if (i === Math.floor(num/2) - 1) break;
    tmp = arr[i];
    arr[i] = arr[num - i];
    arr[num - i] = tmp;
}

print(arr.join(' '));

function main() {
    readline();
    var data = readline().split(' ').map(Number);
    var n = data.length;
    var i=0;
    while(i<data.length/2){
        if(i%2 == 0){
            var a = data[i];
            data[i] = data[n-i-1];
            data[n-i-1] = a;
        }
        i++
    }
    return print(data);
}

main()


'use strict';
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
    input: process.stdin,
});
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
let n;
let d;
let a;
function f(b) {
    let m = b.length;
    let k = 0;
    let mn = b[0];
    let l = 0;
    let mx = b[0];
    for (let i = 1; i < m; i++) {
        let gap = b[i] - b[i - 1];
        if (mn > gap) {
            mn = gap;
            k = i;
        }
        if (mx < gap) {
            mx = gap;
            l = i;
        }
    }
    let can = Math.trunc(mx / 2);
    let back = d - b[b.length - 1];
    can = Math.max(can, back);
    // printf("b: %j mn %d can %d\n", b, mn, can);
    return Math.min(mn, can);
}
function solve() {
    let k = 0;
    let mn = a[0];
    for (let i = 1; i < n; i++) {
        let gap = a[i] - a[i - 1];
        if (mn > gap) {
            mn = gap;
            k = i;
        }
    }
    let ans = mn;
    const b = [];
    for (let i = 0; i < n; i++) {
        if (i != k) {
            b.push(a[i]);
        }
    }
    ans = Math.max(ans, f(b));
    if (k > 0) {
        const c = [];
        for (let i = 0; i < n; i++) {
            if (i != k - 1) {
                c.push(a[i]);
            }
        }
        ans = Math.max(ans, f(c));
    }
    return ans - 1;
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        d = nextInt();
        a = af(n);
        for (let i = 0; i < n; i++) {
            a[i] = nextInt();
        }
        printf("%d\n", solve());
    }
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
lines.push(input);
})
rl.on('close', () => {
// (function() {
// const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
let l = 0;
let t = +lines[l++]
const output = []
for (let i = 0; i < t; i++) {
l++
const [n, d] = lines[l++].trim().split(' ').map(Number)
const arr = lines[l++].trim().split(' ').map(Number)
output[i] = solve(n, d, arr)
}
console.log(output.join('\n'))
// })()
})

function solve(n, d, arr) {
    const parts = Array(n + 1)
    const leftMin = Array(n)
    const leftMax = Array(n)
    const rightMin = Array(n)
    const rightMax = Array(n)
    arr.forEach((x, i) => {
        // between i - 1 and i
        parts[i] = i ? x - arr[i - 1] - 1 : x - 1
        // max of [0, i]
        leftMin[i] = i ? Math.min(leftMin[i - 1], parts[i]) : parts[i]
        leftMax[i] = i ? Math.max(leftMax[i - 1], parts[i]) : parts[i]
    })
    parts[n] = d - arr[n - 1] - 1

    for (let i = n - 1; i >= 0; i--) {
        // max of [i, n - 1]
        rightMin[i] = i < n - 1 ? Math.min(rightMin[i + 1], parts[i]) : parts[i]
        rightMax[i] = i < n - 1 ? Math.max(rightMax[i + 1], parts[i]) : parts[i]
    }
// console.log(leftMin, rightMin)
    //
    let ans = -Infinity
    arr.forEach((x, i) => {
        // expect for parts[i] and parts[i + 1]
        const merged = parts[i] + parts[i + 1] + 1
        let max = Math.max(
            i - 1 >= 0 ? leftMax[i - 1] : -Infinity,
            i + 2 <= n - 1 ? rightMax[i + 2] : -Infinity,
        )
        const min = Math.min(
            i - 1 >= 0 ? leftMin[i - 1] : Infinity,
            i + 2 <= n - 1 ? rightMin[i + 2] : Infinity,
        )
        let mergedIsMax = false
        if (merged > max) {
            max = merged
            mergedIsMax = true
        }
        const h1 = Math.floor((max - 1) / 2)
        // const h2 = Math.ceil((max - 1) / 2)
        const last = i < n - 1 ? parts[n] : merged
        // insert into the max or move to last
        let now = Math.max(mergedIsMax ? h1 : Math.min(h1, merged), Math.min(merged, last))
        now = Math.min(min, now)
    // console.log(i, now, ';', min, h1, merged, last)
        //
        ans = Math.max(ans, now)
    })
    return ans
}

'use strict'; /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}
const DEBUG = 1
const l = DEBUG ? console.log : ()=>{};

module.exports = E;

const ra = ()=>readline().split(' ').map(a=>+a)

const EPS = 1e-6;

const cnt_u = arr=>{
  arr.sort((a, b)=>a-b);
  let min_u = Infinity;
  for (let i=0; i<arr.length; i++){
    let prev = i ? arr[i-1] : 0;
    min_u = Math.min(min_u, arr[i]-prev-1);
  }
  return min_u;
};

const get_candidates = (arr, d)=>{
  let n = arr.length;
  let to_try = [];
  let max_u = d-arr[n-1]-1;
  for (let i=0; i<n; i++){
    let prev = i ? arr[i-1] : 0;
    max_u = Math.max(max_u, arr[i]-prev-1);
  }
  for (let i=0; i<n; i++){
    let prev = i ? arr[i-1] : 0;
    if (arr[i]-prev-1 == max_u && max_u>=2){
      to_try.push(prev+Math.ceil(max_u/2));
      if (max_u%2)
        to_try.push(prev+Math.floor(max_u/2));
    }
  }
  return to_try;
}

const calc = (n, d, arr)=>{
  let min_u = Infinity;
  let max_u = d-arr[n-1]-1;
  for (let i=0; i<n; i++){
    let prev = i ? arr[i-1] : 0;
    min_u = Math.min(min_u, arr[i]-prev-1);
    max_u = Math.max(max_u, arr[i]-prev-1);
  }
  let min_i = new Set();
  for (let i=0; i<n; i++){
    let prev = i ? arr[i-1] : 0;
    if (arr[i]-prev-1 == min_u){
      min_i.add(i);
      if (i)
        min_i.add(i-1);
      if (i<n-1)
        min_i.add(i+1);
    }
  }
  if (min_i.size>6)
    return min_u;

  let sarr = new Set(arr);

  for (let i of min_i){
    let ar = arr.slice(0, i).concat(arr.slice(i+1));
    if (ar[0]!=1)
      min_u = Math.max(min_u, cnt_u(ar.concat(1)))
    if (ar[ar.length-1]!=d)
      min_u = Math.max(min_u, cnt_u(ar.concat(d)))
    let to_try = get_candidates(ar, d).slice(0, 10);
    for (let tr of to_try)
      min_u = Math.max(min_u, cnt_u(ar.concat(tr)))
  }
  return min_u;
};

function main() {
    let T = +readline()
    while (T--){
      readline()
      let [n, d] = ra();
      let arr = ra();
      print(calc(n, d, arr));
    }
}

E.calc = calc;

'use strict'; /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}

module.exports = E;

const ra = ()=>readline().split(' ').map(a=>+a)

const EPS = 1e-6;

const cnt_u = arr=>{
  arr.sort((a, b)=>a-b);
  let min_u = Infinity;
  for (let i=0; i<arr.length; i++){
    let prev = i ? arr[i-1] : 0;
    min_u = Math.min(min_u, arr[i]-prev-1);
  }
  return min_u;
};

const get_candidates = (arr, d)=>{
  let n = arr.length;
  let to_try = [];
  let max_u = d-arr[n-1]-1;
  for (let i=0; i<n; i++){
    let prev = i ? arr[i-1] : 0;
    max_u = Math.max(max_u, arr[i]-prev-1);
  }
  for (let i=0; i<n; i++){
    let prev = i ? arr[i-1] : 0;
    if (arr[i]-prev-1 == max_u && max_u>=2){
      to_try.push(prev+Math.ceil(max_u/2));
      if (max_u%2)
        to_try.push(prev+Math.floor(max_u/2));
    }
  }
  return to_try;
}

const calc = (n, d, arr)=>{
  let min_u = Infinity;
  let max_u = d-arr[n-1]-1;
  for (let i=0; i<n; i++){
    let prev = i ? arr[i-1] : 0;
    min_u = Math.min(min_u, arr[i]-prev-1);
    max_u = Math.max(max_u, arr[i]-prev-1);
  }
  let min_i = new Set();
  for (let i=0; i<n; i++){
    let prev = i ? arr[i-1] : 0;
    if (arr[i]-prev-1 == min_u){
      min_i.add(i);
      if (i)
        min_i.add(i-1);
      if (i<n-1)
        min_i.add(i+1);
    }
  }
  //console.log({arr, min_u, max_u, min_i})
  if (min_i.size>3)
    return min_u;

  for (let i of min_i){
    let ar = arr.slice(0, i).concat(arr.slice(i+1));
    if (ar[0]!=1)
      min_u = Math.max(min_u, cnt_u(ar.concat(1)))
    if (ar[ar.length-1]!=d)
      min_u = Math.max(min_u, cnt_u(ar.concat(d)))
    let to_try = get_candidates(ar, d);
    //console.log('CAND', {ar, to_try})
    for (let tr of to_try)
      min_u = Math.max(min_u, cnt_u(ar.concat(tr)))
  }
  return min_u;
};

function main() {
    let T = +readline()
    while (T--){
      readline()
      let [n, d] = ra();
      let arr = ra();
      print(calc(n, d, arr));
    }
}

E.calc = calc;

const TreeMultiSet = (function () {
var{TreeMultiSet:t}=function(t){
/*! *****************************************************************************
        Copyright (c) Microsoft Corporation.

        Permission to use, copy, modify, and/or distribute this software for any
        purpose with or without fee is hereby granted.

        THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
        AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
        LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
        OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
        PERFORMANCE OF THIS SOFTWARE.
        ***************************************************************************** */
var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function r(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function i(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}var s,u=function(){function t(t,e){this.it_=t,this.last_=e}return t.prototype.next=function(){if(this.it_.equals(this.last_))return{done:!0,value:void 0};var t=this.it_;return this.it_=this.it_.next(),{done:!1,value:t.value}},t.prototype[Symbol.iterator]=function(){return this},t}(),a=function(){function t(){}return t.prototype.empty=function(){return 0===this.size()},t.prototype.rbegin=function(){return this.end().reverse()},t.prototype.rend=function(){return this.begin().reverse()},t.prototype[Symbol.iterator]=function(){return new u(this.begin(),this.end())},t.prototype.toJSON=function(){var t,e,n=[];try{for(var o=r(this),i=o.next();!i.done;i=o.next()){var s=i.value;n.push(s)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(e=o.return)&&e.call(o)}finally{if(t)throw t.error}}return n},t}(),c=function(){function t(t,e){this.data_=t,this.index_=e}return t.prototype.index=function(){return this.index_},Object.defineProperty(t.prototype,"value",{get:function(){return this.data_[this.index_]},enumerable:!1,configurable:!0}),t.prototype.prev=function(){return--this.index_,this},t.prototype.next=function(){return++this.index_,this},t.prototype.advance=function(t){return this.index_+=t,this},t.prototype.equals=function(t){return this.data_===t.data_&&this.index_===t.index_},t.prototype.swap=function(t){var e,n;e=o([t.data_,this.data_],2),this.data_=e[0],t.data_=e[1],n=o([t.index_,this.index_],2),this.index_=n[0],t.index_=n[1]},t}(),_=function(t){function e(e){var n=t.call(this)||this;return n.data_=e(n),n}return n(e,t),e.prototype.assign=function(t,e){this.clear(),this.insert(t,e)},e.prototype.clear=function(){this.data_.clear()},e.prototype.begin=function(){return this.data_.begin()},e.prototype.end=function(){return this.data_.end()},e.prototype.has=function(t){return!this.find(t).equals(this.end())},e.prototype.size=function(){return this.data_.size()},e.prototype.push=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(0===t.length)return this.size();var n=new c(t,0),r=new c(t,t.length);return this._Insert_by_range(n,r),this.size()},e.prototype.insert=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 1===t.length?this._Insert_by_key(t[0]):t[0].next instanceof Function&&t[1].next instanceof Function?this._Insert_by_range(t[0],t[1]):this._Insert_by_hint(t[0],t[1])},e.prototype.erase=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 1!==t.length||t[0]instanceof this.end().constructor&&t[0].source()===this?1===t.length?this._Erase_by_range(t[0]):this._Erase_by_range(t[0],t[1]):this._Erase_by_val(t[0])},e.prototype._Erase_by_range=function(t,e){void 0===e&&(e=t.next());var n=this.data_.erase(t,e);return this._Handle_erase(t,e),n},e}(a),l=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.insert=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return t.prototype.insert.apply(this,i([],o(e),!1))},e.prototype._Erase_by_val=function(t){var e=this.find(t);if(!0===e.equals(this.end()))return 0;for(var n=e.next(),r=1;!n.equals(this.end())&&this._Key_eq(t,n.value);)n=n.next(),++r;return this._Erase_by_range(e,n),r},e.prototype.merge=function(t){this.insert(t.begin(),t.end()),t.clear()},e}(_);!function(t){t.construct=function(t){for(var e,n,r=[],s=1;s<arguments.length;s++)r[s-1]=arguments[s];return r.length>=1&&r[0]instanceof Array?(e=function(){var e=r[0];t.push.apply(t,i([],o(e),!1))},n=r.slice(1)):r.length>=2&&r[0].next instanceof Function&&r[1].next instanceof Function?(e=function(){var e=r[0],n=r[1];t.assign(e,n)},n=r.slice(2)):(e=null,n=r),{ramda:e,tail:n}}}(s||(s={}));var h=null;function p(){return null===y&&(null===h&&(h="object"==typeof global&&"object"==typeof global.process&&"object"==typeof global.process.versions&&void 0!==global.process.versions.node),void 0===(y=h?global:self).__s_iUID&&(y.__s_iUID=0)),y}var f,y=null;function v(t){if(t instanceof Object){if(!1===t.hasOwnProperty("__get_m_iUID")){var e=++p().__s_iUID;Object.defineProperty(t,"__get_m_iUID",{value:function(){return e}})}return t.__get_m_iUID()}return void 0===t?-1:0}function d(t,e){return t=t?t.valueOf():t,e=e?e.valueOf():e,t instanceof Object&&t.equals instanceof Function?t.equals(e):t===e}function g(t,e){return t=t.valueOf(),e=e.valueOf(),t instanceof Object?t.less instanceof Function?t.less(e):v(t)<v(e):t<e}function b(t,e){return e^=t?1:0,e*=k}function m(t,e){return x(t.toString(),e)}function x(t,e){for(var n=0;n<t.length;++n)e^=t.charCodeAt(n),e*=k;return Math.abs(e)}!function(t){t.construct=function(t,e,n){for(var r=[],u=3;u<arguments.length;u++)r[u-3]=arguments[u];var a=null,c=g;if(1===r.length&&r[0]instanceof e){var _=r[0];c=_.key_comp(),a=function(){var e=_.begin(),n=_.end();t.assign(e,n)}}else{var l=s.construct.apply(s,i([t],o(r),!1));a=l.ramda,l.tail.length>=1&&(c=l.tail[0])}n(c),null!==a&&a()},t.emplacable=function(t,e,n){var r=e.prev(),o=r.equals(t.end())||t.value_comp()(r.value,n);return o=o&&(e.equals(t.end())||t.value_comp()(n,e.value))}}(f||(f={}));var w,I=2166136261,k=16777619,q=function(){function t(t,e){this.first=t,this.second=e}return t.prototype.equals=function(t){return d(this.first,t.first)&&d(this.second,t.second)},t.prototype.less=function(t){return!1===d(this.first,t.first)?g(this.first,t.first):g(this.second,t.second)},t.prototype.hashCode=function(){return function(){for(var t,e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var i=I;try{for(var s=r(n),u=s.next();!u.done;u=s.next()){var a=u.value,c=typeof(a=a?a.valueOf():a);if("boolean"===c)i=b(a,i);else if("number"===c||"bigint"===c)i=m(a,i);else if("string"===c)i=x(a,i);else if(a instanceof Object&&a.hashCode instanceof Function){var _=a.hashCode();if(1===n.length)return _;i^=_,i*=k}else i=m(v(a),i)}}catch(e){t={error:e}}finally{try{u&&!u.done&&(e=s.return)&&e.call(s)}finally{if(t)throw t.error}}return Math.abs(i)}(this.first,this.second)},t}(),E=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.find=function(t){var e=this.lower_bound(t);return!e.equals(this.end())&&this._Key_eq(t,e.value)?e:this.end()},e.prototype.count=function(t){for(var e=this.find(t),n=0;!e.equals(this.end())&&this._Key_eq(e.value,t);e=e.next())++n;return n},e.prototype.equal_range=function(t){return new q(this.lower_bound(t),this.upper_bound(t))},e.prototype.value_comp=function(){return this.key_comp()},e.prototype._Key_eq=function(t,e){return!this.key_comp()(t,e)&&!this.key_comp()(e,t)},e.prototype._Insert_by_key=function(t){var e=this.upper_bound(t);return e=this.data_.insert(e,t),this._Handle_insert(e,e.next()),e},e.prototype._Insert_by_hint=function(t,e){if(f.emplacable(this,t,e)){var n=this.data_.insert(t,e);return this._Handle_insert(n,n.next()),n}return this._Insert_by_key(e)},e.prototype._Insert_by_range=function(t,e){for(var n=t;!n.equals(e);n=n.next())this._Insert_by_key(n.value)},e}(l),O=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(function(t){function e(e){var n=this.constructor,r=t.call(this,e)||this,o=n.prototype;return Object.setPrototypeOf?Object.setPrototypeOf(r,o):r.__proto__=o,r}return n(e,t),Object.defineProperty(e.prototype,"name",{get:function(){return this.constructor.name},enumerable:!1,configurable:!0}),e.prototype.what=function(){return this.message},e.prototype.toJSON=function(){return{name:this.name,message:this.message,stack:this.stack}},e}(Error)),F=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(O),S=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(O);!function(t){function e(t){if("string"==typeof t)return t;var e=t.constructor.name;return t.constructor.__MODULE&&(e=t.constructor.__MODULE+"."+e),"std."+e}t.get_class_name=e,t.empty=function(t,n){return new S("Error on "+e(t)+"."+n+"(): it's empty container.")},t.negative_index=function(t,n,r){return new S("Error on "+e(t)+"."+n+"(): parametric index is negative -> (index = "+r+").")},t.excessive_index=function(t,n,r,o){return new S("Error on "+e(t)+"."+n+"(): parametric index is equal or greater than size -> (index = "+r+", size: "+o+").")},t.not_my_iterator=function(t,n){return new F("Error on "+e(t)+"."+n+"(): parametric iterator is not this container's own.")},t.erased_iterator=function(t,n){return new F("Error on "+e(t)+"."+n+"(): parametric iterator, it already has been erased.")},t.negative_iterator=function(t,n,r){return new S("Error on "+e(t)+"."+n+"(): parametric iterator is directing negative position -> (index = "+r+").")},t.iterator_end_value=function(t,n){void 0===n&&(n="end");var r=e(t);return new S("Error on "+r+".Iterator.value: cannot access to the "+r+"."+n+"().value.")},t.key_nout_found=function(t,n,r){throw new S("Error on "+e(t)+"."+n+"(): unable to find the matched key -> "+r)}}(w||(w={}));var j=function(){function t(t,e,n){this.prev_=t,this.next_=e,this.value_=n}return t._Set_prev=function(t,e){t.prev_=e},t._Set_next=function(t,e){t.next_=e},t.prototype.prev=function(){return this.prev_},t.prototype.next=function(){return this.next_},Object.defineProperty(t.prototype,"value",{get:function(){return this._Try_value(),this.value_},enumerable:!1,configurable:!0}),t.prototype._Try_value=function(){if(void 0===this.value_&&!0===this.equals(this.source().end()))throw w.iterator_end_value(this.source())},t.prototype.equals=function(t){return this===t},t}(),z=function(){function t(t,e){this.index_=t,this.value_=e}return t.prototype.index=function(){return this.index_},Object.defineProperty(t.prototype,"value",{get:function(){return this.value_},enumerable:!1,configurable:!0}),t.prototype.next=function(){return++this.index_,this},t.prototype.equals=function(t){return this.index_===t.index_},t}();var R=function(t){function e(){var e=t.call(this)||this;return e.end_=e._Create_iterator(null,null),e.clear(),e}return n(e,t),e.prototype.assign=function(t,e){this.clear(),this.insert(this.end(),t,e)},e.prototype.clear=function(){j._Set_prev(this.end_,this.end_),j._Set_next(this.end_,this.end_),this.begin_=this.end_,this.size_=0},e.prototype.resize=function(t){var e=t-this.size();e>0?this.insert(this.end(),e,void 0):e<0&&this.erase(function(t,e){if(0===e)return t;if(t.advance instanceof Function)return t.advance(e);var n;if(e<0){if(!(t.prev instanceof Function))throw new F("Error on std.advance(): parametric iterator is not a bi-directional iterator, thus advancing to negative direction is not possible.");n=function(t){return t.prev()},e=-e}else n=function(t){return t.next()};for(;e-- >0;)t=n(t);return t}(this.end(),-e),this.end())},e.prototype.begin=function(){return this.begin_},e.prototype.end=function(){return this.end_},e.prototype.size=function(){return this.size_},e.prototype.push_front=function(t){this.insert(this.begin_,t)},e.prototype.push_back=function(t){this.insert(this.end_,t)},e.prototype.pop_front=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,"pop_front");this.erase(this.begin_)},e.prototype.pop_back=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,"pop_back");this.erase(this.end_.prev())},e.prototype.push=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(0===t.length)return this.size();var n=new c(t,0),r=new c(t,t.length);return this._Insert_by_range(this.end(),n,r),this.size()},e.prototype.insert=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t.source()!==this.end_.source())throw w.not_my_iterator(this.end_.source(),"insert");if(!0===t.erased_)throw w.erased_iterator(this.end_.source(),"insert");return 1===e.length?this._Insert_by_repeating_val(t,1,e[0]):2===e.length&&"number"==typeof e[0]?this._Insert_by_repeating_val(t,e[0],e[1]):this._Insert_by_range(t,e[0],e[1])},e.prototype._Insert_by_repeating_val=function(t,e,n){var r=new z(0,n),o=new z(e);return this._Insert_by_range(t,r,o)},e.prototype._Insert_by_range=function(t,e,n){for(var r=t.prev(),o=null,i=0,s=e;!1===s.equals(n);s=s.next()){var u=this._Create_iterator(r,null,s.value);0===i&&(o=u),j._Set_next(r,u),r=u,++i}return!0===t.equals(this.begin())&&(this.begin_=o),j._Set_next(r,t),j._Set_prev(t,r),this.size_+=i,o},e.prototype.erase=function(t,e){return void 0===e&&(e=t.next()),this._Erase_by_range(t,e)},e.prototype._Erase_by_range=function(t,e){if(t.source()!==this.end_.source())throw w.not_my_iterator(this.end_.source(),"insert");if(!0===t.erased_)throw w.erased_iterator(this.end_.source(),"insert");if(t.equals(this.end_))return this.end_;var n=t.prev();j._Set_next(n,e),j._Set_prev(e,n);for(var r=t;!r.equals(e);r=r.next())r.erased_=!0,--this.size_;return t.equals(this.begin_)&&(this.begin_=e),e},e.prototype.swap=function(t){var e,n,r;e=o([t.begin_,this.begin_],2),this.begin_=e[0],t.begin_=e[1],n=o([t.end_,this.end_],2),this.end_=n[0],t.end_=n[1],r=o([t.size_,this.size_],2),this.size_=r[0],t.size_=r[1]},e}(a),P=function(){function t(t){this.base_=t.prev()}return t.prototype.source=function(){return this.base_.source()},t.prototype.base=function(){return this.base_.next()},Object.defineProperty(t.prototype,"value",{get:function(){return this.base_.value},enumerable:!1,configurable:!0}),t.prototype.prev=function(){return this._Create_neighbor(this.base().next())},t.prototype.next=function(){return this._Create_neighbor(this.base_)},t.prototype.equals=function(t){return this.base_.equals(t.base_)},t}(),C=function(t){function e(e){var n=t.call(this)||this;return n.associative_=e,n}return n(e,t),e.prototype._Create_iterator=function(t,n,r){return e.Iterator.create(this,t,n,r)},e._Swap_associative=function(t,e){var n;n=o([e.associative_,t.associative_],2),t.associative_=n[0],e.associative_=n[1]},e.prototype.associative=function(){return this.associative_},e}(R);!function(t){var e=function(t){function e(e,n,r,o){var i=t.call(this,n,r,o)||this;return i.source_=e,i}return n(e,t),e.create=function(t,n,r,o){return new e(t,n,r,o)},e.prototype.reverse=function(){return new r(this)},e.prototype.source=function(){return this.source_.associative()},e}(j);t.Iterator=e;var r=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype._Create_neighbor=function(t){return new e(t)},e}(P);t.ReverseIterator=r}(C||(C={}));var M=function(){function t(t,e){this.value=t,this.color=e,this.parent=null,this.left=null,this.right=null}return Object.defineProperty(t.prototype,"grand",{get:function(){return this.parent.parent},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sibling",{get:function(){return this===this.parent.left?this.parent.right:this.parent.left},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uncle",{get:function(){return this.parent.sibling},enumerable:!1,configurable:!0}),t}(),D=function(t){function e(e,n){return t.call(this,e,n,(function(t,e){var r=n(t.value,e.value);return r||n(e.value,t.value)?r:v(t)<v(e)}))||this}return n(e,t),e.prototype.insert=function(e){v(e),t.prototype.insert.call(this,e)},e.prototype._Nearest_by_key=function(t,e){if(null===this.root_)return null;for(var n=this.root_,r=null;;){var o=n.value,i=null;if(this.key_comp()(t,o.value)?i=n.left:this.key_comp()(o.value,t)?i=n.right:(r=n,i=e(n)),null===i)break;n=i}return null!==r?r:n},e.prototype.nearest_by_key=function(t){return this._Nearest_by_key(t,(function(t){return t.left}))},e.prototype.upper_bound=function(t){var e=this._Nearest_by_key(t,(function(t){return t.right}));if(null===e)return this.source().end();var n=e.value;return this.key_comp()(t,n.value)?n:n.next()},e}(function(t){function e(e,n,r){var o=t.call(this,r)||this;return o.source_=e,o.key_comp_=n,o.key_eq_=function(t,e){return!n(t,e)&&!n(e,t)},o}return n(e,t),e._Swap_source=function(t,e){var n;n=o([e.source_,t.source_],2),t.source_=n[0],e.source_=n[1]},e.prototype.get_by_key=function(t){var e=this.nearest_by_key(t);return null!==e&&this.key_eq_(t,e.value.value)?e:null},e.prototype.lower_bound=function(t){var e=this.nearest_by_key(t);return null===e?this.source_.end():this.key_comp_(e.value.value,t)?e.value.next():e.value},e.prototype.equal_range=function(t){return new q(this.lower_bound(t),this.upper_bound(t))},e.prototype.source=function(){return this.source_},e.prototype.key_comp=function(){return this.key_comp_},e.prototype.key_eq=function(){return this.key_eq_},e.prototype.value_comp=function(){return this.key_comp_},e}(function(){function t(t){this.root_=null,this.comp_=t,this.equal_=function(e,n){return!t(e,n)&&!t(n,e)}}return t.prototype.clear=function(){this.root_=null},t.prototype.root=function(){return this.root_},t.prototype.get=function(t){var e=this.nearest(t);return null!==e&&this.equal_(t,e.value)?e:null},t.prototype.nearest=function(t){if(null===this.root_)return null;for(var e=this.root_;;){var n=null;if(this.comp_(t,e.value))n=e.left;else{if(!this.comp_(e.value,t))return e;n=e.right}if(null===n)break;e=n}return e},t.prototype._Fetch_maximum=function(t){for(;null!==t.right;)t=t.right;return t},t.prototype.insert=function(t){var e=this.nearest(t),n=new M(t,1);null===e?this.root_=n:(n.parent=e,this.comp_(n.value,e.value)?e.left=n:e.right=n),this._Insert_case1(n)},t.prototype._Insert_case1=function(t){null===t.parent?t.color=0:this._Insert_case2(t)},t.prototype._Insert_case2=function(t){0!==this._Fetch_color(t.parent)&&this._Insert_case3(t)},t.prototype._Insert_case3=function(t){1===this._Fetch_color(t.uncle)?(t.parent.color=0,t.uncle.color=0,t.grand.color=1,this._Insert_case1(t.grand)):this._Insert_case4(t)},t.prototype._Insert_case4=function(t){t===t.parent.right&&t.parent===t.grand.left?(this._Rotate_left(t.parent),t=t.left):t===t.parent.left&&t.parent===t.grand.right&&(this._Rotate_right(t.parent),t=t.right),this._Insert_case5(t)},t.prototype._Insert_case5=function(t){t.parent.color=0,t.grand.color=1,t===t.parent.left&&t.parent===t.grand.left?this._Rotate_right(t.grand):this._Rotate_left(t.grand)},t.prototype.erase=function(t){var e=this.get(t);if(null!==e){if(null!==e.left&&null!==e.right){var n=this._Fetch_maximum(e.left);e.value=n.value,e=n}var r=null===e.right?e.left:e.right;0===this._Fetch_color(e)&&(e.color=this._Fetch_color(r),this._Erase_case1(e)),this._Replace_node(e,r),1===this._Fetch_color(this.root_)&&(this.root_.color=0)}},t.prototype._Erase_case1=function(t){null!==t.parent&&this._Erase_case2(t)},t.prototype._Erase_case2=function(t){1===this._Fetch_color(t.sibling)&&(t.parent.color=1,t.sibling.color=0,t===t.parent.left?this._Rotate_left(t.parent):this._Rotate_right(t.parent)),this._Erase_case3(t)},t.prototype._Erase_case3=function(t){0===this._Fetch_color(t.parent)&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,this._Erase_case1(t.parent)):this._Erase_case4(t)},t.prototype._Erase_case4=function(t){1===this._Fetch_color(t.parent)&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,t.parent.color=0):this._Erase_case5(t)},t.prototype._Erase_case5=function(t){t===t.parent.left&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&1===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,t.sibling.left.color=0,this._Rotate_right(t.sibling)):t===t.parent.right&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&1===this._Fetch_color(t.sibling.right)&&(t.sibling.color=1,t.sibling.right.color=0,this._Rotate_left(t.sibling)),this._Erase_case6(t)},t.prototype._Erase_case6=function(t){t.sibling.color=this._Fetch_color(t.parent),t.parent.color=0,t===t.parent.left?(t.sibling.right.color=0,this._Rotate_left(t.parent)):(t.sibling.left.color=0,this._Rotate_right(t.parent))},t.prototype._Rotate_left=function(t){var e=t.right;this._Replace_node(t,e),t.right=e.left,null!==e.left&&(e.left.parent=t),e.left=t,t.parent=e},t.prototype._Rotate_right=function(t){var e=t.left;this._Replace_node(t,e),t.left=e.right,null!==e.right&&(e.right.parent=t),e.right=t,t.parent=e},t.prototype._Replace_node=function(t,e){null===t.parent?this.root_=e:t===t.parent.left?t.parent.left=e:t.parent.right=e,null!==e&&(e.parent=t.parent)},t.prototype._Fetch_color=function(t){return null===t?0:t.color},t}()));return t.TreeMultiSet=function(t){function e(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var s=t.call(this,(function(t){return new C(t)}))||this;return f.construct.apply(f,i([s,e,function(t){s.tree_=new D(s,t)}],o(n),!1)),s}return n(e,t),e.prototype.clear=function(){t.prototype.clear.call(this),this.tree_.clear()},e.prototype.swap=function(t){var e,n;e=o([t.data_,this.data_],2),this.data_=e[0],t.data_=e[1],C._Swap_associative(this.data_,t.data_),D._Swap_source(this.tree_,t.tree_),n=o([t.tree_,this.tree_],2),this.tree_=n[0],t.tree_=n[1]},e.prototype.key_comp=function(){return this.tree_.key_comp()},e.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},e.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},e.prototype._Handle_insert=function(t,e){for(;!t.equals(e);t=t.next())this.tree_.insert(t)},e.prototype._Handle_erase=function(t,e){for(;!t.equals(e);t=t.next())this.tree_.erase(t)},e}(E),function(t){t.Iterator=C.Iterator,t.ReverseIterator=C.ReverseIterator}(t.TreeMultiSet||(t.TreeMultiSet={})),Object.defineProperty(t,"__esModule",{value:!0}),t}({});

return t
})();

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
lines.push(input);
})
rl.on('close', () => {
// (function() {
// const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
let l = 0;
let t = +lines[l++]
const output = []
for (let i = 0; i < t; i++) {
l++
const [n, d] = lines[l++].trim().split(' ').map(Number)
const arr = lines[l++].trim().split(' ').map(Number)
output[i] = solve(n, d, arr)
}
console.log(output.join('\n'))
// })()
})

function solve(n, d, arr) {
    const set = new TreeMultiSet((a, b) => {
        if (a[0] === b[0]) {
            return a[1] < b[1]
        } else {
            return a[0] < b[0]
        }
    })
    const parts = Array(n + 1)
    arr.forEach((x, i) => {
        parts[i] = [i ? x - arr[i - 1] - 1 : x - 1, i]
        set.insert(parts[i])
    })
    parts[n] = [d - arr[n - 1] - 1, n]
    // set.insert(parts[n])
    // console.log(set.size())
    // return
    let ans = -Infinity
    arr.forEach((x, i) => {
    // console.log('0:', print(set))
        const a = parts[i]
        const b = parts[i + 1]
        const c = [a[0] + b[0] + 1, n + 1]
        set.erase(a)
        set.erase(b)
        set.insert(c)
    // console.log('1:', print(set))
        //
        const max = set.rbegin().value
        const h1 = [Math.floor((max[0] - 1) / 2), n + 2]
        const h2 = [Math.ceil((max[0] - 1) / 2), n + 3]
        if (h1[0] > parts[n][0]) {
            set.erase(max)
            set.insert(h1)
            set.insert(h2)
        } else {
            set.insert(parts[n])
        }
    // console.log('2:', print(set))
        ans = Math.max(ans, set.begin().value[0])

        // recover
        if (h1[0] > parts[n][0]) {
            set.insert(max)
            set.erase(h1)
            set.erase(h2)
        } else {
            set.erase(parts[n])
        }
        set.insert(a)
        set.insert(b)
        set.erase(c)
    // console.log('3:', print(set))
    })
    return ans
}
function print(set) {
    let iter = set.begin()
    const temp = []
    while (iter !== set.end()) {
        temp.push(iter.value[0])
        iter = iter.next()
    }
    return temp.join(' ')
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(BigInt)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    const limit = 3000
    const dp = Array(n + 1).fill(0)
        .map(() => Array(limit + 2).fill(0))
    // dp[n] = dp[n].fill(1)
    // for (let i = arr.length - 1; i >= 0; i--) {
    //     for (let mod = limit; mod >= 1; mod--) {
    //         let sum = 0
    //         for (let j = i; j < arr.length; j++) {
    //             sum += arr[j]
    //             if (!(sum % mod)) {
    //                 dp[i][mod] = add(dp[i][mod], dp[j + 1][mod + 1])
    //             }
    //         }
    //     }
    // }
    const sum = Array(n)
    arr.forEach((x, i) => {
        sum[i] = i ? sum[i - 1] + x : x
    })
    let ans = 0
    for (let mod = 1; mod <= limit; mod++) {
        const temp = Array(mod + 1).fill(0)
        for (let i = 0; i < arr.length; i++) {
            if (mod === 1) {
                dp[i][mod] = 1
            }
            const r = Number(sum[i] % BigInt(mod + 1))
            dp[i][mod + 1] = temp[r]
            temp[r] = add(temp[r], dp[i][mod])
            //
            if (i === n - 1) {
                ans = add(ans, dp[i][mod])
            }
        }
        // console.log(temp)
    }
    // console.log(dp)
    return ans
    // return dp[0][1]
}
// function helperWithCache(arr, idx, mod) {
//     const k = idx + ',' + mod
//     if (!CACHE[k]) {
//         CACHE[k] = helper(arr, idx, mod)
//     }
//     return CACHE[k]
// }
// function helper(arr, idx, mod) {
//     if (idx === arr.length) return 1

//     let sum = 0n
//     let ans = 0
//     for (let i = idx; i < arr.length; i++) {
//         sum += arr[i]
//         if (!(sum % mod)) {
//             ans = add(ans, helperWithCache(arr, i + 1, mod + 1n))
//         }
//     }
//     return ans
// }
const MOD = 1e9 + 7
function add(a, b) {
    return (a + b) % MOD
}


MAX = 100010
MAX2 = MAX/2;

counts = [];
sums = [];
n = +readline();
for (i = 0; i <= MAX; i++) {
    sums[i] = counts[i] = 0;
}

array = readline().split(' ');
for (i = 0; i < n; i++) {
    n2 = n1 = +array[i];
    counts[n1]++;

    mulOps = 0;
    while (n1 < MAX2) {
        n1 <<= 1;
        mulOps++;
        counts[n1]++;
        sums[n1] += mulOps;
    }

    divideOps = 0;
    while (n2 > 1) {
        odd = (n2 & 1) === 1;
        n2 >>= 1;
        divideOps++;
        counts[n2]++;
        sums[n2] += divideOps;
        if (odd) {
            n3 = n2;
            ops = divideOps;
            while (n3 < MAX2) {
                n3 <<= 1;
                ops++;
                counts[n3]++;
                sums[n3] += ops;
            }
        }
    }
}

minSum = sums[1];
for (i = 1; i < MAX; i++) {
    if (counts[i] == n && minSum > sums[i]) {
        minSum = sums[i];
    }
}

print(minSum);

function calcBits(n) {
  var res = [];
  while (n) {
    res.push(n & 1);
    n >>= 1;
  }
  return res.reverse();
}

var n = parseInt(readline().split());
var a = readline().split(' ').map((x) => parseInt(x));
var maxs = 0;
for (var i = 0; i < n; ++ i) {
  maxs = Math.max(maxs, a[i]);
}
var cnt = new Array(maxs + 1);
var cntSteps = new Array(maxs + 1);
cnt.fill(0);
cntSteps.fill(0);
for (var i = 0; i < n; ++ i) {
  var bits = calcBits(a[i]);
  var num = 0;
  for (var j = 0; j < bits.length; ++ j) {
    var cur = (num << 1) + bits[j];
    ++ cnt[cur];
    cntSteps[cur] += bits.length - j - 1;
    if (num && bits[j] == 1) {
      cur = num << 1;
      for (var k = bits.length - j + 1; cur <= maxs; ++ k, cur <<= 1) {
        ++ cnt[cur];
        cntSteps[cur] += k;
      }
    }
    num = (num << 1) + bits[j];
  }
  num <<= 1;
  for (var j = 1; num <= maxs; ++ j, num <<= 1) {
    ++ cnt[num];
    cntSteps[num] += j;
  }
}
var ans = 1 << 30;
for (var i = 1; i <= maxs; ++ i) {
  if (cnt[i] == n) {
    ans = Math.min(ans, cntSteps[i]);
  }
}
print(ans);

var n = parseInt(readline().split());
var a = readline().split(' ').map((x) => parseInt(x));
a.sort();
var maxs = a[n - 1];
var cnt = new Array(maxs + 1);
var cntSteps = new Array(maxs + 1);
cnt.fill(0);
cntSteps.fill(0);
for (var i = 0; i < n; ++ i) {
  var num = a[i];
  var initSteps = 0;
  while (num) {
    for (var next = num, steps = 0; next <= maxs; next <<= 1, ++ steps) {
      ++ cnt[next];
      cntSteps[next] += initSteps + steps;
    }
    while (num && (num & 1) == 0) {
      num >>= 1;
      ++ initSteps;
      ++ cnt[num];
      cntSteps[num] += initSteps;
    }
    ++ initSteps;
    num >>= 1;
  }
}
var ans = 1 << 30;
for (var i = 1; i <= maxs; ++ i) {
  if (cnt[i] == n) {
    ans = Math.min(ans, cntSteps[i]);
  }
}
print(ans);

var n = parseInt(readline().split());
var a = readline().split(' ').map((x) => parseInt(x));
a.sort();
var maxs = a[n - 1];
var f = new Array(maxs + 1);
var b = new Array(maxs + 1);
var cntf = new Array(maxs + 1);
var cntb = new Array(maxs + 1);
f.fill(0);
b.fill(0);
cntf.fill(0);
cntb.fill(0);
for (var i = 0; i < n; ++ i) {
  ++ f[a[i]];
  for (var num = a[i] << 1, steps = 1; num <= maxs; num <<= 1, ++ steps) {
    cntf[num] += steps;
    ++ f[num];
  }
}
for (var i = n - 1; i >= 0; -- i) {
  ++ b[a[i]];
  for (var num = a[i] >> 1, steps = 1; num > 0; num >>= 1, ++ steps) {
    cntb[num] += steps;
    ++ b[num];
  }
}
var occur = new Array(maxs + 1);
occur.fill(0);
for (var i = 0; i < n; ++ i) {
  ++ occur[a[i]];
}
var ans = 1 << 30;
for (var i = 1; i <= maxs; ++ i) {
  if (f[i] + b[i] - occur[i] == n) {
    ans = Math.min(ans, cntf[i] + cntb[i]);
  }
}
print(ans);

MAX = 0x40000;
FLAG = 0x3ffff;

counts = [];
sums = [];
n = +readline();
for (i = 0; i <= MAX; i++) {
    sums[i] = counts[i] = 0;
}
readline().split(' ').forEach(function(number) {
    n1 = +number;
    mulOps = 0;
    while (n1 < MAX) {
        n1 <<= 1;
        mulOps++;
        counts[n1 & FLAG]++;
        sums[n1 & FLAG] += mulOps;
    }

    divideOps = 0;
    n2 = +number;
    counts[n2]++;
    while (n2 > 1) {
        odd = (n2 & 1);
        n2 >>= 1;
        divideOps++;
        counts[n2 & FLAG]++;
        sums[n2 & FLAG] += divideOps;
        if (odd) {
            n3 = n2;
            ops = divideOps;
            while (n3 < MAX) {
                n3 <<= 1;
                ops++;
                counts[n3 & FLAG]++;
                sums[n3 & FLAG] += ops;
            }
        }
    }
})

minSum = sums[1];
for (i = 1; i < MAX; i++) {
    if (counts[i] == n && minSum > sums[i]) {
        minSum = sums[i];
    }
}

print(minSum);

Node = function(position, value) {
    this.position = position;
    this.value = value;
    this.toString = function() {
        return '(' + this.position + ', ' + this.value + ')';
    };
};

n = +readline();
numbers = readline().split(' ');
nodes = [];
for (i = 0; i < n; i++) {
    nodes[i] = new Node(i, +numbers[i]);
}
nodes.sort(function(n1, n2) {
    if (n1.value != n2.value) return n1.value - n2.value;
    return n1.position - n2.position;
});

max = 1;
mright = mleft = nodes[0].position;
count = 1;
left = right = nodes[0].position;
for (i = 1; i < n; i++) {
    if (nodes[i].value != nodes[i - 1].value) {
        left = right = nodes[i].position;
        count = 1;
    } else {
        right = nodes[i].position;
        count++;
    }
    if (max < count) {
        max = count;
        mleft = left;
        mright = right;
    } else if (max == count && mright - mleft > right - left) {
        mleft = left;
        mright = right;
    }

}

print((mleft + 1) + ' ' + (mright + 1));


let data = '';
process.stdin.on('data', c => data += c);

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i < t; i++){
		let s = nl.num();
		let m = 0;
		let x = 1;
		while(s > 0) {
			s -= x;
			m++;
			x += 2;
		}
		ans.push(m);

	}
	console.log(ans.join('\n'));
};

process.stdin.on('end', sol);

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(str => str.trim());

    main();
});

function readLine() {
    return inputString[currentLine++];
}
function main()
{
    //const name=readLine();
    //console.log(name);

    let test=readLine();
    while(test--)
    {
        let s=readLine();
        s--;
        val=3;
        cnt=1;
        while(s-val>=0)
        {
            s-=val;
            val+=2;
            cnt++;
        }
        if(s>0)
            cnt++;
        console.log(cnt);
    }
}

/***
Educational Codeforces Round 111 (Div. 2)
2021-07-14

A. Find the Array
***/

function main() {
  var t = readline();
  t = parseInt(t);
  var s; // avoid re-reading same line
  for (var i = 0; i < t; i++) {
    s = readline();
    s = parseInt(s);

    // Max case: [1, 3, 5, ...]
    var ans = Math.ceil(Math.sqrt(s));
    print(ans);
  }
}

main();

var x = parseInt(readline());

for(i = 0; i < x; i++)
{
    var s = parseInt(readline());
    print(Math.ceil(Math.sqrt(s)));
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(j =1 ;j <= n;j ++){
        console.log(Math.ceil(Math.sqrt(lines[j])))
    }
});

let q = '';
process.stdin.on('data', c => q += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = q.split(EOL);
    var t = lines[0];
    var e = 0;
    for(i = 1; i <= t; i++){
        var k = lines[i];
        var ans = Math.ceil(Math.sqrt(k));
        console.log(ans);
    }
});

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

var currentLine = 0;
var inputString = "";

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

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

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

/******** Main function *************/

function main() {
  const t = +input();

  for (let i = 0; i < t; i++) {
    let n = +input();

    let total = 0;
    let num = 1;

    while (n > 0) {
      total++;
      n -= num;
      num += 2;
    }
    console.log(total);
  }
}

const stdin = process.openStdin();
let content = '';

stdin.addListener('data', (data) => {
          content += data;
})

stdin.addListener('end', () => {
          content = content.split('\n');
          content.shift();
          content = content.map((string) => string.substring(0, string.length - 1));
          content.pop();
          content = content.map(string => parseInt(string));
          content.forEach((num) => console.log(isBeautiful(num)));
})

const isBeautiful = (num) => {
          let sum = 1;
          let i = 1;
          let ans = 1;
          while (sum < num) {
                   i += 2;
                   sum += i;
                   ans++;
          }
          return ans;
}

const main = () => {
  let t = readInt();
  while (t--) {
    const s = readInt();
    let left = 1;
    let right = s;
    let res = 0;
    while (left <= right) {
      const mid = Math.floor((left + right) / 2);
      if (mid * mid - s >= 0) {
        res = mid;
        right = mid - 1;
      } else {
        left = mid + 1;
      }
    }
    console.log(res);
  }
};

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,
  terminal: false
});
let c = 0;
let n;

rl.on('line', (d) => {
  if (c === 0) {
    n = +d;
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  const sum = arr.reduce((a, b) => a + b, 0);
  const ans = n * (n + 1) / 2 - sum;
  // arr.sort((a, b) => a - b);
  // let ans = -1;

  // for (let i = 1; i <= n; i++) {
  //   if (i !== arr[i - 1]) {
  //     ans = i;
  //     break;
  //   }
  // }

  console.log(ans);

  c++;
});

var info = readline().split(' ').map(Number);
var Arr = readline().split(' ').map(Number);
var sNum = 0;
var sortArr = Arr.sort(function(a,b){return a-b;});
for (i=0; i<info-2; i++) {
    if (sortArr[i+1] - sortArr[i] != 1) {
        sNum = sortArr[i]+1;
    }
}
if (sNum !=0) {
    print(sNum);
}
else if (sortArr[0] != 1) {
print(1);
}
else {
print(info);
}

'use strict';

/*let input = `
10
3 8 10 1 7 9 6 5 2
`.trim().split('\n');
function print(output) {
	console.log(output);
}
function readline() {
	return input.shift();
}*/

//code

var n = Number(readline());
var sum = readline().split(' ').map(Number).reduce(function (acc, curr) {
	return acc + curr;
}, 0);
print(n * (n + 1) / 2 - sum);

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
let n;

rl.on('line', (d) => {
  if (c === 0) {
    n = +d;
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => a - b);
  let ans = -1;

  for (let i = 1; i <= n; i++) {
    if (i !== arr[i - 1]) {
      ans = i;
      break;
    }
  }

  console.log(ans);

  c++;
});

const n = Number(readline());
const numbers = readline().split(" ").map(x => Number(x) - 1).sort((a, b) => a > b ? 1 : a < b ? -1 : 0);
print(numbers.findIndex((value, index) => value !== index) + 1 || n);

'use strict';

// let inpFileStrArr = `
// 10
// 3 8 10 1 7 9 6 5 2
// `.trim().split('\n'), inpFileCounter = 0;
// function readline() {
//   return inpFileStrArr[inpFileCounter++];
// }
// function print(x) {
//   console.log(x);
// }

var n = Number(readline());
var sum = readline().split(' ').map(Number).reduce(function (a, b) {
  return a + b;
}, 0);

print(n * (n + 1) / 2 - sum);

var m = parseInt(readline());
var sum = (m + 1) / 2 * m;
var line = readline().split(' ');
for (var i = 0; i < line.length; ++i) {
    sum -= parseInt(line[i]);
}
print(sum);

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
let n;

rl.on('line', (d) => {
  if (c === 0) {
    n = +d;
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => a - b);
  let ans = -1;

  for (let i = 1; i < arr.length; i++) {
    if (i !== arr[i - 1]) {
      ans = i;
      break;
    }
  }

  console.log(ans);

  c++;
});

const n = Number(readline());
const numbers = readline().split(" ").map(x => Number(x) - 1).sort((a, b) => a > b ? 1 : a < b ? -1 : 0);
print(numbers.findIndex((value, index) => value !== index) + 1);

var info = readline().split(' ').map(Number);
var Arr = readline().split(' ').map(Number);
var numSeries = 0;
var sortArr = Arr.sort(function(a,b){return a-b;});
for (i=0; i<info-2; i++) {
    if (sortArr[i]+1 != sortArr[i+1]) {
        numSeries = sortArr[i]+1;
    }
}
print(numSeries);


'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(0, -1)
  const I = ils[0]
  const F = {}
  for (let i = 2; i < ils.length; i++) {
    const l = ils[i].replace(/'s/, '').split(' ')
    const n1 = l[0]
    const n2 = l[2] == 'on' ? l[3] : l[2]
    if (n1 == I || n2 == I) {
      const n = n1 == I ? n2 : n1
      F[n] = F[n] || 0
      const a = l[1]
           if (a == 'posted'   ) F[n] += 15
      else if (a == 'commented') F[n] += 10
      else if (a == 'likes'    ) F[n] += 5
    } else {
      F[n1] = F[n1] || 0
      F[n2] = F[n2] || 0
    }
  }
  const Fa = []
  for (let n in F) Fa.push([n, F[n]])
  Fa.sort((a, b) => (b[1] - a[1]) || (b[0] < a[0] ? 1 : -1))
  console.log(Fa.map(([n]) => n).join('\n'))
})

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(0, -1)
  const I = ils[0]
  const F = {}
  for (let i = 2; i < ils.length; i++) {
    const l = ils[i].replace(/'s/, '').split(' ')
    const n1 = l[0]
    const n2 = l[2] == 'on' ? l[3] : l[2]
    if (n1 == I || n2 == I) {
      const n = n1 == I ? n2 : n1
      const a = l[1]
      if (a == 'posted'   ) F[n] += 15
      else if (a == 'commented') F[n] += 10
      else if (a == 'likes'    ) F[n] += 5
    } else {
      F[n1] = F[n1] || 0
      F[n2] = F[n2] || 0
    }
  }
  const Fa = []
  for (let n in F) Fa.push([n, F[n]])
  Fa.sort((a, b) => b[1] - a[1])
  console.log(Fa.map(([n]) => n).join('\n'))
})


function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function main() {
	var integers = tokenizeIntegers(readline());
	var platformNum = integers[0], hopLength = integers[1],
		totalLength = integers[2], platformLength = integers[3];
	var gapLength = totalLength - platformLength;

	var visited = new Array(totalLength+1);
	visited[0] = true;
	var distance = 0;

	while (true) {
		distance += hopLength;
		var position = distance % totalLength;
		if (position > platformLength) {
			print(distance);
			return;
		}
		if (visited[position]) {
			var distance = Math.floor(platformNum*totalLength / hopLength) *
					hopLength;
			if (distance < platformNum*totalLength) {
				distance += hopLength;
			}
			print(distance);
			return;
		}
		visited[position] = true;
	}
}

main();

'use strict'

let lll = readline().split(' ').map(v => parseInt(v))

const N = lll[0]
const D = lll[1]
const M = lll[2]
const L = lll[3]

const MAX = (N - 1) * M + L

let cur = 0
let d = D

;(function () {
  while (true) {
    cur += D
    if (cur > MAX) return print(cur)

    let pop = d % M
    if (pop + D <= L) {
      let ss = Math.floor((L - pop) / D)
      cur += D * ss
      d += D * ss
      pop += D * ss
    }
    if (pop > L) return print(cur)
    d = D + pop
  }
})()


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();
    let l = 3;
    const arr = [];
    while (l--) {
      const nums = readLine()
        .split(" ")
        .map((n) => parseInt(n));
      arr.push(nums);
    }
    const result = [];
    for (let col = 0; col < len; col++) {
      for (let row = 0; row < 3; row++) {
        if (!result.length) {
          result.push(arr[0][0]);
          break;
        } else {
          if (result[col - 1] !== arr[row][col]) {
            result.push(arr[row][col]);
            break;
          }
        }
      }
    }
    if (result[0] === result[len - 1]) {
      for (let i = 0; i < 3; i++) {
        const num = arr[i][len - 1];
        if (result[len - 2] !== num && num !== result[0]) {
          result[len - 1] = num;
          break;
        }
      }
    }

    console.log(result.join(" "));
  }
}

#!/usr/bin/env node
'use strict';

const { createInterface } = require('readline');
const rl = createInterface({
  input: process.stdin,
  crlfDelay: Infinity
});

const buf = [];
const prom = [];
let maxBuf = 0;
let maxProm = 0;
rl.on('line', (line) => {
  if (prom.length > 0) {
    maxProm = Math.max(maxProm, prom.length);
    const [resolve, reject] = prom.shift();
    resolve(line);
  } else {
    rl.pause();
    buf.push(line);
    maxBuf = Math.max(maxBuf, buf.length);
  }
});

rl.on('close', () => {
  // console.error({maxProm, maxBuf});
});

async function getLine() {
  return new Promise((resolve, reject) => {
    if (buf.length > 0) {
      const line = buf.shift();
      resolve(line);
    } else {
      prom.push([resolve, reject]);
      rl.resume();
    }
  });
}

/**
 *
 * @param {Number []} a
 * @param {Number []} b
 * @param {Number []} c
 * @returns {Number []}
 */
function solve(a, b, c) {
  const n = a.length;
  const inp = [a, b, c];
  const res = [a[0]];
  for (let i = 1; i < n; i++) {
    for (let j = 0; j < 3; j++) {
      if (res[i-1] === inp[j][i]) continue;
      res[i] = inp[j][i];
      break;
    }
  }
  if (res[n-1] === res[0]) {
    for (let i = 0; i < 3; i++) {
      const t = inp[i][n-1];
      if (res[n-2] === t || res[0] === t) {
        continue;
      }
      res[n-1] = t;
      break;
    }
  }
  return res;
}

async function main() {
  const t = Number(await getLine());
  for (let i = 0; i < t; i++) {
    const n = Number(await getLine());
    const a = (await getLine()).split(' ').map(Number);
    const b = (await getLine()).split(' ').map(Number);
    const c = (await getLine()).split(' ').map(Number);
    const res = solve(a, b, c);
    console.log(res.join(' '));
  }
}

if (require.main === module) {
  main();
}

var total  = parseInt(readline());

while (total-- ) {
    var n = parseInt(readline());
    var values = [];

    for (var i = 0; i < 3; i++) {
        values.push(readline().split(" ").map(Number));
    }

    var exclude = values[0][0];
    var first = values[0][0];
    var result = [exclude];

    for (var i = 1; i < n; i++) {
        for (var j = 0; j < 3; j++) {
            if (values[j][i] !== exclude) {
                if (i === n - 1 && first === values[j][i]) {
                    continue;
                } else {
                    result.push(values[j][i]);
                    exclude = values[j][i];
                    break;
                }
            }
        }
    }

    print(result.join(" "));
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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 output = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var alist = nextIntArray();
    var blist = nextIntArray();
    var clist = nextIntArray();
    var list = [alist[0]];
    for(var j = 1; j < N; j++){
      if(list[list.length - 1] != alist[j]){
        list.push(alist[j]);
      }else if(list[list.length - 1] != blist[j]){
        list.push(blist[j]);
      }else{
        list.push(clist[j]);
      }
    }
    if(list[0] == list[N - 1]){
      if(alist[N - 1] != list[0] && alist[N - 1] != list[N - 2]){
        list[N - 1] = alist[N - 1];
      }else if(blist[N - 1] != list[0] && blist[N - 1] != list[N - 2]){
        list[N - 1] = blist[N - 1];
      }else{
        list[N - 1] = clist[N - 1];
      }
    }
    output[i] = myconv(list, 8);
  }
  myout(myconv(output, 9));
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

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 ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
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);
  return (u + MOD) % MOD;
}
// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let t = $()
  while (t--) {
    let n = $(), a = $(n), b = $(n), c = $(n)
    p = Array(n)
    p[0] = a[0]
    For(1, n - 1, i => {
      if (a[i] != p[i - 1]) p[i] = a[i];
      else p[i] = b[i];
    })
    if (a[n-1] != p[0] && a[n-1] != p[n-2]) p[n-1] = a[n-1];
    if (b[n-1] != p[0] && b[n-1] != p[n-2]) p[n-1] = b[n-1];
    if (c[n-1] != p[0] && c[n-1] != p[n-2]) p[n-1] = c[n-1];
    log(p.join(' '))
  }
}

var total  = parseInt(readline());

while (total-- ) {
    var n = parseInt(readline());
    var values = [];

    for (var i = 0; i < 3; i++) {
        values.push(readline().split(" ").map(Number));
    }

    var exclude = values[0][0];
    var result = [exclude];

    for (var i = 1; i < n; i++) {
        for (var j = 0; j < 3; j++) {
            if (values[j][i] !== exclude) {
                result.push(values[j][i]);
                exclude = values[j][i];
                break;
            }
        }
    }

    print(result.join(" "));
}

var t = parseInt(readline());

while(t--) {
    var values = readline().split(" ").map(Number);
    var n = values[0];
    var k = values[1];

    var se = new Set(readline().split(" ").map(Number));

    if (k < se.size) {
        print(-1);
    } else if (k === se.size) {
        print(1);
    } else {
        print(2);
    }
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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 output = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var alist = nextIntArray();
    var blist = nextIntArray();
    var clist = nextIntArray();
    var list = [alist[0]];
    for(var j = 1; j < N; j++){
      if(list[list.length - 1] != alist[j]){
        list.push(alist[j]);
      }else if(list[list.length - 1] != blist[j]){
        list.push(blist[j]);
      }else{
        list.push(clist[j]);
      }
    }
    output[i] = myconv(list, 8);
  }
  myout(myconv(output, 9));
}

#!/usr/bin/env node
'use strict';

const { createInterface } = require('readline');
const rl = createInterface({
  input: process.stdin,
  crlfDelay: Infinity
});

const buf = [];
const prom = [];
let maxBuf = 0;
let maxProm = 0;
rl.on('line', (line) => {
  if (prom.length > 0) {
    maxProm = Math.max(maxProm, prom.length);
    const [resolve, reject] = prom.shift();
    resolve(line);
  } else {
    rl.pause();
    buf.push(line);
    maxBuf = Math.max(maxBuf, buf.length);
  }
});

rl.on('close', () => {
  // console.error({maxProm, maxBuf});
});

async function getLine() {
  return new Promise((resolve, reject) => {
    if (buf.length > 0) {
      const line = buf.shift();
      resolve(line);
    } else {
      prom.push([resolve, reject]);
      rl.resume();
    }
  });
}

/**
 *
 * @param {Number []} a
 * @param {Number []} b
 * @param {Number []} c
 * @returns {Number []}
 */
function solve(a, b, c) {
  const n = a.length;
  const inp = [a, b, c];
  const res = [a[0]];
  for (let i = 1; i < n; i++) {
    for (let j = 0; j < 3; j++) {
      if (res[i-1] === inp[j][i]) continue;
      res[i] = inp[j][i];
      break;
    }
  }
  if (res[n-1] === res[0]) {
    for (let i = 0; i < 3; i++) {
      const t = inp[i][n-1];
      if (res[n-2] === t || res[0] === t) {
        continue;
      }
      res[n-1] = t;
      break;
    }
  }
  return res;
}

async function main() {
  const t = Number(await getLine());
  for (let i = 0; i < t; i++) {
    const n = Number(await getLine());
    const a = (await getLine()).split(' ').map(Number);
    const b = (await getLine()).split(' ').map(Number);
    const c = (await getLine()).split(' ').map(Number);
    const res = solve(a, b, c);
    console.log(`Case #${i+1}:`, res.join(' '));
  }
}

if (require.main === module) {
  main();
}