        /////////////////////////// JavaScript Lover /////////////////////////////////////
             ////////////////////      ShixyCat       //////////////////////////////
var t = parseInt(readline())
for(var i=0 ; i<t ; i++){
    var n = parseInt(readline())
    var arr = readline().split(" ").map(function(x) { return parseInt(x); });

    var oddFlag =0;
    for(var j=0 ; j<n; j++) if(arr[j]%2 !=0){
        oddFlag =1;
        break;
    }

    var cnt =0;
    if(oddFlag){
        for(var j=0 ; j<n; j++) if(arr[j]%2 ==0) cnt++;
    }else{
       //var min = ;
       var arrTemp = [];
       for(var j=0 ; j<arr.length;j++)arrTemp[j]=0;

       for(var j = 0 ; j<arr.length ;j++){
          for(var k = 0 ; ;k++){
           if(arr[j] % 2 != 0) break;
           arr[j]  = arr[j] /2;
           arrTemp[j]++;
          }
       }
       //print(arrTemp)
        cnt = Math.min(...arrTemp) + arr.length -1;
    }

    print(cnt);
}

let ryan = '';//.map(Numaer).sort(function(a, a){return a - a})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
   var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var a = lines[i].split(' ').map(Number);
            var e = 0, min = 2e9;
            for(j = 0; j < n; j++){
                if(a[j] % 2 === 0){
                    e++;
                }
                var m = 0;
                while(a[j] % 2 === 0){
                    m++;
                    a[j] /= 2;
                }
                min = Math.min(min, m);
            }
            console.log(min === 0 ? e : min + e - 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) {
    let odd = 0
    let even = 0
    let min = Infinity
    const ks = arr.map(x => {
        let k = 0
        while (!(x & 1)) {
            x /= 2
            k++
        }
        if (k) {
            even++
            if (k < min) min = k
        } else {
            odd++
        }
        return k
    })
    // console.log(even ? min + (even - 1) : 0)
    if (even) {
        if (odd) {
            return even
        } else {
            return min + (even - 1)
        }
    } else {
        return 0
    }
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var a = lines[i].split(' ').map(Number);
            var e = 0, min = 2e9;
            for(j = 0; j < n; j++){
                if(a[j] % 2 === 0){
                    e++;
                }
                var m = 0;
                while(a[j] % 2 === 0){
                    m++;
                    a[j] /= 2;
                }
                min = Math.min(min, m);
            }
            console.log(min === 0 ? e : min + e - 1);
        }
    }
});

'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++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);

        let odd = arr.filter(x => x % 2 === 1);
        let even = arr.filter(x => x % 2 === 0);

        if (odd.length > 0) {
            output(even.length);
        } else {
            let min = Infinity;
            for (let i = 0; i < even.length; i++) {
                let count = 0;
                while (even[i] % 2 === 0) {
                    even[i] /= 2;
                    count++;
                }
                if (count < min) {
                    min = count;
                }
            }
            output(even.length + min - 1);
        }

    }
}

const readline = require("readline");

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

class Input {
	constructor(line) {
		this.pointer = -1;
		this.content = [line];
	}
	add(line) {
		this.content.push(line);
	}
	get(line) {
		if (!(this.pointer < this.content.length - 1)) {
			return -1
		}
		return this.content[++this.pointer];
	}
}

const intify = (arr) => {
	if (typeof arr == "string") {
		let temp = "";
		for (let i = 0; i < arr.length; i++) {
			if (arr[i] != ' ') {
				temp += arr[i];
			}
		}
		return parseInt(temp)
	} else {
		return arr.map(ele => parseInt(ele))
	}
}

rl.once("line", line => {
	let inp = new Input(line);
	rl.on("line", line => {
		inp.add(line)
	}).on("close", () => {

		let t = intify(inp.get());
		while (t--) {
			let n = intify(inp.get())
			let arr = intify(inp.get().split(' '))
			let evens = 0;
			let odds = 0;
			for (let i = 0; i < arr.length; i++) {
				if (arr[i] % 2 == 1) {
					odds++;
				} else {
					evens++;
				}
			}
			if (odds > 0) {
				console.log(evens);
			} else {
				let minimum = 40;
				for (let i = 0; i < arr.length; i++) {
					let count = 0;
					while (arr[i] > 1 && arr[i] % 2 == 0) {
						arr[i] /= 2;
						count++;
					}
					minimum = Math.min(minimum, count)
				}
				console.log((arr.length - 1) + minimum);
			}
		}

    });
});

function getRes(countOfEven, minTwoDegree, n) {
    if (countOfEven < n) {
        return countOfEven;
    } else {
        return minTwoDegree + countOfEven - 1;
    }
}

function main() {
    let t = +readline();
    while (t > 0) {
        const n = +readline();
        const ticketsData = readline().split(' ');
        let countOfEven = 0;
        let minTwoDegree = null;

        ticketsData.forEach(ticketData => {
            let numTicketData = +ticketData;

            if ((numTicketData & 1) === 0) {
                ++countOfEven;
            }

            let degree = 0;

            while ((numTicketData & 1) === 0) {
                numTicketData >>= 1;
                ++degree;
            }

            if (degree < minTwoDegree || minTwoDegree === null) {
                minTwoDegree = degree;
            }
        });

        console.log(getRes(countOfEven, minTwoDegree, n));

        --t;
    }
}

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

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

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

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

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const getDigits = (x) => {
    let digits = new Array(10).fill(false);
    let len = 0;
    while (x) {
        len++;
        digits[x % 10n] = true;
        x /= 10n;
    }
    return [digits, len];
}

const getLen = (x) => {
    let str = x.toString(10);
    return str.length;
}

const get2 = (x) => {
    let two = 0;
    while (x % 2 === 0) {
        two++;
        x /= 2;
    }
    return two;
}

const calc = (t)=>{
    /* read */
    let n = +readline();
    let a = ra();
    let twos = new Array(n);
    let minTwos = Infinity;
    let maxTwos = -1;
    let even = 0;
    let odd = 0;

    for (let i = 0; i < n; i++) {
        twos[i] = get2(a[i]);
        minTwos = Math.min(minTwos, twos[i]);
        maxTwos = Math.max(maxTwos, twos[i]);
        if (twos[i] > 0) even++;
        else odd++;
    }

    if (maxTwos === 0) return 0;

    if (minTwos === 0) return even;

    return minTwos + n - 1;
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc(t));
        // process.stdout.write(`${calc(t)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

'use strict';

function solve(n, a) {
  let even = 0,
      odd = 0;
  for (let num of a) {
    if (num & 1) {
      odd++;
    } else {
      even++;
    }
  }
  if (odd) return even;
  let min = Infinity;
  for (let num of a) {
    for (let i = 0; i < 31; i++) {
      if (num & 1 << i) {
        min = Math.min(min, i);
        break;
      }
    }
  }
  return min + n - 1;
}

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

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

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL); /*your input text, split by lines*/
    var n = lines[0]
    for(j = 1; j <= n; j++){
        k = lines[j].split('').map(Number)
        b = lines[j]

        k[0] -= 1
        if(k[0] === 0 && k.length < 1){
            k.splice(0,1)
        }
        console.log(k.join(''))

    }

});

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +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) {
    let even = 0
    let min = Infinity
    const ks = arr.map(x => {
        let k = 0
        while (!(x & 1)) {
            x /= 2
            k++
        }
        if (k) {
            even++
            if (k < min) min = k
        }
        return k
    })
    return even ? min + (even - 1) : 0
}

        /////////////////////////// JavaScript Lover /////////////////////////////////////
             ////////////////////      ShixyCat       //////////////////////////////
var t = parseInt(readline())
for(var i=0 ; i<t ; i++){
    var n = parseInt(readline())
    var arr = readline().split(" ").map(function(x) { return parseInt(x); });

    var oddFlag =0;
    for(var j=0 ; j<n; j++) if(arr[j]%2 !=0){
        oddFlag =1;
        break;
    }

    var cnt =0;
    if(oddFlag){
        for(var j=0 ; j<n; j++) if(arr[j]%2 ==0) cnt++;
    }else{
       var min = Math.min(...arr);
       for(var j = 0 ; ;j++){
           if(min%2 != 0) break;
           min = min/2;
           cnt++
       }
        cnt += arr.length-1;
    }

    print(cnt);
}

        /////////////////////////// JavaScript Lover /////////////////////////////////////
             ////////////////////      ShixyCat       //////////////////////////////
var t = parseInt(readline())
for(var i=0 ; i<t ; i++){
    var n = parseInt(readline())
    var arr = readline().split(" ").map(function(x) { return parseInt(x); });

    var oddFlag =0;
    for(var j=0 ; j<n; j++) if(arr[j]%2 !=0){
        oddFlag =1;
        break;
    }

    var cnt =0;
    if(oddFlag){
        for(var j=0 ; j<n; j++) if(arr[j]%2 ==0) cnt++;
    }else{
       var min = Math.min(...arr);
       for(var j = 0 ; j<n;j++){
           if(min%2 != 0) break;
           min = min/2;
           cnt++
       }
        cnt += arr.length-1;
    }

    print(cnt);
}

        /////////////////////////// JavaScript Lover /////////////////////////////////////
             ////////////////////      ShixyCat       //////////////////////////////
