//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 one = nextIntArray();
		var N = one[0];
		var K = one[1];
		var alist = nextIntArray();
		alist.sort(function(a,b){
			return a - b;
		});
		var blist = nextIntArray();
		blist.sort(function(a,b){
			return b - a;
		});
		var isOK = true;
		for(var j = 0; j < N; j++){
			if(alist[j] + blist[j] > K){
				isOK = false;
			}
		}
		output[i] = (isOK) ? "YES" : "NO";
		if(i < t - 1){
			var sp = next();
		}
	}
	myout(myconv(output, 9));
}

var inputs = parseInt(readline());

for(var i =0;i<inputs;i++)
{
	var params = readline().split(" ").map(x => parseInt(x));
	var a =  readline().split(" ").map(x => parseInt(x));
	var b =  readline().split(" ").map(x => parseInt(x));
	readline();
	b.reverse();
	var isPossible = true;
	var n = params[0];
	var x = params[1];
    for(var j=0;j< n; j++){
        if(a[j]+b[j]>x)
        {
             isPossible = false;
            break;

        }

    }
    if(isPossible)
    {
        print('Yes');
    }
    else
    {
        print('No');
    }
}

(function () {
    var t = +readline();
    var i = 0;
    while(i++ < t) {
        rearrangeArray();
        readline();
    }

    function rearrangeArray() {
        var nums = readline().split(' ').map(Number);
        var n = nums[0], x = nums[1];
        var a = readline().split(' ').map(Number);
        var b = readline().split(' ').map(Number);
        var available = b.sort((j,k) => k-j);
        outer: for(var j = 0; j < n; j++) {
            var curLength = available.length
            for(var k = 0; k < curLength; k++) {
                if(available[k] <= x - a[j]) {
                    available.splice(k, 1);
                    continue outer;
                }
            }
            if(available.length >= curLength) {
                print("No");
                return;
            }
        }
        print("Yes");
    }
})();

let data = '';
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on('data', chunk => data += chunk);
process.stdin.on('end', () => {
  data = data.replace(/\s/g, ' ').replace(/  /g, ' ').split(' ').filter(x => !!x);
  main();
});
let __i = 0;

let read = () => Number(data[__i++]);
let readArray = (n) => { let t = new Array(n); for (let i = 0; i < n; i++) t[i] = Number(read()); return t; }

function main() {
  let t = read();
  while(t--) {
    let n = read(), x = read();
    let a = readArray(n);
    let b = readArray(n);

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

    let r = true;
    for (let i = 0; i < n; i++) {
      if (a[i] + b[i] > x) {
        r = false;
        break;
      }
    }
    console.log(r ? "Yes" : "No");
  }
}

(()=>{"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],h=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 p(){return i[u++]}function f(){return p().split(" ").map((t=>parseFloat(t)))}function c(){return p().split("")}e.default={runMain:h,runEachTest:t=>{h((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:p,nextNumbers:f,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,e]=s.default.nextNumbers(),r=s.default.nextNumbers(),n=s.default.nextNumbers();n.reverse();let o=r.filter(((t,r)=>t+n[r]<=e)).length==t;s.default.puts(o?"Yes":"No"),s.default.readline()}))},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, x] = io.nextNumbers()
//   let a = io.nextNumbers()
//   let b = io.nextNumbers()
//
//   b.reverse()
//
//   let ok = a.filter((y, i) => y + b[i] <= x).length == n
//
//   io.puts(ok ? "Yes" : "No")
//
//   io.readline()
// }
//
// 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').filter((line) => line.trim() !== '')
  const T = parseInt(lines[0])
  let curLine = 1
  for (let t = 0; t < T; t++) {
    const [n, x] = lines[curLine++].split(' ').map((k) => parseInt(k))
    const a = lines[curLine++].split(' ').map((k) => parseInt(k)).sort((u, v) => u - v)
    const b = lines[curLine++].split(' ').map((k) => parseInt(k)).sort((u, v) => v - u)
    let ans = 'Yes'
    for (let i = 0; i < n; i++) {
      if (a[i] + b[i] > x) {
        ans = 'No'
      }
    }
    console.log(ans)
  }
})

process.stdin.resume()
process.stdin.setEncoding('utf-8')
let stdInputString = ''

let currentLine = 0;

function readLine() {
    return stdInputString
}

process.stdin.once('data', rawData => {
    stdInputString += rawData
})

process.stdin.once('end', _ => {
    stdInputString = stdInputString
        .trim()
        .replace(/\r/g, '')
        .split('\n')
    main()
})

function main() {
    const w = readLine()
    let a = b = x = ''
    let ntest = w[0];

    for (let i = 0; i < ntest; i++) {
        w.map((ln, k) => {
            if ((4 * i) < k && k < (4 * (1 + i))) {
                if (k % 4 === 1)
                    x = ln.split(' ')[1]
                else if (k % 4 === 2)
                    a = ln.split(' ').map(Number)
                else
                    b = ln.split(' ').map(Number)
            }
        })

        function swap(index, b) {
            let len = b.length - 1;
            let tem = b[index]
            b[index] = b[len]
            b[len] = tem;
            return b;
        }

        function fulfills(b, a, sum) {
            if (a[a.length - 1] + b[b.length - 1] <= sum)
                return true
            else
                return false
        }

        function absoluteFalse(a, b, x) {
            if ((a[a.length - 1] >= x) || (b[b.length - 1] >= x)) {
                return true;
            } else if ((a[a.length - 1] + b[0]) > x) {
                return true;
            } else if ((b[b.length - 1] + a[0]) > x) {
                return true;
            } else if (a[a.length - 1] + b[0] === x) {
                b.splice(b.length, 0, b[0])
                b.shift()
                return b
            } else if ((a[a.length - 1] + b[0] <= x) && (a[a.length - 1] + b[1] > x)) {
                b.splice(b.length, 0, b[0])
                b.shift()
                return b
            } else
                return false
        }

        function preprocessing(a, b, x) {
            let abFalse = absoluteFalse(a, b, x)
            if (abFalse === true) {
                return false
            } else if (abFalse.length > 0) {
                return abFalse
            } else
                return true
        }

        function matchNsum(a, b, x, len) {
            let result = false;
            let op = ''
            if (preprocessing(a, b, x) === false)
                return false
            else if (preprocessing(a, b, x).length > 0)
                b = preprocessing(a, b, x)

            while (a.length > 0) {
                if (op === 'p') {
                    if (preprocessing(a, b, x) === false)
                        return false
                    else if (preprocessing(a, b, x).length > 0)
                        b = preprocessing(a, b, x)
                }

                if (fulfills(b, a, x)) {
                    result = true;
                    if (b.length > 0) {
                        b.pop();
                        a.pop();
                        op = 'p'
                        len = b.length
                    } else {
                        return result
                    }
                } else {
                    result = false;
                    if (len > 0) {
                        len--
                        b = swap(len, b)
                        op = 's'
                    } else if (a.length === 1) {
                        return result
                    }
                }
            }
            return result
        }
        result = matchNsum(a, b, x, b.length) === false ? 'No' : 'Yes'
        console.log(result)
        a = [];
        b = [];
    }
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')
let stdInputString = ''

let currentLine = 0;

function readLine() {
    return stdInputString
}

process.stdin.once('data', rawData => {
    stdInputString += rawData
})

process.stdin.once('end', _ => {
    stdInputString = stdInputString
        .trim()
        .replace(/\r/g, '')
        .split('\n')
    main()
})

function main() {
    const w = readLine()
    let a = b = x = ''
    let ntest = w[0];

    for (let i = 0; i < ntest; i++) {
        w.map((ln, k) => {
                if ((4 * i) < k && k < (4 * (1 + i))) {
                    if (k % 4 === 1) {
                        x = ln.split(' ')[1]
                            // console.log('len = ' + v[0])
                            // console.log('x = ' + x)
                    } else if (k % 4 === 2) {
                        a = ln.split(' ').map(Number)
                    } else {
                        b = ln.split(' ').map(Number)
                    }
                }
            })
            // Function:

        function swap(index, b) {
            let len = b.length - 1;
            let tem = b[index]
            b[index] = b[len]
            b[len] = tem;
            return b;
        }

        function fulfills(b, a, sum) {
            if (a[a.length - 1] + b[b.length - 1] <= sum)
                return true
            else
                return false
        }

        function absoluteFalse(a, b, x) {
            if ((a[a.length - 1] >= x) || (b[b.length - 1] >= x)) {
                return true;
            } else if ((a[a.length - 1] + b[0]) > x) {
                return true;
            } else if ((b[b.length - 1] + a[0]) > x) {
                return true;
            } else if (a[a.length - 1] + b[0] === x) {
                b.splice(b.length, 0, b[0])
                b.shift()
                return b
            } else if ((a[a.length - 1] + b[0] <= x) && (a[a.length - 1] + b[1] > x)) {
                b.splice(b.length, 0, b[0])
                b.shift()
                return b
            } else
                return false
        }

        function preprocessing(a, b, x) {
            let abFalse = absoluteFalse(a, b, x)
            if (abFalse === true) {
                a = []
                b = []
                return false
            } else if (abFalse.length > 0) {
                return abFalse
            } else
                return true
        }

        function matchNsum(a, b, x, len) {
            let result = false;
            let op = ''
            if (preprocessing(a, b, x) === false)
                return false
            else if (preprocessing(a, b, x).length > 0)
                b = preprocessing(a, b, x)

            while (a.length > 0) {
                if (op === 'p') {
                    if (preprocessing(a, b, x) === false)
                        return false
                    else if (preprocessing(a, b, x).length > 0)
                        b = preprocessing(a, b, x)
                }

                if (fulfills(b, a, x)) {
                    result = true;
                    if (b.length > 0) {
                        b.pop();
                        a.pop();
                        op = 'p'
                        len = b.length
                    } else {
                        return result
                    }
                } else {
                    result = false;
                    if (len > 0) {
                        len--
                        b = swap(len, b)
                        op = 's'
                    } else if (a.length === 1) {
                        return result
                    }
                }
            }
            return result
        }
        result = matchNsum(a, b, x, b.length) === false ? 'No' : 'Yes'
        console.log(result)
    }
}

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

    A();
});

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());
    let y = t;
    while(t > 0){
        t--;
        if(t < y-1)
            readline();
        let [n,x] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let b = ti(readline().split(' '));

        let visited = new Array(n);
        visited.fill(false);
        let flag = true;

        for(let i = 0; i < n; i++){
            let max = a[i];
            let index = -1;
            for(let j = 0; j < n; j++){
                if(!visited[j] && a[i]+b[j] <= x){
                    max = Math.max(max, a[i]+b[j]);
                    index = j;
                }
            }
            if(index !== -1){
                visited[index] = true;
            }else{
                console.log('No');
                flag = false;
                break;
            }
        }
        if(flag)
            console.log('Yes');
    }
}