var t = parseInt(readline())
for(var i=0 ; i<t ; i++){
    var n = parseInt(readline())
    var arr = readline().split(" ").map(function(x) { return parseInt(x); });

    var oddFlag =0;
    for(var j=0 ; j<n; j++) if(arr[j]%2 !=0){
        oddFlag =1;
        break;
    }

    var cnt =0;
    if(oddFlag){
        for(var j=0 ; j<n; j++) if(arr[j]%2 ==0) cnt++;
    }else{
       var min = Math.min(...arr);
       for(var j = 0 ; j<10;j++){
           if(min%2 != 0) break;
           min = min/2;
           cnt++
       }
        cnt += arr.length-1;
    }

    print(cnt);
}


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

    testLoop: for (let test = 0; test < N; test++) {
        let [n, x] = readline().split(' ').map(Number);
        let arr = readline().split(' ').map(Number);

        // sort array ascending:
        arr.sort((a, b) => a - b);

        let no = false;
        for (let i = 0; i < n; i++) {
            let diff = arr[n + i] - arr[i];
            if (diff < x) {
                no = true;
            }
        }

        output(no ? 'NO' : 'YES');
    }
}

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function isPossible(n, x, heights) {
    heights.sort();
    heights.sort(function(a, b) {
        return a - b;
      });
    // console.log(heights)

    let front = []
    let back = []

    for (let i = 0; i < heights.length; i++) {
        if (i < n) {
            front.push(heights[i])
        } else {
            back.push(heights[i])
        }
    }

    // console.log(front)
    // console.log(back)
    for (let j = 0; j < front.length; j++) {
        if (back[j] - front[j] < x) {
            // console.log(back[j] + " " + front[j])
            return "NO";
        }
    }

    return "YES";
}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        const n_x = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
        const n = n_x[0];
        const x = n_x[1];

        if ((n >= 1 && n <= 100) && (x >= 1 && x <= 1000)) {
            const heights = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            if (heights.length == 2*n) {
                const result = isPossible(n, x, heights);
                console.log(result)
            }
        }
        // ws.write(result + '\n');
    }

    // ws.end();
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, x = 0;
    for(i = 1; i <= t * 2; i++){
        var k = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = k[0], x = k[1];
        }else{
            k = k.sort(function(a, b){return a - b});
            var f = [], s = [];
            for(j = 0; j < n * 2; j++){
                if(j < n){
                    f.push(k[j]);
                }else{
                    s.push(k[j]);
                }
            }
            var a = false;
            for(j = 0; j < n; j++){
                if(s[j] - f[j] < x){
                    a = true;
                }
            }
            console.log(!a ? 'YES' : 'NO');
        }
    }

});

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, x = 0;
    for(i = 1; i <= t * 2; i++){
        var k = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = k[0] * 2, x = k[1];
        }else{
            k = k.sort(function(a, b){return a - b});
            var f = [];
            var s = [];
            for(j = 0; j < n; j++){
                if(j < n / 2){
                    f.push(k[j]);
                }else{
                    s.push(k[j]);
                }
            }
            var a = false;
            for(j = 0; j < n / 2; j++){
                if(s[j] - f[j] < x){
                    a = true;
                }
            }
            console.log(!a ? '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(){
    var tests = parseInt(readline());
    for (let t = 0;t < tests; ++t) {
        var nm = readline().split(" ").map(x => parseInt(x));
        let n = nm[0];
        let m = nm[1];
        let res = true;
        var arr = readline().split(" ").map(x=> parseInt(x));
        arr.sort((n1,n2) => {return n1-n2;});
        for (let i = 0;i < n;++i) {
            if (arr[i+n] - arr[i] < m) {
                res = false;
            }
        }
        console.log((res?'YES':'NO'));
    }

}

function photographer() {
  let [n, dx] = r().split` `.map(Number);
  a = r().split` `.map(Number).sort((a, b) => a - b);
  heights = a.slice(0, n).map((d, i) => a[i + n] >= d + dx);
  return heights.every(d => d) ? 'YES' : 'NO';
}

function main() {
  tt = +r();
  for (; tt; tt--) log(photographer());
}

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++];
}

r = readline;
log = console.log;

'use strict';
/*
Mark is asked to take a group photo of 2n people. The i-th person has height hi units.

To do so, he ordered these people into two rows, the front row and the back row, each consisting of n people. However, to ensure that everyone is seen properly, the j-th person of the back row must be at least x units taller than the j-th person of the front row for each j between 1 and n, inclusive.

Help Mark determine if this is possible.
*/
const main = () => {
  const n = parseInt(readline());

  for (let i = 0; i < n; ++i) {
    const [k, minDiff] = readline().split(' ').map(Number);
    const heights = readline().split(' ').map(Number);
    heights.sort((a, b) => a - b);
    let result = true;
    for (let j = 0; j < k; ++j) {
      if (heights[j + k] < heights[j] + minDiff) {
        result = false;
        break;
      }
    }
    console.log(result ? 'YES' : 'NO');
  }
};

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

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

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, d] = readline()
      .trim(" ")
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    arr.sort((a, b) => a - b);
    let i = 0,
      ans = true;
    while (i < n) {
      if (arr[i + n] - arr[i] < d) {
        ans = false;
        break;
      }
      i++;
    }
    console.log(`${ans === true ? "YES" : "NO"}`);
  }
};
solve();

T = readline()

while(T--){
  nx = readline().split(' ').map(el => +el)
  n = nx[0]
  x = nx[1]

  h = readline().split(' ').map(el => +el)
  h.sort((next, prev) => next - prev)

  ans = 'YES'
  for(i = 0; i < n; i++){
    for(j = n; j < n*2; j++){

      if(h[j] - h[i] < x){
        ans = 'NO'
        break
      }
      if(ans == 'NO')
        break
      i++
    }
  }

  print(ans)
}

var tests = parseInt(readline());
    for (var t=0; t < tests; t++) {
        var nx = readline().split(' ').map(x=>parseInt(x));
        var n = nx[0];
        var arr = readline().split(' ').map(x=>parseInt(x));
        arr.sort((a,b)=>a-b);
        var ans = 'yes';
        for (var i =0; i < n; i++) {
            if (arr[i+n] - arr[i] < nx[1]) {
                ans = 'no';
                break;
            }
        }
        print(ans);
    }

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function isPossible(n, x, heights) {
    heights.sort();

    let front = []
    let back = []

    for (let i = 0; i < heights.length; i++) {
        if (i < n) {
            front.push(heights[i])
        } else {
            back.push(heights[i])
        }
    }

    if (back[0] - front[0] >= x) {
        return "YES"
    } else {
        return "NO"
    }
}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        const n_x = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
        const n = n_x[0];
        const x = n_x[1];

        if ((n >= 1 && n <= 100) && (x >= 1 && x <= 1000)) {
            const heights = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            if (heights.length == 2*n) {
                const result = isPossible(n, x, heights);
                console.log(result)
            }
        }
        // ws.write(result + '\n');
    }

    // ws.end();
}

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function isPossible(n, x, heights) {
    // console.log(n)
    // console.log(x)
    // console.log(heights)

    heights.sort();

    let front = []
    let back = []

    for (let i = 0; i < heights.length; i++) {
        if (i < n) {
            front.push(heights[i])
        } else {
            back.push(heights[i])
        }
    }

    // console.log(front)
    // console.log(back)

    if (back[0] - front[0] >= x) {
        return "YES"
    } else {
        return "NO"
    }
}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
       const n_x = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
        const n = n_x[0];
        const x = n_x[1];
        const heights = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));

        const result = isPossible(n, x, heights);

        console.log(result)
        // ws.write(result + '\n');
    }

    // ws.end();
}


var pair = readline().split(' '),
    n = +pair[0],
    k = +pair[1],
    servers = {
        'parent': function(i) {
            return Math.floor((i-1)/2);
        },
        'children': function(i) {
            return [2*i + 1, 2*i + 2];
        },
        'index': [],
        'heapify': function() {
            var i = 0,
                index = this.index,
                j,
                k,
                l = index.length,
                temp;
            while ((j = this.children(i))[0] < l
                && (index[i] >= index[j[0]] || index[i] >= index[j[1]])) {
                k = (j[1] >= l || index[j[0]] < index[j[1]]) ? j[0] : j[1];
                temp = index[i];
                index[i] = index[k];
                index[k] = temp;
                i = k;
            }
        }
    },
    s,
    m,
    e = [],
    i = 0;
for (;i<k;i++) {
    servers.index[i] = 0;
}
for (i=0;i<n;i++) {
    pair = readline().split(' ');
    s = +pair[0];
    m = +pair[1];
    e[i] = servers.index[0] = Math.max(servers.index[0], s) + m;
    servers.heapify();
}
print(e.join(' '));