var N = Number(readline());

// 调整数组 a b 使得
// a[i] + b[i] <= x

for( ; N; N -- && readline())
{
	print(['No', 'Yes'][test() + 0]);
}

function test()
{
	var x = Number(readline().split(' ')[1]);
	var a = readline().split(' ').map(e => Number(e)).sort((a, b) => a - b);
	var b = readline().split(' ').map(e => Number(e)).sort((a, b) => b - a);

	for(var i = 0; i < a.length; i ++)
	{
		if(a[i] + b[i] > x)
			return false;
	}

	return true;
}

var t=readline();

for (k = 0; k< t; k++){
	if (k > 0){
		var empty = readline();
	}
	var nx = readline();
	var a = readline().split(" ");
	var b = readline().split(" ");
	var shi = false;
	var x = +nx.split(" ")[1];
	for (i = 0; i < a.length; i++){
		var toDelete = a.length - (i + 1);

		if ((+a[toDelete] + +b[i]) > x){
			shi = true;
		}

	}
	if (shi == true){
		print ("No");
	}
	else{
		print ("Yes");
	}
}

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, x] = readLine().split(" ").map(Number);
    const arr1 = readLine().split(" ").map(Number);
    const arr2 = readLine().split(" ").map(Number);
    readLine();
    let flag = true;

    arr1.sort((a, b) => a - b);
    arr2.sort((a, b) => b - a);

    for (let i = 0; i < len; i++) {
      if (arr1[i] + arr2[i] > x) {
        console.log("No");
        flag = false;
        break;
      }
    }
    if (flag) console.log("Yes");
  }
}

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, x] = readLine().split(" ").map(Number);
    const arr1 = readLine().split(" ").map(Number);
    const arr2 = readLine().split(" ").map(Number);
    readLine();

    const [min1, max1, min2, max2] = [Math.min(...arr1), Math.max(...arr1), Math.min(...arr2), Math.max(...arr2)];
    if (x < min1 || x < min2 || min1 + max2 > x || min2 + max1 > x) console.log("No");
    else console.log("Yes");
  }
}

let input = ''

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

process.stdin.on('end', () => {
  const lines = input.trim().split('\n').filter((line) => line.trim() !== '')
  const T = parseInt(lines[0])
  let curLine = 1
  for (let t = 0; t < T; t++) {
    const [n, x] = lines[curLine++].split(' ').map((k) => parseInt(k))
    const a = lines[curLine++].split(' ').map((k) => parseInt(k)).sort()
    const b = lines[curLine++].split(' ').map((k) => parseInt(k)).sort((u, v) => v - u)
    let ans = 'Yes'
    for (let i = 0; i < n; i++) {
      if (a[i] + b[i] > x) {
        ans = 'No'
      }
    }
    console.log(ans)
  }
})

let input = ''

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

process.stdin.on('end', () => {
  const lines = input.trim().split('\n').filter((line) => line.trim() !== '')
  const T = parseInt(lines[0])
  let curLine = 1
  for (let t = 0; t < T; t++) {
    const [n, x] = lines[curLine++].split(' ').map((x) => parseInt(x))
    const a = lines[curLine++].split(' ').map((x) => parseInt(x)).sort()
    const b = lines[curLine++].split(' ').map((x) => parseInt(x)).sort((u, v) => v - u)
    let ans = 'Yes'
    for (let i = 0; i < n; i++) {
      if (a[i] + b[i] > x) {
        ans = 'No'
      }
    }
    console.log(ans)
  }
})

var t=readline();

for (k = 0; k< t; k++){
	if (k > 0){
		var empty = readline();
	}
	var nx = readline();
	var a = readline().split(" ");
	var b = readline().split(" ");
	var shi = false;
	var x = nx.split(" ")[1];
	for (i = 0; i < a.length; i++){
		var toDelete = a.length - (i + 1);

		if ((a[toDelete] + b[i]) > x){
			shi = true;
		}

	}
	if (shi == true){
		print ("No");
	}
	else{
		print ("Yes");
	}
}

var inputs = parseInt(readline());

for(var i =0;i<inputs;i++)
{
	var params = readline().split(" ").map(x => parseInt(x));

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

	a.sort();
	b.sort();
	b.reverse();
	var isPossible = true;
	var n = params[0];
	var x = params[1];
    for(var j=0;j< n; j++){
        if(a[j]+b[j]<=x)
        {
            continue
        }
        else
        {
            isPossible = false;
            break;
        }
    }
    if(isPossible)
    {
        print('Yes');
    }
    else
    {
        print('No');
    }
}

var inputs = parseInt(readline());

for(var i =0;i<inputs;i++)
{
	var params = readline().split(" ").map(x => parseInt(x));
	var a =  readline().split(" ").map(x => parseInt(x));
	var b =  readline().split(" ").map(x => parseInt(x));
	readline();

	a.sort();
	b.sort();
	b.reverse();
	var isPossible = true;
	var n = params[0];
	var x = params[1];
    for(var j=0;j< n; j++){
        if(a[j]+b[j]<=x)
        {
            continue
        }
        else
        {
            isPossible = false;
            break;
        }
    }
    if(isPossible)
    {
        print('Yes');
    }
    else
    {
        print('No');
    }
}


'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() {
    let range = readline();
    for(let r=0;r<range;r++) {
        let data = readline()
        let a = readline().split(" ").map(x => parseInt(x));

        if(data === 1) {
            console.log("Yes");
            break;
        }

        let output = "Yes";

        for(let i=1;i<data - 1;i++) {
            if(a[i] - a[i - 1] > 1) {
                output = "No";
                break;
            }
        }

        console.log(output);
    }

}