var BinaryHeap = (function() {
    function BinaryHeap(predicate) {
        this.predicate = predicate || function(a, b) { return a > b; };

        this.items = new Float64Array(1 + 1) /* zero index + initial capacity */;
        this.count = 0;
    }

    BinaryHeap.prototype.toArray = function() {
        var array = [];
        for (var i = 1; i <= this.count; i++) {
            array.push(this.items[i]);
        }
        return array;
    };

    BinaryHeap.prototype.insert = function(item) {
        this.items[++this.count] = item;

        /* ensure binary heap invariant */
        var child = this.count;
        var parent = child >> 1;
        while (child > 1 && this.predicate(this.items[child], this.items[parent])) {
            var tmp = this.items[child];
            this.items[child] = this.items[parent];
            this.items[parent] = tmp;

            child = parent;
            parent = child >> 1;
        }

        /* expand array if necessary */
        if (this.count === this.items.length - 1) {
            this.resize(this.count * 2 + 1);
        }
    };

    BinaryHeap.prototype.delete = function() {
        if (this.count === 0) throw "Heap is empty";

        var item = this.items[1];
        this.items[1] = this.items[this.count];
        this.items[this.count--] = null;

        /* ensure binary heap invariant */
        var parent = 1;
        var child = parent << 1;
        while (child <= this.count) {
            if (child < this.count) {
                child = this.predicate(this.items[child], this.items[child + 1]) ? child : child + 1;
            }

            if (this.predicate(this.items[parent], this.items[child])) break;

            var tmp = this.items[parent];
            this.items[parent] = this.items[child];
            this.items[child] = tmp;

            parent = child;
            child = parent << 1;
        }

        /* shrink array if necessary */
        if (this.count === this.items.length / 4) {
            resize(this.count * 2 + 1);
        }

        return item;
    };

    BinaryHeap.prototype.length = function() {
        return this.count;
    };

    BinaryHeap.prototype.resize = function(capacity) {
        var items = new Float64Array(capacity);
        for (var i = 0; i <= this.count; i++) {
            items[i] = this.items[i];
        }
        this.items = items;
    };

    return BinaryHeap;
})();

/*var lines = [];
lines[0] = "6 1";
lines[1] = "1 1000000000";
lines[2] = "2 1000000000";
lines[3] = "3 1000000000";
lines[4] = "4 1000000000";
lines[5] = "5 1000000000";
lines[6] = "6 3";
var line = 0;
function readline() {
	return lines[line++];
}*/

function readn() {
	return +readline();
}
function parsens(s) {
	return 	s.split(" ").map(function(x) { return +x; });
}
function sortNumbers(a,b) {
	return a-b;
}

var numbers = parsens(readline());
var videosCount = numbers[0];
var serversCount = numbers[1];
var videoIn = [];
var videoSize = [];
for (var i = 0; i < videosCount; i++) {
	var numbers = parsens(readline());
	videoIn[i] = numbers[0];
	videoSize[i] = numbers[1];
}

//console.log(videoIn);
//console.log(videoSize);

var videoOut = [];
var heap = new BinaryHeap(function(a,b){return a<b});
for (var i = 0; i < serversCount; i++) {
	heap.insert(0);//enq()
}

//debugger;
for (var videoIndex = 0; videoIndex < videosCount; videoIndex++) {
	var time = videoIn[videoIndex];
	var size = videoSize[videoIndex];
	var nearestFreeServerTime = Math.max(time, heap.delete());//deq()
	var outTime = nearestFreeServerTime + size;
	heap.insert(outTime);//enq()
	videoOut[videoIndex] = outTime;
}

for (var i = 0; i < videosCount; i++) {
	print(videoOut[i]);//
	//console.log(videoOut[i]);
}

var pair = readline().split(' '),
    n = +pair[0],
    k = +pair[1],
    servers = {
        'parent': function(i) {
            return Math.floor((i-1)/2);
        },
        'children': function(i) {
            return [2*1 + 1, 2*i + 2];
        },
        'index': [],
        'heapify': function() {
            var i = 0,
            index = this.index,
            j,
            k,
            l = index.length - 1,
            temp;
            while ((j = this.children(i))[0] < l
                && (index[i] >= index[j[0]] || index[i] >= index[j[1]])) {
                k = (j[1] >= l || index[j[0]] < index[j[1]]) ? j[0] : j[1];
                temp = index[i];
                index[i] = index[k];
                index[k] = temp;
                i = k;
            }
        }
    },
    s,
    m,
    e = [],
    i = 0;
for (;i<k;i++) {
    servers.index[i] = 0;
}
for (i=0;i<n;i++) {
    pair = readline().split(' ');
    s = +pair[0];
    m = +pair[1];
    e[i] = servers.index[0] = Math.max(servers.index[0], s) + m;
    servers.heapify();
}
print(e.join(' '));

var pair = readline().split(' '),
	n = +pair[0],
	k = +pair[1],
	servers = [],
	s,
	m,
	e,
	i = 0;
for (;i<k;i++) {
	servers[i] = 0;
}
for (i=0;i<n;i++) {
	pair = readline().split(' ');
	s = +pair[0];
	m = +pair[1];
	e = Math.max(servers[0], s) + m;
	print(e);
	servers[0] = e;
	servers.sort();
}

var pair = readline().split(' '),
	n = +pair[0],
	k = +pair[1],
	servers = [],
	s,
	m,
	e = [],
	i = 0;
for (;i<k;i++) {
	servers[i] = 0;
}
for (i=0;i<n;i++) {
	pair = readline().split(' ');
	s = +pair[0];
	m = +pair[1];
	e[i] = servers[0] = Math.max(servers[0], s) + m;
	servers.sort(function(a,b){
		return a < b;
	});
}
print(e.join(' '));

var pair = readline().split(' '),
	n = +pair[0],
	k = +pair[1],
	servers = [],
	s,
	m,
	e = [],
	i = 0;
for (;i<k;i++) {
	servers[i] = 0;
}
for (i=0;i<n;i++) {
	pair = readline().split(' ');
	s = +pair[0];
	m = +pair[1];
	e[i] = servers[0] = Math.max(servers[0], s) + m;
	servers.sort();
}
print(e.join(' '));

var BinaryHeap = (function() {
    function BinaryHeap(predicate) {
        this.predicate = predicate || function(a, b) { return a > b; };

        this.items = new Float64Array(1 + 1) /* zero index + initial capacity */;
        this.count = 0;
    }

    BinaryHeap.prototype.toArray = function() {
        var array = [];
        for (var i = 1; i <= this.count; i++) {
            array.push(this.items[i]);
        }
        return array;
    };

    BinaryHeap.prototype.insert = function(item) {
        this.items[++this.count] = item;

        /* ensure binary heap invariant */
        var child = this.count;
        var parent = child >> 1;
        while (child > 1 && this.predicate(this.items[child], this.items[parent])) {
            var tmp = this.items[child];
            this.items[child] = this.items[parent];
            this.items[parent] = tmp;

            child = parent;
            parent = child >> 1;
        }

        /* expand array if necessary */
        if (this.count === this.items.length - 1) {
            this.resize(this.count * 2 + 1);
        }
    };

    BinaryHeap.prototype.delete = function() {
        if (this.count === 0) throw "Heap is empty";

        var item = this.items[1];
        this.items[1] = this.items[this.count];
        this.items[this.count--] = null;

        /* ensure binary heap invariant */
        var parent = 1;
        var child = parent << 1;
        while (child <= this.count) {
            if (child < this.count) {
                child = this.predicate(this.items[child], this.items[child + 1]) ? child : child + 1;
            }

            if (this.predicate(this.items[parent], this.items[child])) break;

            var tmp = this.items[parent];
            this.items[parent] = this.items[child];
            this.items[child] = tmp;

            parent = child;
            child = parent << 1;
        }

        /* shrink array if necessary */
        if (this.count === this.items.length / 4) {
            resize(this.count * 2 + 1);
        }

        return item;
    };

    BinaryHeap.prototype.length = function() {
        return this.count;
    };

    BinaryHeap.prototype.resize = function(capacity) {
        var items = new Float64Array(capacity);
        for (var i = 0; i <= this.count; i++) {
            items[i] = this.items[i];
        }
        this.items = items;
    };

    return BinaryHeap;
})();

var lines = [];
lines[0] = "6 1";
lines[1] = "1 1000000000";
lines[2] = "2 1000000000";
lines[3] = "3 1000000000";
lines[4] = "4 1000000000";
lines[5] = "5 1000000000";
lines[6] = "6 3";
var line = 0;
function readline() {
	return lines[line++];
}

function readn() {
	return +readline();
}
function parsens(s) {
	return 	s.split(" ").map(function(x) { return +x; });
}
function sortNumbers(a,b) {
	return a-b;
}

var numbers = parsens(readline());
var videosCount = numbers[0];
var serversCount = numbers[1];
var videoIn = [];
var videoSize = [];
for (var i = 0; i < videosCount; i++) {
	var numbers = parsens(readline());
	videoIn[i] = numbers[0];
	videoSize[i] = numbers[1];
}

//console.log(videoIn);
//console.log(videoSize);

var videoOut = [];
var heap = new BinaryHeap(function(a,b){return a<b});
for (var i = 0; i < serversCount; i++) {
	heap.insert(0);//enq()
}

//debugger;
for (var videoIndex = 0; videoIndex < videosCount; videoIndex++) {
	var time = videoIn[videoIndex];
	var size = videoSize[videoIndex];
	var nearestFreeServerTime = Math.max(time, heap.delete());//deq()
	var outTime = nearestFreeServerTime + size;
	heap.insert(outTime);//enq()
	videoOut[videoIndex] = outTime;
}