// Lang: Node.js
'use strict';
let x = '', y = 0;
let print = x => console.log(x);

process.stdin.on('data', inputStdin => x += inputStdin);
process.stdin.on('end', () => { x = x.split('\n'); main(); });
let readline = () => x[y++];

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

function main() {

 var Tc = parseInt(readline());
 while (Tc--) {
   var n = parseInt(readline());
   var ar = readline().split(' ').map((x) => parseInt(x));
   var ok = 1;
   for (var i = 1; i < n; i++) {
     if (ar[i] > ar[i - 1] && ar[i] != ar[i - 1] + 1) {
       ok = 0;
       break;
     }
   }
   print(ok ? 'YES' : 'NO');
 }
}

'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() {
    let range = readline();
    for(let r=0;r<range;r++) {
        let data = readline()
        let a = readline().split(" ").map(x => parseInt(x));

        if(data === 1) {
            console.log("Yes")
        } else if(a[a.length - 1] - a[0] < 1) {
            console.log("Yes")
        } else {
            console.log("No");
        }

    }

}


let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        let longItems = data.reduce((agr, item) => {
            item = +item;
            if (item > agr[0]) agr.unshift(item);
            else if (item > agr[1]) agr[1] = item;
            return agr;
        }, [0, 0]);
        let maxKForLong = longItems[1] - 1;
        let maxKForShort = data.length - 2;
        let k = Math.min(maxKForLong, maxKForShort);
        return k > 0 ? k : 0;

    }

    let testCount = 1;

    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ");
        console.log(foo(data));
        testCount++;
    }
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        let longItems = data.reduce((agr, item) => {
            item = +item;
            if (item > agr[0]) agr.unshift(item);
            else if (item > agr[1]) agr[1] = item;
            return [agr[0], agr[1]];
        }, [0, 0]);
        let maxKForLong = longItems[1] - 1;
        //console.log("maxKForLong", maxKForLong);
        let maxKForShort = data.length - 2;
        //console.log("maxKForShort", maxKForShort);
        let k = Math.min(maxKForLong, maxKForShort);
        return k > 0 ? k : 0;

    }

    let testCount = 1;

    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ");
        //console.log(data)
        console.log(foo(data));
        testCount++;
    }
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        let longItems = data.reduce((agr, item) => {
            if (item > agr[0]) agr.unshift(item);
            else if (item > agr[1]) agr[1] = item;
            return [agr[0], agr[1]];
        }, [0, 0]);
        let maxKForLong = longItems[1] - 1;
        //console.log("maxKForLong", maxKForLong);
        let maxKForShort = data.length - 2;
        //console.log("maxKForShort", maxKForShort);
        let k = Math.min(maxKForLong, maxKForShort);
        return k > 0 ? k : 0;

    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ").map(Number);
        //console.log(data)
        answer += foo(data) + "\n";
        testCount++;
    }
    console.log(answer)
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data, min, max) {
	    function check(data, k) {
	        //console.log("k ", k);
	        let lengthLong = data.reduce((agr, value) => {
	            if (value >= k + 1) agr++;
	            return agr;
	        }, 0);

	        //console.log("lengthLong", lengthLong);
	        let hasLong = lengthLong >=2 ;

	        let hasShort = (data.length - 2) >= k;
	        return hasLong && hasShort;
	    }

	    let middle = min + Math.ceil((max - min) / 2);
	    //console.log(min, max, middle);
	    let isValid = check(data, middle);
	    let isNextValid = check(data, middle + 1);
	    //console.log(isValid, isNextValid);
	    if (isValid && !isNextValid) return middle;
	    if (max <= min) return 0;

	    if (isValid && isNextValid) {
	        min = middle;
	    } else {
	        max = (max !== middle) ? middle : middle -1;
	    }
	    return foo(data, min, max);
	}

	let testCount = 1;

	while(testCount <= +lines[0]) {
	    let data = lines[testCount * 2].split(" ");
	    //console.log("data ", data);
	    console.log(foo(data, 1, data.length - 2));
	    testCount++;
	}
})

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

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

  if (c % 2) {
    c++;
    return;
  }

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

  const max = arr[1];

  console.log(Math.min(max - 1, arr.length - 2));

  // let ans = 0;

  // for (let i = 2; i < arr.length; i++) {
  //   ans++;
  // }

  // console.log(Math.min(max - 1, ans));

  c++;
});

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

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

  if (c % 2) {
    c++;
    return;
  }

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

  const max = arr[1];
  let ans = 0;

  for (let i = 2; i < arr.length; i++) {
    ans++;
  }

  console.log(Math.min(max - 1, ans));

  c++;
});

t=+readline()

function cmp(a,b)
{
    if (+a<+b)
    return 1
    if (+a==+b)
    return 0
    if (+a>+b)
    return -1
}

function min(a,b)
{
    if (a<b)
    return a
    return b
}

while(t--)
{
    n=+readline()
    a=readline().split(' ').map(function(x){return +x})
    a.sort(cmp)
    x1=0
    if (n<=2||a[1]==1)
    {
        print(0)
    } else {
        print(min(n-2,a[1]-1))
    }
}

const readLines = () => {
	try {
		return require("fs").readFileSync("input.txt", "utf8").split(/[\r\n]+/);
	} catch(e) {}
	const lines = [];
	for(var line; undefined !== (line = readline()); )
		lines.push(line);
	return lines;
};
const output = (text) => {
	try {
		console.log(text);
	} catch(e) {}
	try {
		text.toString().split(/[\r\n]+/).map(s => print(s));
	} catch(e) {}
};

var a = readLines();
var count = +a.shift();
var result = [];
for(var i = 0; i < count; i++) {
	var numBoards = +a.shift();
	var boards = a.shift().split(" ").map(Number);;
	boards.sort((l, r) => r - l);
	result.push( Math.min((boards[1]|0) - 1, numBoards - 2) );
}

output( result.join("\n") );

var t = +readline()

for ( var i = 0 ; i < t ; i++ ) {
  var n = +readline()
  var planks = readline().split(' ')
  planks.sort((a,b) => a - b)

  var l = Math.min(planks.pop(), planks.pop()) - 1
  print(Math.min(l, planks.length))
}

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {
    var T = +rd();
    while (T-->0) {
        var n = +rd();
        var A = rdAr().sortGt();
        var max2 = A[1] - 1;
        pr(Math.min(max2, n - 2));
    }
};

if (INPUT) {
INPUT = INPUT.split('\n').reverse();
readline = () => INPUT.pop();
write = (s) => {OUTPUT += s};
print = (s) => {OUTPUT += s + '\n'};
}
const rd = readline;
const wr = write;
const pr = print;
const rdAr = () => rd().split(' ').map(v => +v);
const prAr = (a) => pr(a.join(' '));
const cmpLt = (a, b) => a - b;
const cmpGt = (a, b) => b - a;
Array.prototype.sortLt = function() { return this.sort(cmpLt); };
Array.prototype.sortGt = function() { return this.sort(cmpGt); };
const crAr = function(length, ...fillArgs) { return new Array(length).fill(...fillArgs); };
const getPrimes = function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(var i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;};

try {main();}finally{return OUTPUT;}
})();

const readLines = () => {
	try {
		return require("fs").readFileSync("input.txt", "utf8").split(/[\r\n]+/);
	} catch(e) {}
	const lines = [];
	for(var line; undefined !== (line = readline()); )
		lines.push(line);
	return lines;
};
const output = (text) => {
	try {
		console.log(text);
	} catch(e) {}
	try {
		text.toString().split(/[\r\n]+/).map(s => print(s));
	} catch(e) {}
};

var a = readLines();
var count = +a.shift();
var result = [];
for(var i = 0; i < count; i++) {
	var numBoards = +a.shift();
	var boards = a.shift().split(" ").map(Number);;
	boards.sort((l, r) => r - l);
	result.push( Math.max((boards[1]|0) - 1, numBoards - 2) );
}

output( result.join("\n") );

const readLines = () => {
	const lines = [];
	for(var line; undefined !== (line = readline()); )
		lines.push(line);
	return lines;
};
const output = (text) => {
	text.toString().split(/[\r\n]+/).map(s => print(s));
};
//const input = readline;
/**/

const a = readLines();
const count = +a.shift();
var result = [];
for(var i = 0; i < count; i++) {
	const numBoards = +a.shift();
	const boards = a.shift().split(" ").map(Number);
	boards.sort((l, r) => r - l);
	result.push( Math.max((boards[1]|0) - 1, numBoards - 2) );
}

output( result.join("\n") );

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        let longItems = data.reduce((agr, item) => {
            if (item > agr[0]) agr.unshift(item);
            else if (item > agr[1]) agr[1] = item;
            return agr;
        }, [0, 0]);
        let maxKForLong = longItems[1] - 1;
        let maxKForShort = data.length - 2;
        let k = Math.min(maxKForLong, maxKForShort);
        return k > 0 ? k : 0;

    }

    let testCount = 1;

    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ");
        console.log(foo(data));
        testCount++;
    }
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        let longItems = data.reduce((agr, item) => {
            item = +item;
            if (item > agr[0]) agr.unshift(item);
            else if (item > agr[1]) agr[1] = item;
            return agr;
        }, [0, 0]);
        let maxKForLong = longItems[1] - 1;
        console.log("maxKForLong",maxKForLong);
        let maxKForShort = data.length - 2;
        console.log("maxKForShort",maxKForShort);
        let k = Math.min(maxKForLong, maxKForShort);
        return k > 0 ? k : 0;

    }

    let testCount = 1;

    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ");
        console.log(data)
        console.log(foo(data));
        testCount++;
    }
})

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

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

  if (c % 2) {
    c++;
    return;
  }

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

  const max = arr[1];
  let ans = 0;

  for (let i = 2; i < arr.length; i++) {
    if (arr[i] < max) {
      ans++;
    }
  }

  console.log(Math.min(max - 1, ans));

  c++;
});

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

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

  if (c % 2) {
    c++;
    return;
  }

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

  const max = arr[1];
  let ans = 0;

  for (let i = 2; i < arr.length; i++) {
    if (arr[i] < max) {
      ans++;
    }
  }

  console.log(ans);

  c++;
});


// 369A     Валера и тарелки

// var n = parseInt(readline());

var input_line = readline().split(' ').map(Number);

var n = input_line[0];
var m = input_line[1];
var r = input_line[2];

var arr = readline().split(' ').map(Number);

var out = 0;
var count1 = 0;
var count2 = 0;

arr.forEach(function(item, i, arr) {
    if (item == 1) {
        count1 ++;
    } else {
        count2 ++;
    };
});

if (count1 > m) {
    out += (count1 - m);
} else {
    r += (m - count1);
};

if (r < count2) {
    out += count2 - r;
};

print(out);

function main(){
    var nmk  = readline().split(' ');
    var washTime = 0;
    var b = parseInt(nmk[1]), p = parseInt(nmk[2]);
    readline().split(' ').forEach(function (i){
        if ( i === "1" ){
            if ( b > 0 ){
                --b;
            }else{
                ++washTime;
            }
        }else{
            if ( p > 0 ){
                --p;
            }else if ( b > 0 ){
                --b;
            }else{
                ++washTime;
            }
        }
    });
    print(washTime);
}
main();

var l=readline().split(' ');
var n=+l[0];
var m=+l[1];
var k=+l[2];

var ans=0;
readline().split(' ').forEach(function(v){
	if(v==='1'){
		if(m>0){
			m--;
		}else{
			ans++;
		}
	}else{
		if(k>0){
			k--;
		}else if(m>0){
			m--;
		}else{
			ans++;
		}
	}
});
print(ans);

var input = readline().split(" ").map(Number), n = +input[0], m = +input[1], k = +input[2],
a = readline().split(" ");
var cnt = 0;

a.forEach(function(day){
	if(day == "1"){
		if(m > 0){
			m--;
		}
		else{
			cnt++;
		}
	}
	else{
		if(k > 0){
			k--;
		}
		else{
			if(m > 0){
				m--;
			}
			else{
				cnt++;
			}
		}
	}
});

write(cnt);

var n = readline().split(' ');
var m = +n[1];
var l = +n[2];
n = +n[0];

var x = 0;
var a = readline().split(' ').map(function (e) {
	switch (e) {
		case '1':
			if (m > 0) m--;
			else x++;
			break;

		case '2':
			if (l > 0) l--;
			else {
				if (m > 0) m--;
				else x++;
			}
			break;
	}
});

print(x);

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 numDays = integers[0], bowlCap = integers[1], dishCap = integers[2];

	var meals = tokenizeIntegers(readline());
	var typeCounts = { 1: 0, 2: 0 };
	for (var i = 0; i < meals.length; i += 1) {
		typeCounts[meals[i]] += 1;
	}

	var bowls = bowlCap - typeCounts[1];
	if (bowls > 0) {
		dishCap += bowls;
	}
	var dishes = dishCap - typeCounts[2];

	var result = -(Math.min(bowls, 0) + Math.min(dishes, 0));
	print(result);
}

main();

var n = readline().split(' ');
var m = +n[1];
var l = +n[2];
n = +n[0];

var x = 0;
var a = readline().split(' ').map(function (e) {
	switch (e) {
		case '1':
			if (m > 0) m--;
			else x++;
			break;

		case '2':
			if (l > 0) l--;
			else x++;
			break;
	}
});

print(x);

var n = readline().split(' ');
var m = +n[1];
var l = +n[2];
n = +n[0];

var x = 0;
var a = readline().split(' ').map(function (e) {
	switch (e) {
		case '1':
			if (m > 0) m--;
			else x++;
			break;

		case '2':
			if (m > 0) m--;
			else {
				if (l > 0) l--;
				else x++;
			}
			break;
	}
});

print(x);

// 369A     Валера и тарелки

// var n = parseInt(readline());

var input_line = readline().split(' ').map(Number);

var n = input_line[0];
var m = input_line[1];
var r = input_line[2];

var arr = readline().split(' ').map(Number);

var out = 0;
var count1 = 0;
var count2 = 0;

arr.forEach(function(item, i, arr) {
    if (item == 1) {
        count1 ++;
    } else {
        count2 ++;
    };
});

if (count1 > m) {
    out += (count1 - m);
} else {
    count2 += (m - count1);
};

if (count2 < (n - count1)) {
    out += (n - count1) - count2;
};

print(out);

// 369A     Валера и тарелки

// var n = parseInt(readline());

var input_line = readline().split(' ').map(Number);

var n = input_line[0];
var m = input_line[1];
var r = input_line[2];

var arr = readline().split(' ').map(Number);

var out = 0;
var count1 = 0;
var count2 = 0;

arr.forEach(function(item, i, arr) {
    if (item = 1) {
        count1 ++;
    } else {
        count2 ++;
    };
});

if (count1 > m) {
    out += (count1 - m);
} else {
    count2 += (m - count1);
};

if (count2 < (n - count1)) {
    out += (n - count1) - count2;
};

print(out);

function main(){
    var nmk  = readline().split(' ');
    var plan = readline().split(' ');
    var i, washTime = 0;
    var b = parseInt(nmk[1]), p = parseInt(nmk[2]);
    for( i = 0 ; i < nmk[0] ; ++i ){
        if ( plan[i] == 1 ){
            if ( b == 0 ){
                b = parseInt(nmk[1]), p = parseInt(nmk[2]);
                ++washTime;
            }
            --b;
        }else{
            if ( p > 0 ){
                --p;
            }else if ( b > 0 ){
                --b;
            }else{
                b = parseInt(nmk[1]), p = parseInt(nmk[2]);
                ++washTime;
                --p;
            }
        }
    }
    print(washTime);
}
main();