for (var i = 0; i < videosCount; i++) {
	print(videoOut[i]);//
	//console.log(videoOut[i]);
}


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 n = integers[0], m = integers[1];

	var funds = [];
	for (var i = 0; i < n; i += 1) {
		funds.push(0);
	}

	for (var i = 0; i < m; i += 1) {
		var integers = tokenizeIntegers(readline());
		var a = integers[0], b = integers[1], debt = integers[2];
		funds[a-1] -= debt;
		funds[b-1] += debt;
	}

	var total = 0;
	for (var i = 0; i < n; i += 1) {
		if (funds[i] > 0) {
			total += funds[i];
		}
	}

	print(total);
}

main();

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 n = integers[0], m = integers[1];

	var funds = [];
	for (var i = 0; i < n; i += 1) {
		funds.push(0);
	}

	for (var i = 0; i < m; i += 1) {
		var integers = tokenizeIntegers(readline());
		var a = integers[0], b = integers[1], debt = integers[2];
		funds[a-1] -= debt;
		funds[b-1] += debt;
	}

	var total = 0;
	for (var i = 0; i < n; i += 1) {
		total += Math.abs(funds[i]);
	}

	print(total/2);
}

main();

var input = readline();
    input = input.split(' ');
    var people = [];
    var n = input[0],
        m = input[1];
    for(var i=0; i<n; i++) people[i]=0;
    for(var i=0; i<m; i++)
    {
        input = readline();
        input = input.split(' ');
        var a = parseInt(input[0]),
            b = parseInt(input[1]),
            c = parseInt(input[2]);
        people[a-1]-=c;
        people[b-1]+=c;
    }
    var result=0;
    for(var i=0; i<n; i++) result+=Math.abs(people[i]);
    print(result/2);

'use strict';

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

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _readline$split$map = readline().split(' ').map(Number);

var _readline$split$map2 = _slicedToArray(_readline$split$map, 2);

var n = _readline$split$map2[0];
var m = _readline$split$map2[1];var arr = [];

for (var i = 0; i < n; i++) {
  arr.push(0);
}

for (var _i = 0; _i < m; _i++) {
  var _readline$split$map3 = readline().split(' ').map(Number);

  var _readline$split$map4 = _slicedToArray(_readline$split$map3, 3);

  var a = _readline$split$map4[0];
  var b = _readline$split$map4[1];
  var c = _readline$split$map4[2];

  arr[a - 1] -= c;arr[b - 1] += c;
}

print(arr.filter(function (x) {
  return x > 0;
}).reduce(function (a, b) {
  return a + b;
}, 0));

// Generated by CoffeeScript 1.4.0
(function() {
  var a, add, b, c, d, global, i, m, max, min, n, readints, x, _i, _ref, _ref1, _ref2;

  readints = function() {
    var x, _i, _len, _ref, _results;
    _ref = readline().split(' ');
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      x = _ref[_i];
      _results.push(x | 0);
    }
    return _results;
  };

  add = function(a, b) {
    return a + b;
  };

  global = (function() {
    return this;
  })();

  _ref = [Math.max, Math.min], max = _ref[0], min = _ref[1];

  _ref1 = readints(), n = _ref1[0], m = _ref1[1];

  d = (function() {
    var _i, _results;
    _results = [];
    for (_i = 0; 0 <= n ? _i <= n : _i >= n; 0 <= n ? _i++ : _i--) {
      _results.push(0);
    }
    return _results;
  })();

  for (i = _i = 0; 0 <= m ? _i < m : _i > m; i = 0 <= m ? ++_i : --_i) {
    _ref2 = readints(), a = _ref2[0], b = _ref2[1], c = _ref2[2];
    d[a] += c;
    d[b] -= c;
  }

  d = (function() {
    var _j, _len, _results;
    _results = [];
    for (_j = 0, _len = d.length; _j < _len; _j++) {
      x = d[_j];
      _results.push(max(x, 0));
    }
    return _results;
  })();

  print(d.reduce(add));

}).call(this);

var nm = readline().trim().split(' ').map((x)=>parseInt(x));
var n=nm[0],m=nm[1];
var d = {};
var _d={};
var debt= function(a,b,c) {
	this.a=a;
	this.b=b;
	this.c=c;

	if(d[a]==undefined)
		d[a]=0;

	if(_d[b]==undefined)
		_d[b]=0;

	d[a]+=c;
	_d[b]+=c;
}

var debts=[];
var input;
for (var i = 0; i <m; i++) {
	input = readline().trim().split(' ').map((x)=>parseInt(x));
	debts.push(new debt(input[0],input[1],input[2]));
}

var ans=0;
for (var i in d) {
	ans+=Math.max(d[i]-(_d[i]==undefined?0:_d[i]),0);
}

print(ans);

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 n = integers[0], m = integers[1];

	var funds = [];
	for (var i = 0; i < n; i += 1) {
		funds.push(0);
	}

	for (var i = 0; i < m; i += 1) {
		var integers = tokenizeIntegers(readline());
		var a = integers[0], b = integers[1], debt = integers[2];
		funds[a] -= debt;
		funds[b] += debt;
	}

	var total = 0;
	for (var i = 0; i < n; i += 1) {
		if (funds[i] > 0) {
			total += funds[i];
		}
	}

	print(total);
}

main();


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

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

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

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

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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  t = inp[r++];
  while (t--) {
    let n = inp[r++];
    let a = inp.slice(r, r = r + n);
    // console.log(a);
    let i = j = 0;
    while (1) {
      while (i < n && a[i] <= 0) i++;
      while ((j <= i || (j < n && a[j] >= 0))) j++;
      if (j >= n) break;
      let v = Math.min(Math.abs(a[i]), Math.abs(a[j]));
      a[i] -= v
      a[j] += v
    }
    // console.log(a);
    let s = 0n;
    a.filter(v => v > 0).forEach(v => s += BigInt(v));
    console.log(s + '');
  }
})();

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

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

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

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

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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  t = inp[r++];
  while (t--) {
    let n = inp[r++];
    let s = c = 0;
    For(1, n, i => {
      let x = inp[r++];
      c = c + x;
      if (c < 0) { s -= c; c = 0 }
    })
    console.log(s);
  }
})();

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));
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 main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    for (let i = 0; i < len - 1; i++) {
      if (arr[i] > 0) {
        arr[i + 1] += arr[i];
        arr[i] = 0;
      }
    }

    console.log(arr[len - 1]);
  }
}

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

    B();
});

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

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

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

    return a;
}

function A(){
    let t = pi(readline());

    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        for(let i = 0; i < Math.floor(n/2); i++){
            let temp = a[i];
            a[i] = a[n-i-1];
            a[n-i-1] = temp;
        }

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

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));

        let tot = 0;
        for(let i = 0; i < n; i++){
            if(a[i] > 0)
                tot += a[i];
            else{
                if(a[i] + tot > 0){
                    tot += a[i];
                    a[i] = 0;
                }else{
                    a[i] += tot;
                    tot = 0;
                }
            }
        }

        let res = 0;
        for(let i = 0; i < n; i++)
            if(a[i] < 0)
                res += a[i];

        console.log(res !== 0 ? -1 * res : 0);
    }
}

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

        // let dp = new Array(n);
        // for(let i = 0; i < n; i++){
        //     dp[i] = new Array(k+1);
        //     for(let j = 0; j < k+1; j++){
        //         dp[i][j] = new Array(2);
        //     }
        // }

        // for(let i = 0; i < n; i++){
        //     for(let j = 0; j < k+1; j++){
        //         if(k % 2 !== 0){
        //             dp[i][j][0] = dp[i][j][1] = 0;
        //         }else{

        //         }
        //     }
        // }

        let isKBalanced = (s) => {
            let p1 = 0;
            let p2 = 0;
            let c0 = 0;
            let c1 = 0;
            while(p2-p1 <= k-1){
                if(s.charAt(p2) === '0')
                    c0++;
                else
                    c1++;
                p2++
            }
            if(c0 !== k/2 || c1 !== k/2)
                return false;

            p2--;
            while(p2 < s.length){
                p2++;
                let x = s.charAt(p1);
                p1++;
                if(p2 < s.length)
                    if(s.charAt(p2) !== x)
                        return false;
            }

            return true;
        }

        let map = {};
        let solve = (s, i) => {
            if(i >= s.length)
                return isKBalanced(s);

            if(map[`${s}_${i}`] !== undefined)
                return map[`${s}_${i}`];

            if(s.charAt(i) === '?'){
                let res0 = solve(s.substring(0,i) + '0' + s.substring(i+1, s.length), i+1);
                if(!res0)
                    return map[`${s}_${i}`] = solve(s.substring(0,i) + '1' + s.substring(i+1, s.length), i+1);
                else
                    return map[`${s}_${i}`] = res0;
            }else{
                return map[`${s}_${i}`] = solve(s, i+1);
            }
        }

        console.log(solve(str, 0) ? 'YES' : 'NO');
    }
}