function find(str,vitamin){
    for (var j = 0;j<str.length;j++){
        if (str.charAt(j) === vitamin) return true;
    }
    return false;
}
var A =Number.MAX_VALUE, B =Number.MAX_VALUE, C =Number.MAX_VALUE, AB =Number.MAX_VALUE, AC =Number.MAX_VALUE, BC =Number.MAX_VALUE, ABC = Number.MAX_VALUE;
var n = +readline();
while (n-->0){
    var ip = readline().split(' ');
    if (find(ip[1],'A')){
        A = Math.min(A,ip[0]);
    }
    if (find(ip[1],'B')){
        B = Math.min(B,ip[0]);
    }
    if (find(ip[1],'C')){
        C = Math.min(C,ip[0]);
    }
    if (ip[1] === 'AB' || ip[1] === 'BA'){
        AB = Math.min(ip[0],AB);
    }
    if (ip[1] === 'AC' || ip[1] === 'CA'){
        AC = Math.min(ip[0],AC);
    }
    if (ip[1] === 'CB' || ip[1] === 'BC'){
        BC = Math.min(ip[0],BC);
    }

    if (ip[1].length === 3){
        ABC = Math.min(ip[0],ABC);
    }
    AB = Math.min(A+B,AB);
    AC = Math.min(A+C,AC);
    BC = Math.min(B+C,BC);
    ABC = Math.min(A+B+C,AB+C,AC+B,BC+A,ABC);
}
print((ABC === Number.MAX_VALUE)?-1:ABC);

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: parseInt(inp[0]),
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
                break;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1];
                break;
            }
        }

        updateSum();

    }

    if (sortedArr['ABC'] && sum > sortedArr['ABC']) {
        sum = sortedArr['ABC'];
    }

    //console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 198,
//     vit: 'BC'
// }, {
//     cost: 259,
//     vit: 'AC'
// }, {
//     cost: 125,
//     vit: 'BA'
// }, {
//     cost: 298,
//     vit: 'CAB'
// }, {
//     cost: 252,
//     vit: 'CA'
// }, {
//     cost: 98,
//     vit: 'AC'
// }, {
//     cost: 284,
//     vit: 'BAC'
// }])

dp = new Array(8);
for (i=1;i<8;i++){
    dp[i] = Number.MAX_VALUE;
}
dp[0] = 0;
n = +readline();
while (n-->0){
    ip = readline().split(' ');
    value = +ip[0];
    plus = 0;
    ip[1].split('').forEach(x => {
        plus |= 1<<(x.charCodeAt() - 65);
    });
    for (i = 7;i>=0;i--){
        dp[i | plus] = Math.min(dp[i | plus], dp[i]+value);
    }
}
print(dp[7] === Number.MAX_VALUE?-1:dp[7]);

function find(str,vitamin){
    for (var j = 0;j<str.length;j++){
        if (str.charAt(j) === vitamin) return true;
    }
    return false;
}
var A =Number.MAX_VALUE, B =Number.MAX_VALUE, C =Number.MAX_VALUE, AB =Number.MAX_VALUE, AC =Number.MAX_VALUE, BC =Number.MAX_VALUE, ABC = Number.MAX_VALUE;
var n = +readline();
while (n-->0){
    var ip = readline().split(' ');
    if (ip[1] === 'A'){
        A = Math.min(A,ip[0]);
    }
    if (ip[1] === 'B'){
        B = Math.min(B,ip[0]);
    }
    if (ip[1] === 'C'){
        C = Math.min(C,ip[0]);
    }
    if (ip[1] === 'AB' || ip[1] === 'BA'){
        AB = Math.min(ip[0],AB);
    }
    if (ip[1] === 'AC' || ip[1] === 'CA'){
        AC = Math.min(ip[0],AC);
    }
    if (ip[1] === 'CB' || ip[1] === 'BC'){
        BC = Math.min(ip[0],BC);
    }

    if (ip[1].length === 3){
        ABC = Math.min(ip[0],ABC);
    }
    AB = Math.min(A+B,AB);
    AC = Math.min(A+C,AC);
    BC = Math.min(B+C,BC);
    ABC = Math.min(A+B+C,AB+C,AC+B,BC+A,ABC,AB+AC,AB+BC,BC+AC);
}
print((ABC === Number.MAX_VALUE)?-1:ABC);

var n = Number(readline());
var input = [];
var hash = {}; var key;
var keymap = {A : "001",
  B : "010" ,
  C : "100",
  AB : "011",
  BC: "110",
  AC: "101",
  ABC: "111"};

for(var i=0; i<n; i++) {
    var juices = readline().split(' ');
    var key = keymap[juices[1].split('').sort().join('')];
    if (hash[key] == undefined) {
      hash[key] = Number(juices[0]);
    } else {
      hash[key] = Math.min(hash[key], Number(juices[0]));
    }
}

var min = hash["111"] ? hash["111"] : -1;

if(hash["001"] && hash["010"] && hash["100"]) {
  min = (min == -1) ? hash["001"]+hash["010"]+hash["100"] : Math.min(min, hash["001"]+hash["010"]+hash["100"]);
}
for(i in hash) {
    for(var j in hash) {
      if((i|j) == "111" && i != j) {
        min = (min == -1) ? (hash[i]+hash[j]) : Math.min(min, hash[i]+hash[j]);
      }
    }
}

print(min);

// var lineIdx = 0;
// var readline = () => {
//   var input = ["4", "5 C", "6 B", "16 ACB", "4 A"]
//   return input[lineIdx++];
// };
// var print = (str) => {
//   console.log(str);
// };

var min = (...arg) => {
  var min;
  for(var a of arg){
    if(a != NaN && (!min || a < min)){
      min = a;
    }
  }
  return min;
}

var res = new Array(8)
var n = parseInt(readline())
for(var i = 0; i < n; i++){
  var line = readline().split(" ");
  var price = parseInt(line[0]);
  var bit = line[1].split('').sort().join('');
  if(!res[bit] || res[bit] > price){
    res[bit] = price;
  }
}

var minPrice = min(res['A'] + res['B'] + res['C'],
res['A'] + res['BC'],
res['B'] + res['AC'],
res['C'] + res['AB'],
res['AB'] + res['AC'],
res['AB'] + res['BC'],
res['BC'] + res['AC'],
res['ABC'])
print(minPrice || -1)

function find(str,vitamin){
    for (var j = 0;j<str.length;j++){
        if (str.charAt(j) === vitamin) return true;
    }
    return false;
}
var A =Number.MAX_VALUE, B =Number.MAX_VALUE, C =Number.MAX_VALUE, AB =Number.MAX_VALUE, AC =Number.MAX_VALUE, BC =Number.MAX_VALUE, ABC = Number.MAX_VALUE;
var n = +readline();
while (n-->0){
    var ip = readline().split(' ');
    if (ip[1] === 'A'){
        A = Math.min(A,ip[0]);
    }
    if (ip[1] === 'B'){
        B = Math.min(B,ip[0]);
    }
    if (ip[1] === 'C'){
        C = Math.min(C,ip[0]);
    }
    if (ip[1] === 'AB' || ip[1] === 'BA'){
        AB = Math.min(ip[0],AB);
    }
    if (ip[1] === 'AC' || ip[1] === 'CA'){
        AC = Math.min(ip[0],AC);
    }
    if (ip[1] === 'CB' || ip[1] === 'BC'){
        BC = Math.min(ip[0],BC);
    }

    if (ip[1].length === 3){
        ABC = Math.min(ip[0],ABC);
    }
    AB = Math.min(A+B,AB);
    AC = Math.min(A+C,AC);
    BC = Math.min(B+C,BC);
    ABC = Math.min(A+B+C,AB+C,AC+B,BC+A,ABC);
}
print((ABC === Number.MAX_VALUE)?-1:ABC);

var n = Number(readline());
var input = [];
var hash = {}; var key;
var keymap = {A : 001,
  B : 010 ,
  C : 100,
  AB : 011,
  BC: 110,
  AC: 101,
  ABC: 111};

for(var i=0; i<n; i++) {
    var juices = readline().split(' ');
    var key = keymap[juices[1].split('').sort().join('')];
    if (hash[key] == undefined) {
      hash[key] = Number(juices[0]);
    } else {
      hash[key] = Math.min(hash[key], Number(juices[0]));
    }
}

var min = -1;
if(hash["001"] && hash["010"] && hash["100"]) {
  min = hash["001"]+hash["010"]+hash["100"];
}
for(i in hash) {
    for(var j in hash) {
      if((i|j) == "111" && i != j) {
        min = (min == -1) ? (hash[i]+hash[j]) : Math.min(min, hash[i]+hash[j]);
      }
    }
}

print(min);

var n = Number(readline());
var input = [];
var hash = {}; var key;
var keymap = {A : "001",
  B : "010" ,
  C : "100",
  AB : "011",
  BC: "110",
  AC: "101",
  ABC: "111"};

for(var i=0; i<n; i++) {
    var juices = readline().split(' ');
    var key = keymap[juices[1].split('').sort().join('')];
    if (hash[key] == undefined) {
      hash[key] = Number(juices[0]);
    } else {
      hash[key] = Math.min(hash[key], Number(juices[0]));
    }
}

var min = -1;
if(hash["001"] && hash["010"] && hash["100"]) {
  min = hash["001"]+hash["010"]+hash["100"];
}
for(i in hash) {
    for(var j in hash) {
      if((i|j) == "111" && i != j) {
        min = (min == -1) ? (hash[i]+hash[j]) : Math.min(min, hash[i]+hash[j]);
      }
    }
}

print(min);

var n = Number(readline());
var input = [];
var hash = {}; var key;
var keymap = {A : "001",
  B : "010" ,
  C : "100",
  AB : "011",
  BC: "110",
  AC: "101",
  ABC: "111"};

for(var i=0; i<n; i++) {
    var juices = readline().split(' ');
    var key = keymap[juices[1].split('').sort().join('')];
    if (hash[key] == undefined) {
      hash[key] = Number(juices[0]);
    } else {
      hash[key] = Math.min(hash[key], Number(juices[0]));
    }
}

var min = -1;
if(hash["001"] && hash["010"] && hash["100"]) {
  min = hash["001"]+hash["010"]+hash["100"];
}
for(i in hash) {
    for(var j in hash) {
      if((i|j) == "111" && i != j) {
        min = (min == -1) ? (hash[i]+hash[j]) : Math.min(min, hash[i]+hash[j]);
      }
    }
}

if (hash["111"] && hash["111"] < min) {
  min = hash["111"];
}

print(min);

// var lineIdx = 0;
// var readline = () => {
//   var input = ["4", "5 C", "6 B", "16 ACB", "4 A"]
//   return input[lineIdx++];
// };
// var print = (str) => {
//   console.log(str);
// };

var min = (...arg) => {
  var min;
  for(var a of arg){
    if(a != NaN && (!min || a < min)){
      min = a;
    }
  }
  return min;
}

var bitStr = (val) => {
  var res = 0;
  for(var c of val){
    if(c == 'A'){
      res = res | 1;
    } else if(c == 'B'){
      res = res | 2;
    } else {
      res = res | 4;
    }
  }
  return res;
}

var res = new Array(8)
var n = parseInt(readline())
for(var i = 0; i < n; i++){
  var line = readline().split(" ");
  var price = parseInt(line[0]);
  var bit = bitStr(line[1]);
  if(!res[bit] || res[bit] > price){
    res[bit] = price;
  }
}

var minPrice = min(res[1] + res[2] + res[4], res[1] + res[6], res[2] + res[5], res[3] + res[4], res[7])
print(minPrice || -1)

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: inp[0],
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    print(inArr)
    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    // sortedArr = {}
    // costSorted.forEach((value) => {
    //     sortedArr[value[0]] = value[1];
    // })

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1]
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //  console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 100,
//     vit: 'A'
// }, {
//     cost: 355,
//     vit: 'BCA'
// }, {
//     cost: 150,
//     vit: 'BC'
// }, {
//     cost: 160,
//     vit: 'AC'
// }, {
//     cost: 180,
//     vit: 'B'
// }, {
//     cost: 190,
//     vit: 'CA'
// }])

// foo([{
//     cost: 10,
//     vit: 'AB'
// }, {
//     cost: 15,
//     vit: 'BA'
// }])

// foo([{
//     cost: 5,
//     vit: 'BA'
// }, {
//     cost: 11,
//     vit: 'CB'
// }])

// foo([{
//     cost: 5,
//     vit: 'C'
// }, {
//     cost: 6,
//     vit: 'B'
// }, {
//     cost: 16,
//     vit: 'BAC'
// }, {
//     cost: 4,
//     vit: 'A'
// }])

var number = readline();
var input = []
print(input)
for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    print(inp)
    input.push({
        cost: inp[0],
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    // sortedArr = {}
    // costSorted.forEach((value) => {
    //     sortedArr[value[0]] = value[1];
    // })

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1]
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //  console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 100,
//     vit: 'A'
// }, {
//     cost: 355,
//     vit: 'BCA'
// }, {
//     cost: 150,
//     vit: 'BC'
// }, {
//     cost: 160,
//     vit: 'AC'
// }, {
//     cost: 180,
//     vit: 'B'
// }, {
//     cost: 190,
//     vit: 'CA'
// }])

// foo([{
//     cost: 10,
//     vit: 'AB'
// }, {
//     cost: 15,
//     vit: 'BA'
// }])

// foo([{
//     cost: 5,
//     vit: 'BA'
// }, {
//     cost: 11,
//     vit: 'CB'
// }])

// foo([{
//     cost: 5,
//     vit: 'C'
// }, {
//     cost: 6,
//     vit: 'B'
// }, {
//     cost: 16,
//     vit: 'BAC'
// }, {
//     cost: 4,
//     vit: 'A'
// }])

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: parseInt(inp[0]),
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
                break;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1 && data[0] != 'ABC') {
                misVitSum += data[1];
                break;
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 198,
//     vit: 'BC'
// }, {
//     cost: 259,
//     vit: 'AC'
// }, {
//     cost: 125,
//     vit: 'BA'
// }, {
//     cost: 298,
//     vit: 'CAB'
// }, {
//     cost: 252,
//     vit: 'CA'
// }, {
//     cost: 98,
//     vit: 'AC'
// }, {
//     cost: 284,
//     vit: 'BAC'
// }])

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: parseInt(inp[0]),
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    // sortedArr = {}
    // costSorted.forEach((value) => {
    //     sortedArr[value[0]] = value[1];
    // })

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
                break;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1]
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 9,
//     vit: 'C'
// }, {
//     cost: 3,
//     vit: 'B'
// }])

// foo([{
//     cost: 100,
//     vit: 'A'
// }, {
//     cost: 355,
//     vit: 'BCA'
// }, {
//     cost: 150,
//     vit: 'BC'
// }, {
//     cost: 160,
//     vit: 'AC'
// }, {
//     cost: 180,
//     vit: 'B'
// }, {
//     cost: 190,
//     vit: 'CA'
// }])

// foo([{
//     cost: 10,
//     vit: 'AB'
// }, {
//     cost: 15,
//     vit: 'BA'
// }])

// foo([{
//     cost: 5,
//     vit: 'BA'
// }, {
//     cost: 11,
//     vit: 'CB'
// }])

// foo([{
//     cost: 5,
//     vit: 'C'
// }, {
//     cost: 6,
//     vit: 'B'
// }, {
//     cost: 16,
//     vit: 'BAC'
// }, {
//     cost: 4,
//     vit: 'A'
// }])

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: parseInt(inp[0]),
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
                break;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1];
                break;
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 198,
//     vit: 'BC'
// }, {
//     cost: 259,
//     vit: 'AC'
// }, {
//     cost: 125,
//     vit: 'BA'
// }, {
//     cost: 298,
//     vit: 'CAB'
// }, {
//     cost: 252,
//     vit: 'CA'
// }, {
//     cost: 98,
//     vit: 'AC'
// }, {
//     cost: 284,
//     vit: 'BAC'
// }])

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: parseInt(inp[0]),
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    // sortedArr = {}
    // costSorted.forEach((value) => {
    //     sortedArr[value[0]] = value[1];
    // })

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1]
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //  console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 100,
//     vit: 'A'
// }, {
//     cost: 355,
//     vit: 'BCA'
// }, {
//     cost: 150,
//     vit: 'BC'
// }, {
//     cost: 160,
//     vit: 'AC'
// }, {
//     cost: 180,
//     vit: 'B'
// }, {
//     cost: 190,
//     vit: 'CA'
// }])