function F(){
    let [n,x] = ti(readline().split(' '));
    let s = readline();
    let t = readline();

    let dp = new Array(n);
    for(let i = 0; i < n; i++){
        dp[i] = new Array(x+1);
        for(let j = 0; j <= x; j++){
            dp[i][j] = new Array(n);
            dp[i][j].fill(0);
        }
    }

    for(let i = 1; i < n; i++){
        for(let j = 0; j <= x; j++){
            for(let k = 0; k <= n; k++){
                dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j][k-1] + (s.charAt(i) === t.charAt(1) ? k-1 : 0));
                if(j !== 0){
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + (t.charAt(0) === t.charAt(1) ? k-1 : 0));
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + k-1);
                }
            }
        }
    }

    let max = 0;
    for(let i = 0; i < x; i++)
        for(let j = 0; j < n; j++)
            max = Math.max(max, dp[n-1][i][j]);

    console.log(max);
}

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));
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 main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => BigInt(n));

    let max = Number.MIN_SAFE_INTEGER;
    for (let i = 0; i < len; i++) {
      if (max < arr[i]) max = arr[i];
    }
    let sum = 0n;
    const numIndex = arr.findIndex((num) => num === max);

    for (let i = numIndex; i < len; i++) sum += arr[i];

    console.log(Number(sum));
  }
}

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));
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 main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => BigInt(n));

    if (len === 1) {
      console.log(Math.abs(Number(arr[0])));
    } else {
      let max = Number.MIN_SAFE_INTEGER;
      for (let i = 0; i < len; i++) {
        if (max < arr[i]) max = arr[i];
      }
      let sum = 0n;
      const numIndex = arr.findIndex((num) => num === max);
      if (numIndex === 0) {
        console.log(0);
      } else {
        for (let i = numIndex; i < len; i++) sum += arr[i];

        console.log(Number(sum));
      }
    }
  }
}

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));
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 main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    const max = Math.max(...arr);
    let sum = 0;
    const numIndex = arr.findIndex((num) => num === max);

    for (let i = numIndex; i < len; i++) sum += arr[i];

    console.log(sum);
  }
}

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

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

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

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

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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  t = inp[r++];
  while (t--) {
    let n = inp[r++];
    let a = inp.slice(r, r = r + n);
    let i = 0;
    let j = n - 1;
    while (1) {
      while (i < n && a[i] <= 0) i++;
      while (j >= 0 && a[j] >= 0) j--;
      if (i > j) break;
      let v = Math.min(Math.abs(a[i]), Math.abs(a[j]));
      a[i] -= v
      a[j] += v
    }
    // console.log(a);
    console.log(a.filter(v => v > 0).sum());
  }
})();

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

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

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

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

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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  t = inp[r++];
  while (t--) {
    let n = inp[r++];
    let a = inp.slice(r, r = r + n);
    // console.log(a);
    let i = 0;
    while (1) {
      while (i < n && a[i] <= 0) i++;
      let j = i + 1;
      while (j < n && a[j] >= 0) j++;
      if (j >= n) break;
      let v = Math.min(Math.abs(a[i]), Math.abs(a[j]));
      a[i] -= v
      a[j] += v
    }
    console.log(a);
    console.log(a.filter(v => v > 0).sum());
  }
})();

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

    B();
});

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

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

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

    return a;
}

function A(){
    let t = pi(readline());

    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        for(let i = 0; i < Math.floor(n/2); i++){
            let temp = a[i];
            a[i] = a[n-i-1];
            a[n-i-1] = temp;
        }

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

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));

        for(let i = 1; i < n; i++){
            if(a[i] > 0 && a[i-1] > 0){
                a[i] += a[i-1];
            }else if(a[i] < 0 && a[i-1] > 0){
                a[i] += a[i-1];
            }
        }

        let res = 0;
        for(let i = 0; i < n; i++)
            if(a[i] < 0)
                res += a[i];

        console.log(res !== 0 ? -1 * res : 0);
    }
}

function F(){
    let [n,x] = ti(readline().split(' '));
    let s = readline();
    let t = readline();

    let dp = new Array(n);
    for(let i = 0; i < n; i++){
        dp[i] = new Array(x+1);
        for(let j = 0; j <= x; j++){
            dp[i][j] = new Array(n);
            dp[i][j].fill(0);
        }
    }

    for(let i = 1; i < n; i++){
        for(let j = 0; j <= x; j++){
            for(let k = 0; k <= n; k++){
                dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j][k-1] + (s.charAt(i) === t.charAt(1) ? k-1 : 0));
                if(j !== 0){
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + (t.charAt(0) === t.charAt(1) ? k-1 : 0));
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + k-1);
                }
            }
        }
    }

    let max = 0;
    for(let i = 0; i < x; i++)
        for(let j = 0; j < n; j++)
            max = Math.max(max, dp[n-1][i][j]);

    console.log(max);
}


function main() {
  const is = new Scanner();
  const word = is.nextLine();
  let ones = 0, j = word.length;
  for (let i = 0; i < word.length; i += 1) {
    if (word[i] === '1') {
      ones += 1;
    }
    if (j === word.length) {
      if (word[i] === '2') {
        j = i;
      } else {
        if (word[i] === '0') {
          process.stdout.write('0');
        }
      }
    }
  }

  for (let i = 0; i < ones; i += 1) {
    process.stdout.write('1');
  }

  for (let i = j; i < word.length; i += 1) {
    if (word[i] === '0') {
      process.stdout.write('0');
    } else if (word[i] === '2') {
      process.stdout.write('2');
    }
  }
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const word = is.nextLine();
  let ones = 0, j = word.length;
  for (let i = 0; i < word.length; i += 1) {
    if (word[i] === '1') {
      ones += 1;
    }
    if (j === word.length && word[i] === '2') {
      j = i;
    }
  }

  for (let i = 0; i < j; i += 1) {
    if (word[i] === '0')
      process.stdout.write('0');
  }
  for (let i = 0; i < ones; i += 1) {
    process.stdout.write('1');
  }

  for (let i = j; i < word.length; i += 1) {
    if (word[i] !== '1') {
      process.stdout.write(String(word[i]));
    }
  }
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

var str = readline ();
var cnt = 0, i, answer = '';
for ( i = 0; i < str.length; i ++ ) {
    if ( str [ i ] == '1' ) cnt ++;
    else answer += str [ i ];
}
var pos = 0, other = '', actually = '';
while ( cnt -- ) other += '1';
while ( pos < answer.length && answer [ pos ] != '2' ) pos ++;
if ( pos == answer.length ) actually = (answer + other);
else {
    i = 0;
    while ( i < answer.length ) {
        if ( i == pos )
            actually += other;
        actually += answer [ i ];
        i ++;
    }
}
print ( actually );

function main() {
  const is = new Scanner();
  const word = is.nextLine().split('').map(Number);
  let ones = 0;
  word.forEach((item) => {
    if (item === 1)
      ones += 1;
  });
  let j = word.indexOf(2);
  j = j === -1 ? word.length : j;

  for (let i = 0; i < j; i += 1) {
    if (word[i] === 0)
      process.stdout.write('0');
  }
  for (let i = 0; i < ones; i += 1) {
    process.stdout.write('1');
  }

  for (let i = j; i < word.length; i += 1) {
    if (word[i] !== 1) {
      process.stdout.write(String(word[i]));
    }
  }
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const word = is.nextLine().split('').map(Number);
  let j = 0;
  for (let i = 1; i < word.length; i += 1) {
    if (word[i] === 1 && word[i - 1] === 2) {
      [word[i], word[i - 1]] = [word[i - 1], word[i]];
      [word[i - 1], word[j]] = [word[j], word[i - 1]];
    }
    if (word[j] === 1)
      j += 1;
  }

  const indexLimit = word.indexOf(2);
  const firstWord = word.slice(0, indexLimit);
  const secondWord = word.slice(indexLimit);
  let zeros = 0, ones = 0;
  firstWord.forEach((item) => {
    if (item === 0)
      zeros += 1;
    else
      ones += 1;
  });
  for (let i = 0; i < zeros; i += 1)
    process.stdout.write('0');
  for (let i = 0; i < ones; i += 1)
    process.stdout.write('1');
  console.log(secondWord.join(''));
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const word = is.nextLine();
  let ones = 0, j = word.length;
  for (let i = 0; i < word.length; i += 1) {
    if (word[i] === '1') {
      ones += 1;
    }
    if (j === word.length) {
      if (word[i] === '2') {
        j = i;
      } else {
        process.stdout.write('0');
      }
    }
  }

  for (let i = 0; i < ones; i += 1) {
    process.stdout.write('1');
  }

  for (let i = j; i < word.length; i += 1) {
    if (word[i] === '0') {
      process.stdout.write('0');
    } else if (word[i] === '2') {
      process.stdout.write('2');
    }
  }
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const word = is.nextLine().split('').map(Number);
  let ones = 0;
  word.forEach((item) => {
    if (item === 1)
      ones += 1;
  });
  const j = word.indexOf(2);

  for (let i = 0; i < j; i += 1) {
    if (word[i] === 0)
      process.stdout.write('0');
  }
  for (let i = 0; i < ones; i += 1) {
    process.stdout.write('1');
  }

  for (let i = j; i < word.length; i += 1) {
    if (word[i] !== 1) {
      process.stdout.write(String(word[i]));
    }
  }

}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });


(function () {
	function Queue (amount) {
		if(!(this instanceof Queue)) {
			return new Queue(amount);
		}
		amount = amount||1024;
		this.amount = amount;
		this.bg = 0;
		this.ed = 0;
		this.arr = [];
	}
	Queue.prototype = {
		constractor: Queue,
		isEmpty: function () {
			return (this.bg === this.ed);
		},
		doubleSize: function () {
			var target = [],
				o = this.arr,
				i = this.bg,
				j = this.ed,
				l = this.amount;
			target.push(o[i])
			i=(i+1)%l;
			for(;i!=j;i=(i+1)%l)
				target.push(o[i]);
			this.amount *= 2;
			this.bg = 0;
			this.ed = target.length;
			this.arr = target;
			//print(this.arr);
		},
		push: function (o) {
			this.arr[this.ed] = o;
			this.ed = (this.ed+1)%this.amount;
			if(this.isEmpty()) {
				this.doubleSize();
			}
		},
		pop: function () {
			var idx = this.bg;
			this.bg = (this.bg+1)%this.amount;
			return this.arr[idx];
		}
	}
	var rotater = (function () {
		var _door = [
			['*'],
			['^','>','v','<'],
			['-','|'],
			['L','U','R','D'],
			['+']
		];
		var _todoor = {},
			i,
			j,
			l;
		for(i=0;i<5;++i) {
			l = _door[i].length;
			for(j=0;j<l;++j) {
				_todoor[_door[i][j]] = {
					x: i,
					y: j,
					l: l
				};
			}
		}
		function rotateOne (c, t) {
			t = (t===undefined?1:t);
			var di = _todoor[c];
			return _door[di.x][(di.y+t)%di.l];
		}
		return {
			rotateOne: rotateOne
		}
	})();
	var steps = [
		[0,1],
		[1,0],
		[0,-1],
		[-1,0]
	];
	var rules = (function () {
		var right = ['+','-','>','L','U','D'];
		var down = ['+','|','v','L','R','U'];
		var left = ['+','-','<','D','R','U'];
		var up = ['+','|','^','D','R','L'];
		function lg (c, d) {
			for(var i=d.length-1;i>=0;--i) {
				if(d[i]===c)
					return true;
			}
			return false;
		}
		return [
			function (a,b) {
				return lg(a,right)&&lg(b,left);
			},
			function (a,b) {
				return lg(a,down)&&lg(b,up);
			},
			function (a,b) {
				return lg(a,left)&&lg(b,right);
			},
			function (a,b) {
				return lg(a,up)&&lg(b,down);
			}
		];
	})();
	function readlineInt () {
		return readline().split(' ').map(function (e) {
			return parseInt(e);
		});
	}
	var line = readlineInt();
	var n = line[0],
		m = line[1];
	var vec = [];
	for(var i=0;i<n;++i)
		vec.push(readline());
	var st = readlineInt();
	var ed = readlineInt();
	st = st.map(function (e) {
		return e-1;
	});
	ed = ed.map(function (e) {
		return e-1;
	});

	st.push(0);
	var qu = new Queue();
	var L = n*m*4;
	var used = [];
	for(var i=0; i<L;++i)
		used[i] = 0;
	qu.push({
		p: st,
		l: 0
	});
	used[(st[0]*m+st[1])*4+st[2]] = 1;

	var cur;
	var nxt;
	var ans = -1;
	var i,j,k,x,xx,ii,jj;
	while(!qu.isEmpty()) {
		cur = qu.pop();
		  // print("i:"+cur.p[0]);
		  // print("j:"+cur.p[1]);
		  // print("x:"+cur.p[2]);
		  // print("l:"+cur.l);
		if(cur.p[0] === ed[0] && cur.p[1] === ed[1]) {
			qu = [];
			ans = cur.l;
			break;
		}
		i = cur.p[0];
		j = cur.p[1];
		x = cur.p[2];
		for(k=0;k<4;++k){
			ii = i + steps[k][0];
			jj = j + steps[k][1];
			if(ii>=0&&ii<n&&jj>=0&&jj<m&&!used[(ii*m+jj)*4+x]) {
				if(rules[k](rotater.rotateOne(vec[i][j],x),rotater.rotateOne(vec[ii][jj],x))) {
					qu.push({
						p: [ii,jj,x],
						l: cur.l+1
					});
					used[(ii*m+jj)*4+x] = 1;
				}
			}
		}
		xx = (x+1)%4;
		if(!used[(i*m+j)*4+xx]) {
			qu.push({
				p: [i,j,xx],
				l: cur.l+1
			});
			used[(i*m+j)*4+xx] = 1;
		}
	}
	print(ans);
})();

(function () {
	function Queue (amount) {
		if(!(this instanceof Queue)) {
			return new Queue(amount);
		}
		amount = amount||1024;
		this.amount = amount;
		this.bg = 0;
		this.ed = 0;
		this.arr = [];
	}
	Queue.prototype = {
		constractor: Queue,
		isEmpty: function () {
			return (this.bg === this.ed);
		},
		doubleSize: function () {
			var target = [],
				o = this.arr,
				i = this.bg,
				j = this.ed,
				l = this.amount;
			target.push(o[i])
			i=(i+1)%l;
			for(;i!=j;i=(i+1)%l)
				target.push(o[i]);
			this.amount *= 2;
			this.bg = 0;
			this.ed = target.length;
			this.arr = target;
			//print(this.arr);
		},
		push: function (o) {
			this.arr[this.ed] = o;
			this.ed = (this.ed+1)%this.amount;
			if(this.isEmpty()) {
				this.doubleSize();
			}
		},
		pop: function () {
			var idx = this.bg;
			this.bg = (this.bg+1)%this.amount;
			return this.arr[idx];
		}
	}
	var rotater = (function () {
		var _door = [
			['*'],
			['^','>','v','<'],
			['-','|'],
			['L','U','R','D'],
			['+']
		];
		var _todoor = {},
			i,
			j,
			l;
		for(i=0;i<5;++i) {
			l = _door[i].length;
			for(j=0;j<l;++j) {
				_todoor[_door[i][j]] = {
					x: i,
					y: j,
					l: l
				};
			}
		}
		function rotateOne (c, t) {
			t = (t===undefined?1:t);
			var di = _todoor[c];
			return _door[di.x][(di.y+t)%di.l];
		}
		return {
			rotateOne: rotateOne
		}
	})();
	var steps = [
		[0,1],
		[1,0],
		[0,-1],
		[-1,0]
	];
	var rules = (function () {
		var right = ['+','-','>','L','U','D'];
		var down = ['+','|','v','L','R','U'];
		var left = ['+','-','<','D','R','U'];
		var up = ['+','|','^','D','R','L'];
		function lg (c, d) {
			for(var i=d.length-1;i>=0;--i) {
				if(d[i]===c)
					return true;
			}
			return false;
		}
		return [
			function (a,b) {
				return lg(a,right)&&lg(b,left);
			},
			function (a,b) {
				return lg(a,down)&&lg(b,up);
			},
			function (a,b) {
				return lg(a,left)&&lg(b,right);
			},
			function (a,b) {
				return lg(a,up)&&lg(b,down);
			}
		];
	})();
	function readlineInt () {
		return readline().split(' ').map(function (e) {
			return parseInt(e);
		});
	}
	var line = readlineInt();
	var n = line[0],
		m = line[1];
	var vec = [];
	for(var i=0;i<n;++i)
		vec.push(readline());
	var st = readlineInt();
	var ed = readlineInt();
	st = st.map(function (e) {
		return e-1;
	});
	ed = ed.map(function (e) {
		return e-1;
	});

	st.push(0);
	var qu = new Queue();
	var used = [];
	used.length = n*m*4;
	qu.push({
		p: st,
		l: 0
	});
	used[(st[0]*m+st[1])*4+st[2]] = true;

	var cur;
	var nxt;
	var ans = -1;
	var i,j,k,x,xx,ii,jj;
	while(!qu.isEmpty()) {
		cur = qu.pop();
		  // print("i:"+cur.p[0]);
		  // print("j:"+cur.p[1]);
		  // print("x:"+cur.p[2]);
		  // print("l:"+cur.l);
		if(cur.p[0] === ed[0] && cur.p[1] === ed[1]) {
			qu = [];
			ans = cur.l;
			break;
		}
		i = cur.p[0];
		j = cur.p[1];
		x = cur.p[2];
		for(k=0;k<4;++k){
			ii = i + steps[k][0];
			jj = j + steps[k][1];
			if(ii>=0&&ii<n&&jj>=0&&jj<m&&!used[(ii*m+jj)*4+x]) {
				if(rules[k](rotater.rotateOne(vec[i][j],x),rotater.rotateOne(vec[ii][jj],x))) {
					qu.push({
						p: [ii,jj,x],
						l: cur.l+1
					});
					used[(ii*m+jj)*4+x] = true;
				}
			}
		}
		xx = (x+1)%4;
		if(!used[(i*m+j)*4+xx]) {
			qu.push({
				p: [i,j,xx],
				l: cur.l+1
			});
			used[(i*m+j)*4+xx] = true;
		}
	}
	print(ans);
})();