// foo([{
//     cost: 10,
//     vit: 'AB'
// }, {
//     cost: 15,
//     vit: 'BA'
// }])

// foo([{
//     cost: 5,
//     vit: 'BA'
// }, {
//     cost: 11,
//     vit: 'CB'
// }])

// foo([{
//     cost: 5,
//     vit: 'C'
// }, {
//     cost: 6,
//     vit: 'B'
// }, {
//     cost: 16,
//     vit: 'BAC'
// }, {
//     cost: 4,
//     vit: 'A'
// }])

var number = readline();
var input = []
for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: inp[0],
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    // sortedArr = {}
    // costSorted.forEach((value) => {
    //     sortedArr[value[0]] = value[1];
    // })

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1]
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //  console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 100,
//     vit: 'A'
// }, {
//     cost: 355,
//     vit: 'BCA'
// }, {
//     cost: 150,
//     vit: 'BC'
// }, {
//     cost: 160,
//     vit: 'AC'
// }, {
//     cost: 180,
//     vit: 'B'
// }, {
//     cost: 190,
//     vit: 'CA'
// }])

// foo([{
//     cost: 10,
//     vit: 'AB'
// }, {
//     cost: 15,
//     vit: 'BA'
// }])

// foo([{
//     cost: 5,
//     vit: 'BA'
// }, {
//     cost: 11,
//     vit: 'CB'
// }])

// foo([{
//     cost: 5,
//     vit: 'C'
// }, {
//     cost: 6,
//     vit: 'B'
// }, {
//     cost: 16,
//     vit: 'BAC'
// }, {
//     cost: 4,
//     vit: 'A'
// }])


'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 output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    /*let N = readline();

    for (let test = 0; test < N; test++) {

        output(result);
    }*/
    let [n, m] = readline().split(' ').map(Number);
    let arr = readline().split(' ').map(Number);

    let prefix = new Array(n).fill(0);
    for (let i = 1; i < n; i++) {
        let cost = arr[i - 1] > arr[i] ? arr[i - 1] - arr[i] : 0;
        prefix[i] = prefix[i - 1] + cost;
    }

    let suffix = new Array(n).fill(0);
    for (let i = n - 2; i >= 0; i--) {
        let cost = arr[i + 1] > arr[i] ? arr[i + 1] - arr[i] : 0;
        suffix[i] = suffix[i + 1] + cost;
    }

    for (let test = 0; test < m; test++) {
        let [s, t] = readline().split(' ').map(Number).map(x => x - 1);

        let result = 0;
        if (s > t) {
            result = suffix[t] - suffix[s];
        } else {
            result = prefix[t] - prefix[s];
        }
        output(result);
    }
}

'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 tests = 1;
    for (let t = 0;t < tests; ++t) {
        var nq = readline().split(' ').map((x)=>parseInt(x));
        var arr = readline().split(' ').map((x) => parseInt(x));
        var pref = Array(nq[0]+1).fill(0);
        var suff = Array(nq[0]+1).fill(0);
        let  n = nq[0];
        // console.log(arr);

        for (let i = 1;i < nq[0];++i) {
            if (arr[i] < arr[i-1]) {
                pref[i+1] = arr[i-1] - arr[i];
            }
            if (arr[n-1-i] < arr[n-i]) {
                suff[n-i] = arr[n-i] - arr[n-1-i];
            }
            pref[i+1] = pref[i+1] + pref[i];
            suff[n-i] = suff[n+1-i] + suff[n-i];
        }
        // console.log(pref);
        // console.log(suff);

        for (let i = 0;i < nq[1];++i) {
            var st = readline().split(' ').map((x)=>parseInt(x));
            if (st[0] < st[1]) {
                console.log(pref[st[1]] - pref[st[0]]);
            } else {
                console.log(suff[st[1]] - suff[st[0]]);

            }
            // console.log(st);
        }
    }

}

'use strict';

function solve(n, m, a, b) {
  const l = new Array(n),
        r = new Array(n);
  for (let i = 0; i < n; i++) {
    var _l, _a;
    l[i] = ((_l = l[i - 1]) !== null && _l !== void 0 ? _l : 0) + Math.max(0, ((_a = a[i - 1]) !== null && _a !== void 0 ? _a : a[i]) - a[i]);
  }
  for (let i = n - 1; i >= 0; i--) {
    var _r, _a2;
    r[i] = ((_r = r[i + 1]) !== null && _r !== void 0 ? _r : 0) + Math.max(0, ((_a2 = a[i + 1]) !== null && _a2 !== void 0 ? _a2 : a[i]) - a[i]);
  }
  const res = new Array(m);
  for (let i = 0; i < m; i++) {
    const [x, y] = b[i].map(num => num - 1);
    if (x === y) res[i] = 0;else if (x < y) {
      res[i] = l[y] - l[x];
    } else {
      res[i] = r[y] - r[x];
    }
  }
  return res.join('\n');
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      const b = [];
      let tmp = m;
      while (tmp--) {
        b.push((await read()).split(' ').map(Number));
      }
      res[i] = solve(n, m, a, b);
    }
    return 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', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});


const n = Number(readline());
print((s => {
  var count = 0;
  var mismatch = false;
  for (var c of s)
    if (c === "(") count++;
    else if (count) count--;
    else {
      if (mismatch) return false;
      else mismatch = true;
    }
  return count === (mismatch ? 1 : 0);
})(readline().substring(0, n)) ? "Yes" : "No");


'use strict';

function obtain(s, t) {
  const m = s.length;
  const n = t.length;

  const next = Array(m+1);
  next[m] = {};
  for (let i = s.length-1; i >= 0; i--) {
    next[i] = Object.assign({}, next[i+1]);
    next[i][s[i]] = i;
  }

  let res = 1;
  let i = 0, j = 0;
  while (j < n) {
    if (i >= m) {
      i = 0;
      res++;
    }
    if (next[i][t[j]] === undefined) {
      i = 0;
      if (next[i][t[j]] === undefined) {
        return -1;
      }
      res++;
    }
    i = next[i][t[j]] + 1;
    j++;
  }

  return res;
}

function main() {
  const t = Number(readline());
  for (let i = 0; i < t; i++) {
    const s = readline();
    const t = readline();
    const res = obtain(s, t);
    print(res);
  }
}

main();

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let i = 0

  T=+input[0];
  for (x=0;x<T;x++){
          s=input[x*2+1]
          t=input[x*2+2]
          n=s.length
          dp=new Array(n+1)
          for (i=0;i<=n;i++)
            dp[i]=new Array(26)
          for (i=0;i<26;i++)
            dp[n][i]=-1

          for (i=s.length-1;i>=0;i--){
              for (j=0;j<26;j++)
                dp[i][j]=dp[i+1][j]
              dp[i][s.charCodeAt(i)-'a'.charCodeAt(0)]=i
          }
        ans=1
        pos=0
        for (i=0;i<t.length;i++){
            w=dp[pos][t.charCodeAt(i)-'a'.charCodeAt(0)]
            if (w==-1){
                ++ans
                pos=dp[0][t.charCodeAt(i)-'a'.charCodeAt(0)]+1
                if (pos==0){
                    ans=-1000000
                    break
                }
            } else {
                pos=w+1
            }
        }
        if (ans==-1000000)
            ans=-1
        wr(ans)
  }

}

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

let input = ''
let ptr = 0
process.stdin.on('data', (i) => {
  input += i
})