(function () {
	function Queue (amount) {
		if(!(this instanceof Queue)) {
			return new Queue(amount);
		}
		amount = amount||1024;
		this.amount = amount;
		this.bg = 0;
		this.ed = 0;
		this.arr = [];
	}
	Queue.prototype = {
		constractor: Queue,
		isEmpty: function () {
			return (this.bg === this.ed);
		},
		doubleSize: function () {
			var target = [],
				o = this.arr,
				i = this.bg,
				j = this.ed,
				l = this.amount;
			target.push(o[i]);
			i=(i+1)%l;
			for(;i!=j;i=(i+1)%l)
				target.push(o[i]);
			this.amount *= 2;
			this.bg = 0;
			this.ed = target.length;
			this.arr = target;
			//print(this.arr);
		},
		push: function (o) {
			this.arr[this.ed] = o;
			this.ed = (this.ed+1)%this.amount;
			if(this.isEmpty()) {
				this.doubleSize();
			}
		},
		pop: function () {
			var idx = this.bg;
			this.bg = (this.bg+1)%this.amount;
			return this.arr[idx];
		}
	};
	var rotater = (function () {
		var _door = [
			['*'],
			['^','>','v','<'],
			['-','|'],
			['L','U','R','D'],
			['+']
		];
		var _todoor = {},
			i,
			j,
			l;
		for(i=0;i<5;++i) {
			l = _door[i].length;
			for(j=0;j<l;++j) {
				_todoor[_door[i][j]] = {
					x: i,
					y: j,
					l: l
				};
			}
		}
		function rotateOne (c, t) {
			t = (t===undefined?1:t);
			var di = _todoor[c];
			return _door[di.x][(di.y+t)%di.l];
		}
		return {
			rotateOne: rotateOne
		};
	})();
	var steps = [
		[0,1],
		[1,0],
		[0,-1],
		[-1,0]
	];
	var rules = (function () {
		var right = ['+','-','>','L','U','D'];
		var down = ['+','|','v','L','R','U'];
		var left = ['+','-','<','D','R','U'];
		var up = ['+','|','^','D','R','L'];
		function lg (c, d) {
			for(var i=d.length-1;i>=0;--i) {
				if(d[i]===c)
					return true;
			}
			return false;
		}
		return [
			function (a,b) {
				return lg(a,right)&&lg(b,left);
			},
			function (a,b) {
				return lg(a,down)&&lg(b,up);
			},
			function (a,b) {
				return lg(a,left)&&lg(b,right);
			},
			function (a,b) {
				return lg(a,up)&&lg(b,down);
			}
		];
	})();
	function readlineInt () {
		return readline().split(' ').map(function (e) {
			return parseInt(e);
		});
	}
	var line = readlineInt();
	var n = line[0],
		m = line[1];
	var vec = [];
	for(var i=0;i<n;++i)
		vec.push(readline());
	var st = readlineInt();
	var ed = readlineInt();
	st = st.map(function (e) {
		return e-1;
	});
	ed = ed.map(function (e) {
		return e-1;
	});

	st.push(0);
	var qu = new Queue();
	var L = n*m*4;
	var used = [];
	for( i=0; i<L;++i)
		used.push(false);
	qu.push({
		p: st,
		l: 0
	});
	used[(st[0]*m+st[1])*4+st[2]] = true;

	var cur;
	var nxt;
	var ans = -1;
	var j,k,x,xx,ii,jj;
	while(!qu.isEmpty()) {
		cur = qu.pop();
		  // print("i:"+cur.p[0]);
		  // print("j:"+cur.p[1]);
		  // print("x:"+cur.p[2]);
		  // print("l:"+cur.l);
		if(cur.p[0] === ed[0] && cur.p[1] === ed[1]) {
			qu = [];
			ans = cur.l;
			break;
		}
		i = cur.p[0];
		j = cur.p[1];
		x = cur.p[2];
		for(k=0;k<4;++k){
			ii = i + steps[k][0];
			jj = j + steps[k][1];
			if(ii>=0&&ii<n&&jj>=0&&jj<m&&!used[(ii*m+jj)*4+x]) {
				if(rules[k](rotater.rotateOne(vec[i][j],x),rotater.rotateOne(vec[ii][jj],x))) {
					qu.push({
						p: [ii,jj,x],
						l: cur.l+1
					});
					used[(ii*m+jj)*4+x] = true;
				}
			}
		}
		xx = (x+1)%4;
		if(!used[(i*m+j)*4+xx]) {
			qu.push({
				p: [i,j,xx],
				l: cur.l+1
			});
			used[(i*m+j)*4+xx] = true;
		}
	}
	print(ans);
})();

(function () {
	function Queue (amount) {
		if(!(this instanceof Queue)) {
			return new Queue(amount);
		}
		amount = amount||1024;
		this.amount = amount;
		this.bg = 0;
		this.ed = 0;
		this.arr = [];
	}
	Queue.prototype = {
		constractor: Queue,
		isEmpty: function () {
			return (this.bg === this.ed);
		},
		doubleSize: function () {
			var target = [],
				o = this.arr,
				i = this.bg,
				j = this.ed,
				l = this.amount;
			target.push(o[i])
			i=(i+1)%l;
			for(;i!=j;i=(i+1)%l)
				target.push(o[i]);
			this.amount *= 2;
			this.bg = 0;
			this.ed = target.length;
			this.arr = target;
			//print(this.arr);
		},
		push: function (o) {
			this.arr[this.ed] = o;
			this.ed = (this.ed+1)%this.amount;
			if(this.isEmpty()) {
				this.doubleSize();
			}
		},
		pop: function () {
			var idx = this.bg;
			this.bg = (this.bg+1)%this.amount;
			return this.arr[idx];
		}
	}
	var rotater = (function () {
		var _door = [
			['*'],
			['^','>','v','<'],
			['-','|'],
			['L','U','R','D'],
			['+']
		];
		var _todoor = {},
			i,
			j,
			l;
		for(i=0;i<5;++i) {
			l = _door[i].length;
			for(j=0;j<l;++j) {
				_todoor[_door[i][j]] = {
					x: i,
					y: j,
					l: l
				};
			}
		}
		function rotateOne (c, t) {
			t = (t===undefined?1:t);
			var di = _todoor[c];
			return _door[di.x][(di.y+t)%di.l];
		}
		return {
			rotateOne: rotateOne
		}
	})();
	var steps = [
		[0,1],
		[1,0],
		[0,-1],
		[-1,0]
	];
	var rules = (function () {
		var right = ['+','-','>','L','U','D'];
		var down = ['+','|','v','L','R','U'];
		var left = ['+','-','<','D','R','U'];
		var up = ['+','|','^','D','R','L'];
		function lg (c, d) {
			for(var i=d.length-1;i>=0;--i) {
				if(d[i]===c)
					return true;
			}
			return false;
		}
		return [
			function (a,b) {
				return lg(a,right)&&lg(b,left);
			},
			function (a,b) {
				return lg(a,down)&&lg(b,up);
			},
			function (a,b) {
				return lg(a,left)&&lg(b,right);
			},
			function (a,b) {
				return lg(a,up)&&lg(b,down);
			}
		];
	})();
	function readlineInt () {
		return readline().split(' ').map(function (e) {
			return parseInt(e);
		});
	}
	var line = readlineInt();
	var n = line[0],
		m = line[1];
	var vec = [];
	for(var i=0;i<n;++i)
		vec.push(readline());
	var st = readlineInt();
	var ed = readlineInt();
	st = st.map(function (e) {
		return e-1;
	});
	ed = ed.map(function (e) {
		return e-1;
	});

	st.push(0);
	var qu = new Queue();
	var L = n*m*4;
	var used = [];
	for(var i=0; i<L;++i)
		used[i] = false;
	qu.push({
		p: st,
		l: 0
	});
	used[(st[0]*m+st[1])*4+st[2]] = true;

	var cur;
	var nxt;
	var ans = -1;
	var j,k,x,xx,ii,jj;
	while(!qu.isEmpty()) {
		cur = qu.pop();
		  // print("i:"+cur.p[0]);
		  // print("j:"+cur.p[1]);
		  // print("x:"+cur.p[2]);
		  // print("l:"+cur.l);
		if(cur.p[0] === ed[0] && cur.p[1] === ed[1]) {
			qu = [];
			ans = cur.l;
			break;
		}
		i = cur.p[0];
		j = cur.p[1];
		x = cur.p[2];
		for(k=0;k<4;++k){
			ii = i + steps[k][0];
			jj = j + steps[k][1];
			if(ii>=0&&ii<n&&jj>=0&&jj<m&&!used[(ii*m+jj)*4+x]) {
				if(rules[k](rotater.rotateOne(vec[i][j],x),rotater.rotateOne(vec[ii][jj],x))) {
					qu.push({
						p: [ii,jj,x],
						l: cur.l+1
					});
					used[(ii*m+jj)*4+x] = true;
				}
			}
		}
		xx = (x+1)%4;
		if(!used[(i*m+j)*4+xx]) {
			qu.push({
				p: [i,j,xx],
				l: cur.l+1
			});
			used[(i*m+j)*4+xx] = true;
		}
	}
	print(ans);
})();

(function () {
	function Queue (amount) {
		if(!(this instanceof Queue)) {
			return new Queue(amount);
		}
		amount = amount||1024;
		this.amount = amount;
		this.bg = 0;
		this.ed = 0;
		this.arr = [];
	}
	Queue.prototype = {
		constractor: Queue,
		isEmpty: function () {
			return (this.bg === this.ed);
		},
		doubleSize: function () {
			var target = [],
				o = this.arr,
				i = this.bg,
				j = this.ed,
				l = this.amount;
			target.push(o[i])
			i=(i+1)%l;
			for(;i!=j;i=(i+1)%l)
				target.push(o[i]);
			this.amount *= 2;
			this.bg = 0;
			this.ed = target.length;
			this.arr = target;
			//print(this.arr);
		},
		push: function (o) {
			this.arr[this.ed] = o;
			this.ed = (this.ed+1)%this.amount;
			if(this.isEmpty()) {
				this.doubleSize();
			}
		},
		pop: function () {
			var idx = this.bg;
			this.bg = (this.bg+1)%this.amount;
			return this.arr[idx];
		}
	}
	var rotater = (function () {
		var _door = [
			['*'],
			['^','>','v','<'],
			['-','|'],
			['L','U','R','D'],
			['+']
		];
		var _todoor = {},
			i,
			j,
			l;
		for(i=0;i<5;++i) {
			l = _door[i].length;
			for(j=0;j<l;++j) {
				_todoor[_door[i][j]] = {
					x: i,
					y: j,
					l: l
				};
			}
		}
		function rotateOne (c, t) {
			t = (t===undefined?1:t);
			var di = _todoor[c];
			return _door[di.x][(di.y+t)%di.l];
		}
		return {
			rotateOne: rotateOne
		}
	})();
	var steps = [
		[0,1],
		[1,0],
		[0,-1],
		[-1,0]
	];
	var rules = (function () {
		var right = ['+','-','>','L','U','D'];
		var down = ['+','|','v','L','R','U'];
		var left = ['+','-','<','D','R','U'];
		var up = ['+','|','^','D','R','L'];
		function lg (c, d) {
			for(var i=d.length-1;i>=0;--i) {
				if(d[i]===c)
					return true;
			}
			return false;
		}
		return [
			function (a,b) {
				return lg(a,right)&&lg(b,left);
			},
			function (a,b) {
				return lg(a,down)&&lg(b,up);
			},
			function (a,b) {
				return lg(a,left)&&lg(b,right);
			},
			function (a,b) {
				return lg(a,up)&&lg(b,down);
			}
		];
	})();
	function readlineInt () {
		return readline().split(' ').map(function (e) {
			return parseInt(e);
		});
	}
	var line = readlineInt();
	var n = line[0],
		m = line[1];
	var vec = [];
	for(var i=0;i<n;++i)
		vec.push(readline());
	var st = readlineInt();
	var ed = readlineInt();
	st = st.map(function (e) {
		return e-1;
	});
	ed = ed.map(function (e) {
		return e-1;
	});

	st.push(0);
	var qu = new Queue();
	var used = new Array(n*m*4);
	//used.length = ;
	qu.push({
		p: st,
		l: 0
	});
	used[(st[0]*m+st[1])*4+st[2]] = true;

	var cur;
	var nxt;
	var ans = -1;
	var i,j,k,x,xx,ii,jj;
	while(!qu.isEmpty()) {
		cur = qu.pop();
		  // print("i:"+cur.p[0]);
		  // print("j:"+cur.p[1]);
		  // print("x:"+cur.p[2]);
		  // print("l:"+cur.l);
		if(cur.p[0] === ed[0] && cur.p[1] === ed[1]) {
			qu = [];
			ans = cur.l;
			break;
		}
		i = cur.p[0];
		j = cur.p[1];
		x = cur.p[2];
		for(k=0;k<4;++k){
			ii = i + steps[k][0];
			jj = j + steps[k][1];
			if(ii>=0&&ii<n&&jj>=0&&jj<m&&!used[(ii*m+jj)*4+x]) {
				if(rules[k](rotater.rotateOne(vec[i][j],x),rotater.rotateOne(vec[ii][jj],x))) {
					qu.push({
						p: [ii,jj,x],
						l: cur.l+1
					});
					used[(ii*m+jj)*4+x] = true;
				}
			}
		}
		xx = (x+1)%4;
		if(!used[(i*m+j)*4+xx]) {
			qu.push({
				p: [i,j,xx],
				l: cur.l+1
			});
			used[(i*m+j)*4+xx] = true;
		}
	}
	print(ans);
})();

(function () {
	function Queue (amount) {
		if(!(this instanceof Queue)) {
			return new Queue(amount);
		}
		amount = amount||2048;
		this.amount = amount;
		this.bg = 0;
		this.ed = 0;
		this.arr = [];
	}
	Queue.prototype = {
		constractor: Queue,
		isEmpty: function () {
			return (this.bg === this.ed);
		},
		doubleSize: function () {
			var target = [],
				o = this.arr,
				i = this.bg,
				j = this.ed,
				l = this.amount;
			target.push(o[i])
			i=(i+1)%l;
			for(;i!=j;i=(i+1)%l)
				target.push(o[i]);
			this.amount *= 2;
			this.bg = 0;
			this.ed = target.length;
			this.arr = target;
			//print(this.arr);
		},
		push: function (o) {
			this.arr[this.ed] = o;
			this.ed = (this.ed+1)%this.amount;
			if(this.isEmpty()) {
				this.doubleSize();
			}
		},
		pop: function () {
			var idx = this.bg;
			this.bg = (this.bg+1)%this.amount;
			return this.arr[idx];
		}
	}
	var rotater = (function () {
		var _door = [
			['*'],
			['^','>','v','<'],
			['-','|'],
			['L','U','R','D'],
			['+']
		];
		var _todoor = {},
			i,
			j,
			l;
		for(i=0;i<5;++i) {
			l = _door[i].length;
			for(j=0;j<l;++j) {
				_todoor[_door[i][j]] = {
					x: i,
					y: j,
					l: l
				};
			}
		}
		function rotateOne (c, t) {
			t = (t===undefined?1:t);
			var di = _todoor[c];
			return _door[di.x][(di.y+t)%di.l];
		}
		return {
			rotateOne: rotateOne
		}
	})();
	var steps = [
		[0,1],
		[1,0],
		[0,-1],
		[-1,0]
	];
	var rules = (function () {
		var right = ['+','-','>','L','U','D'];
		var down = ['+','|','v','L','R','U'];
		var left = ['+','-','<','D','R','U'];
		var up = ['+','|','^','D','R','L'];
		function lg (c, d) {
			for(var i=d.length-1;i>=0;--i) {
				if(d[i]===c)
					return true;
			}
			return false;
		}
		return [
			function (a,b) {
				return lg(a,right)&&lg(b,left);
			},
			function (a,b) {
				return lg(a,down)&&lg(b,up);
			},
			function (a,b) {
				return lg(a,left)&&lg(b,right);
			},
			function (a,b) {
				return lg(a,up)&&lg(b,down);
			}
		];
	})();
	function readlineInt () {
		return readline().split(' ').map(function (e) {
			return parseInt(e);
		});
	}
	var line = readlineInt();
	var n = line[0],
		m = line[1];
	var vec = [];
	for(var i=0;i<n;++i)
		vec.push(readline());
	var st = readlineInt();
	var ed = readlineInt();
	st = st.map(function (e) {
		return e-1;
	});
	ed = ed.map(function (e) {
		return e-1;
	});

	st.push(0);
	var qu = new Queue();
	var used = [];
	used.length = n*m*4;
	qu.push({
		p: st,
		l: 0
	});
	used[(st[0]*m+st[1])*4+st[2]] = true;

	var cur;
	var nxt;
	var ans = -1;
	var i,j,k,x,xx,ii,jj;
	while(!qu.isEmpty()) {
		cur = qu.pop();
		  // print("i:"+cur.p[0]);
		  // print("j:"+cur.p[1]);
		  // print("x:"+cur.p[2]);
		  // print("l:"+cur.l);
		if(cur.p[0] === ed[0] && cur.p[1] === ed[1]) {
			qu = [];
			ans = cur.l;
			break;
		}
		i = cur.p[0];
		j = cur.p[1];
		x = cur.p[2];
		for(k=0;k<4;++k){
			ii = i + steps[k][0];
			jj = j + steps[k][1];
			if(ii>=0&&ii<n&&jj>=0&&jj<m&&!used[(ii*m+jj)*4+x]) {
				if(rules[k](rotater.rotateOne(vec[i][j],x),rotater.rotateOne(vec[ii][jj],x))) {
					qu.push({
						p: [ii,jj,x],
						l: cur.l+1
					});
					used[(ii*m+jj)*4+x] = true;
				}
			}
		}
		xx = (x+1)%4;
		if(!used[(i*m+j)*4+xx]) {
			qu.push({
				p: [i,j,xx],
				l: cur.l+1
			});
			used[(i*m+j)*4+xx] = true;
		}
	}
	print(ans);
})();