process.stdin.on('end', () => {
  input = input.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main()
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt() {
  return parseInt(input[ptr++])
}

function readString() {
  return input[ptr++]
}

function readStrings() {
  return input[ptr++].split(' ')
}

function readInts() {
  return input[ptr++].split(' ').map(a => parseInt(a))
}

function main() {
  let t  = readInt()
  while(t--) {
    const s = readString()
    const t = readString()
    let map = {}
    const sL = s.length
    const tL = t.length
    for(let i = 0; i < sL; i++) {
      if(!map[s[i]]) map[s[i]] = [i]
      else map[s[i]].push(i)
    }
    let curr = -1
    let count = 1
    let f = true
    for(let i = 0; i < tL; i++) {
      if(!map[t[i]]) {
        f = false
        break
      }
      // wr('curr', t[i], curr)
      let x = findMe(map[t[i]], curr)
      // wr('x', x, map[t[i]])
      if(x !== -1) curr = x
      else {
        count++
        curr = map[t[i]][0]
      }
    }
    if(!f) wr(-1)
    else wr(count)
  }

  function findMe(a, n) {
    let i = 0, j = a.length - 1
    while(i < j) {
      let m = Math.floor((i + j) / 2)
      // wr(i, m, j)
      if(a[m] <= n) {
        i = m + 1
      }
      else if(a[m] > n) {
        j = m
      }
    }
    if(a[i] > n) return a[i]
    else return -1
  }
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let i = 0

  T=+input[0];
  for (x=0;x<T;x++){
          s=input[x*2+1]
          t=input[x*2+2]
          n=s.length
          dp=new Array(n+1)
          for (i=0;i<=n;i++)
            dp[i]=new Array(26)
          for (i=0;i<26;i++)
            dp[n][i]=-1

          for (i=s.length-1;i>=0;i--){
              for (j=0;j<26;j++)
                dp[i][j]=dp[i+1][j]
              dp[i][s.charCodeAt(i)-'a'.charCodeAt(0)]=i
          }
        ans=1
        pos=0
        for (i=0;i<t.length;i++){
            w=dp[pos][t.charCodeAt(i)-'a'.charCodeAt(0)]
            if (w==-1){
                ++ans
                pos=dp[0][t.charCodeAt(i)-'a'.charCodeAt(0)]+1
                if (pos==0){
                    ans=-1000000
                }
            } else {
                pos=w+1
            }
        }
        if (ans==-1000000)
            ans=-1
        wr(ans)
  }

}


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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = new Array(N);
		for(var i = 0; i < N; i++){
			list[i] = {
				no : i,
				count : nextInt()
			};
		}
		list.sort(function(a,b){
			return b.count - a.count;
		});
		var output = new Array(N + 1);
		output[0] = 0;
		var sum = 0;
		for(var i = 0; i < N; i++){
			var index = Math.floor(i / 2) + 1;
			if(i % 2 == 1){
				index *= -1;
			}
			output[list[i].no + 1] = index;
			sum += 2 * Math.abs(index) * list[i].count;
		}
		myout(sum);
		myout(myconv(output, 8));
	}
}

process.stdin.setEncoding('utf-8')
const readline = require('readline')

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

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data * 2
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function solve([n], arr) {
    const mp = arr.map((i, index) => ([i, index])).sort((a, b) => a[0] - b[0]).reverse()
    const ans = new Array(n).fill(0)
    let currentSide = true;
    let k = 1
    let minTime = 0;
    mp.forEach((i) => {
        let index = i[1]
        if (currentSide) {
            ans[index] = k
        } else {
            ans[index] = -k
            k++
        }
        currentSide = !currentSide
    })
    for (let i = 0; i < n; i++) {
        minTime += (2 * Math.abs(ans[i]) * arr[i]);
    }
    console.log(minTime)
    console.log(0 + ' ' + ans.join(' '))
}

function main() {

    for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])
}

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++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    const sorted = arr.map((x, i) => ({ x, i }))
        .sort((a, b) => b.x - a.x)
    let left = -1
    let right = 1
    const ans = Array(n)
    ans[0] = 0
    let d = 0
    for (let i = 0; i < sorted.length; i++) {
        ans[sorted[i].i + 1] = (i & 1) ? right++ : left--
        d += 2 * Math.abs(ans[sorted[i].i + 1]) * sorted[i].x
    }
    return d + '\n' + ans.join(' ')
}

const solve = (arr)=>{
     let narr = [];
     for(let i=0;i<arr.length;i++){
          let obj = {"val" : arr[i],"ind" : i};
          narr.push(obj);
     }
     narr.sort((a,b)=>b.val - a.val);
     let plus = 1,minus = 1,k=0,res = 0,obj = [];
     for(let i=0;i<narr.length;i++){
          if(!k){
               plus++;
               res += Math.abs(1-plus)*2*narr[i]["val"];
               obj[narr[i]["ind"]] = plus;
          }
          else{
               minus--;
               res+=Math.abs(1-minus)*2*narr[i]["val"];
               obj[narr[i]["ind"]] = minus;
          }
          k = !k;
     }
     console.log(res);
     let r = "1 ";
     for(let i=0;i<obj.length;i++) r+=obj[i]+" ";
     console.log(r);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(arr);
  }
}
main();

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

		for (let i = 0; i < n; i++) {
			a[i] = [a[i], i];
		}
		a.sort((x, y) => y[0] - x[0]);

		const ans = [0];
		let dist = 0;
		for (let i = 0; i < n; i++) {
			ans[a[i][1]+1] = Math.ceil((i+1)/2) * (i&1 ? 1 : -1);
			dist += 2*a[i][0]*Math.abs(ans[a[i][1]+1]);
		}

		console.log(dist);
		console.log(ans.join(' '));
	}
}

var t = parseInt(readline());

  while (t--) {
    var n = parseInt(readline());
    var input2 = readline().split(" ");
    var arr = [];
    for (var i = 0; i < n; i++) {
      arr.push({
        value: parseInt(input2[i]),
        index: i,
      });
    }

    arr.sort((a, b) => {
      if (a.value > b.value) {
        return 1;
      } else if (a.value < b.value) {
        return -1;
      } else {
        return 0;
      }
    });

    var time = 0;
    var ans = [];
    var idx = 1;
    for (var i = n - 1; i >= 0; i -= 2) {
      var temp = 2 * idx;
      time = time + arr[i].value * temp;
      ans[arr[i].index] = idx;
      idx++;
    }

    idx = -1;
    for (var i = n - 2; i >= 0; i -= 2) {
      var temp = 2 * Math.abs(idx);
      time = time + arr[i].value * temp;
      ans[arr[i].index] = idx;
      idx--;
    }
    print(time);
    var val = "0 ";
    for (var i = 0; i < n; i++) val += ans[i] + " ";
    print(val);
  }

process.stdin.setEncoding('utf-8')
const readline = require('readline')

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

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data * 2
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function solve([n], arr) {
    const mp = arr.map((i, index) => ([i, index])).reverse()
    const ans = new Array(n).fill(0)
    let currentSide = true;
    let k = 1
    let minTime = 0;
    mp.forEach((i) => {
        let value = i[0]
        let index = i[1]
        if (currentSide) {
            ans[index] = k
        } else {
            ans[index] = -k
            k++
        }
        currentSide = !currentSide
    })
    for (let i = 0; i < n; i++) {
        minTime += (2 * Math.abs(ans[i]) * arr[i]);
    }
    console.log(minTime)
    console.log(0 + ' ' + ans.join(' '))
}

function main() {
    for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])
}

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++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    const sorted = arr.map((x, i) => ({ x, i }))
        .sort((a, b) => b.x - a.x)
    let left = -1
    let right = 1
    const ans = Array(n)
    ans[0] = 0
    for (let i = 0; i < sorted.length; i++) {
        ans[sorted[i].i + 1] = (i & 1) ? right++ : left--
    }
    return ans.join(' ')
}

  var t = parseInt(readline());

  while (t--) {
    var n = parseInt(readline());
    var input2 = readline().split(" ");
    var arr = [];
    for (var i = 0; i < n; i++) {
      arr.push({
        value: parseInt(input2[i]),
        index: i,
      });
    }

    arr.sort((a, b) => {
      if (a.value > b.value) {
        return 1;
      } else if (a.value < b.value) {
        return -1;
      } else {
        return 0;
      }
    });

    var time = 0;
    var ans = [];
    var idx = 1;
    for (var i = n - 1; i >= 0; i -= 2) {
      var temp = 2 * idx;
      time = time + arr[i].value * temp;
      ans[arr[i].index] = idx;
      idx++;
    }

    idx = -1;
    for (var i = n - 2; i >= 0; i -= 2) {
      var temp = 2 * Math.abs(idx);
      time = time + arr[i].value * temp;
      ans[arr[i].index] = idx;
      idx--;
    }
    print(time);
    var val = "";
    for (var i = 0; i < n; i++) val += ans[i] + " ";
    print(val);
  }