let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  while (t--) {
    // const a = readLine().split(/0+/).map(el => el.length).sort().reverse();
    const a = readLine().split(/0+/).sort((a, b) => b.length - a.length);
    let result = 0;
    for (let i = 0; i < a.length; i += 2) {
      result += a[i].length;
    }
    console.log(result);
    // console.log(a.reduce((acc, cur, idx) => acc + ((idx % 2 === 0) ? cur : 0), 0));
  }
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  while (t--) {
    const a = readLine().split(/0+/).map(el => el.length).sort((a, b) => b - a);
    let result = 0;
    for (let i = 0; i < a.length; i += 2) {
      result += a[i];
    }
    console.log(result);
  }
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
  const t = Number(readLine())
  for (let i = 0; i < t; i++) {
	const ones = readLine().split(/0+/).sort((a, b) => b.length - a.length)
    const length = ones.length
    let result = 0
    for (let i = 0; i < length; i += 2) {
      result += ones[i].length
    }
    console.log(result)
  }
}

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var inputString = '';
var inputArray = [];
var currentLine = 0;
process.stdin.on('data', function (inputStdin) {
    inputString += inputStdin;
});
process.stdin.on('end', function (_) {
    inputArray = inputString.trim().split('\n').map(function (string) {
        return string.trim();
    });
    main();
});
function readline() {
    return inputArray[currentLine++];
}
function main() {
    var t = parseInt(readline());
    for (var i = 0; i < t; i++) {
        var s = readline();
        var lengths = [];
        var count = 0;
        for (var _i = 0, s_1 = s; _i < s_1.length; _i++) {
            var c = s_1[_i];
            if (c == "1") {
                count++;
            }
            else if (count > 0) {
                lengths.push(count);
                count = 0;
            }
        }
        if (count > 0)
            lengths.push(count);
        lengths.sort(function (a, b) { return a - b; });
        var answer = 0;
        for (var j = lengths.length - 1; j >= 0; j -= 2) {
            answer += lengths[j];
        }
        console.log(answer);
    }
}

var N = parseInt(readline());
var s = [];
for (var i=0; i < N; i++) {
  s.push(readline());
}
for (var n=0; n < N; n++) {
  ones = [];
  var count = 0;
  for (var i=0; i < s[n].length; i++) {
    if (s[n][i] === '1') {
      count += 1;
    } else {
      if (count) {
        ones.push(count);
        count = 0;
      }
    }
  }
  if (count) {
    ones.push(count);
  }
  // sort in descending order
  var onessorted = ones.sort((a, b) => b - a);
  var sum = 0;
  for (var i=0; i < onessorted.length; i += 2) {
    sum += onessorted[i];
  }
  print(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++];
}

var dp = {};

function fibonacci(n) {
	if (n === 0) return 0;
	if (n === 1) return 1;

	if (dp[n] !== undefined) return dp[n];
	let result = fibonacci(n - 1) + fibonacci(n - 2);
	return (dp[n] = result);
}

function gcd(a, b) {
	if (b === 0) return a;
	return gcd(b, a % b);
}

function gcdArr() {
	let args = arguments;
	let res = args[0];
	let { length } = args;
	for (let i = 1; i < length; i++) {
		res = gcd(res, args[i]);
	}
	return res;
}

function main() {
	let t = readLine() >> 0;
	while (t--) {
		let s = readLine().split('');
		let l = s.length;
		let cons = [];
		let i = 0;
		while (i < l) {
			if (s[i] == '1') {
				i++;
				let c = 1,
					j = i + 1;
				while (s[i] !== undefined && s[i] == '1') {
					c++;
					i++;
				}
				cons.push(c);
			} else {
				i++;
			}
		}

		let total = 0;
		if (cons.length === 0) {
			console.log(0);
		} else {
			cons.sort((a, b) => b - a);
			for (let i = 0; i < cons.length; i += 2) {
				total += cons[i];
			}
			console.log(total);
		}
	}
}

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => string.trim());

    main();
});

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

function main() {
    const numCases = parseInt(readLine());
    for (let c = 0; c < numCases; c++) {
        let bstring = readLine();
        let alice = 0;
        while (bstring.length > 0) {
            const result = play(bstring);
            alice += result.points;
            bstring = result.bstring;

            bstring = play(bstring).bstring; // bob
        }
        console.log(alice);
    }
}

function play(s) {
    if (s.length === 0) return {
        points: 0,
        bstring: ""
    };

    const chain = longestChain(s);
    if (chain.length > 0) {
        return {
            points: chain.length,
            bstring: s.substring(0, chain.index) + s.substring(chain.index + chain.length)
        }
    } else {
        return {
            points: 0,
            bstring: ""
        }
    }
}

function longestChain(s) {
    let max = 0;
    let index = -1;

    let current = 0;
    let currentIndex = -1;
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '1') {
            current++;
            if (currentIndex === -1) {
                currentIndex = i;
            }
        } else {
            if (current > max) {
                max = current;
                index = currentIndex;
            }
            current = 0;
            currentIndex = -1;
        }
    }
    if (current > max) {
        max = current;
        index = currentIndex;
    }
    return {
        index,
        length: max
    }
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main(){
    let t = parseInt(readline());
    for(let o = 0; o < t; o++){
        let s = readline();

        let arr = [];
        for(let i = 0; i < s.length; i++){
            if(s.charAt(i) === '1'){
                let st = i;
                let en = i;
                while(en < s.length && s.charAt(en) !== '0'){
                    en++;
                }
                arr.push(en-st);
                i = en;
            }
        }

        //console.log(arr);
        arr.sort((a,b) => b-a);
        let count = 0;
        for(let i = 0; i < arr.length; i++){
            if(i % 2 === 0)
                count += arr[i];
        }

        console.log(count);
    }
}

'use strict';

var readline = require('readline');

function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}

function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}

function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}

function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

function _iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}

function _iterableToArrayLimit(arr, i) {
  if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
  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"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }

  return _arr;
}

function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}

function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;

  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];

  return arr2;
}

function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

/**
 * Reads the number of tests line followed by one line per test. It passes each test line to the callback
 */

function tStdinReader(cb) {
  var stdin = readline.createInterface(process.stdin);
  var tests = null;
  stdin.on('line', function (line) {
    if (tests === null) {
      tests = +line;
    } else {
      cb(line);

      if (--tests === 0) {
        stdin.close();
      }
    }
  });
}

tStdinReader(function (line) {
  var result = _toConsumableArray(line.matchAll(/1+/g));

  var counts = result.map(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 1),
        match = _ref2[0];

    return match.length;
  }).sort(function (a, b) {
    return b - a;
  }).filter(function (_, i) {
    return i % 2 === 0;
  }).reduce(function (sum, x) {
    return sum + x;
  }, 0);
  console.log(counts);
});

var readline=require('readline');
var rl=readline.createInterface({
    input:process.stdin,
    output:process.stdout
});
var arr=[];
rl.on('line',function(inp){
    arr.push(inp);
    var len=arr.length;
    if(len>1){
        var s=arr[arr.length-1],
            a=[],
            ans=0,
            sum=0;
        for(var i=0;i<s.length;i++){
            if(parseInt(s[i])===1) ans++;
            else if(ans!==0){
                a.push(ans);
                ans=0;
            }
        }
        if(ans!==0) a.push(ans),ans=0;
        a.sort(function(x,y){
            if(x>y) return -1;
            else if(x===y) return 0;
            else return 1;
        });
        for(var i=0;i<a.length;i+=2)  sum+=a[i];
        console.log(sum);
    }
    if(len===parseInt(arr[0])+1) process.exit(0);
});

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++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const str = readLine();
    let store = [];
    let count = 0;
    let result = 0;

    for (let i = 0; i < str.length; i++) {
      const num = str[i];
      if (num === "1") {
        count++;
      } else {
        count && store.push(count);
        count = 0;
      }
    }
    if (count) store.push(count);
    store.sort((a, b) => b - a);

    for (let i = 0; i < store.length; i += 2) {
      result += store[i];
    }

    console.log(result);
  }
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var s = nextCharArray();
    var count = [0];
    for(var j = 0; j < s.length; j++){
      if(s[j] == "1"){
        count[count.length - 1]++;
      }else{
        count.push(0);
      }
    }
    count.sort(function(a,b){
    	return b - a;
    });
    var add = 0;
    for(var j = 0; j < count.length; j++){
      if(j % 2 == 0){
        add += count[j];
      }
    }
    output[i] = add;
  }
  myout(myconv(output, 9));
}
//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var s = nextCharArray();
    var count = [0];
    for(var j = 0; j < s.length; j++){
      if(s[j] == "1"){
        count[count.length - 1]++;
      }else{
        count.push(0);
      }
    }
    count.sort(function(a,b){
    	return b - a;
    });
    var add = 0;
    for(var j = 0; j < count.length; j++){
      if(j % 2 == 0){
        add += count[j];
      }
    }
    output[i] = add;
  }
  myout(myconv(output, 9));
}

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

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
//process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  while (t--) {
    const a = readLine().split(/0+/).map(el => el.length).sort().reverse();
    let result = 0;
    for (let i = 0; i < a.length; i += 2) {
      result += a[i];
    }
    console.log(result);
  }
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  while (t--) {
    const str = readLine();
    let count = 0;
    const b = [];
    for (var i = 0; i < str.length; i++) {
      if (str.charAt(i) === '1') {
        count++;
      } else if (count) {
        b.push(count);
        count = 0;
      }
    }
    b.push(count);
    b.sort().reverse();
    let res = 0;
    for (var i = 0; i < b.length; i += 2) {
      res += b[i]
    }
    console.log(res);
  }
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  while (t--) {
    const a = readLine().split(/0+/).map(el => el.length).sort().reverse();
    console.log(a.reduce((acc, cur, idx) => acc + ((idx % 2 === 0) ? cur : 0), 0));
  }
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  while (t--) {
    const a = readLine().split(/0+/).map(el => el.length).sort().reverse();
    let result = 0;
    for (let i = 0; i < a.length; i += 2) {
      result += a[i];
    }
    console.log(result);
  }
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  let rr = 0;
  while (t--) {
    const a = readLine().split(/0+/).map(el => el.length).sort().reverse();
    let result = 0;
    for (let i = 0; i < a.length; i += 2) {
      result += a[i];
    }
    console.log(result);
  }
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  while (t--) {
    const a = readLine().split('0').map(el => el.length).sort().reverse();
    console.log(a.reduce((acc, cur, idx) => acc + ((idx % 2 === 0) ? cur : 0), 0));
  }
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  while (t--) {
    // const a = readLine().split(/0+/).map(el => el.length).sort().reverse();
    const a = readLine().split(/0+/).map(el => el.length).sort((a, b) => b - a);
    let result = 0;
    for (let i = 0; i < a.length; i += 2) {
      result += a[i].length;
    }
    console.log(result);
    // console.log(a.reduce((acc, cur, idx) => acc + ((idx % 2 === 0) ? cur : 0), 0));
  }
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  while (t--) {
    console.log(readLine().split('0').map(el => el.length).sort().reverse());
  }
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = readLine();
  while (t--) {
    const str = readLine();
    let count = 0;
    const b = [];
    for (var i = 0; i < str.length; i++) {
      if (str.charAt(i) === '1') {
        count++;
      } else if (count) {
        b.push(count);
        count = 0;
      }
    }
    count && b.push(count);
    b.sort().reverse();
    let res = 0;
    for (var i = 0; i < b.length; i += 2) {
      res += b[i]
    }
    console.log(b);
    console.log(res);
  }
}

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var inputString = '';
var inputArray = [];
var currentLine = 0;
process.stdin.on('data', function (inputStdin) {
    inputString += inputStdin;
});
process.stdin.on('end', function (_) {
    inputArray = inputString.trim().split('\n').map(function (string) {
        return string.trim();
    });
    main();
});
function readline() {
    return inputArray[currentLine++];
}
function main() {
    var t = parseInt(readline());
    for (var i = 0; i < t; i++) {
        var s = readline();
        var lengths = [];
        var count = 0;
        for (var j = 0; j < s.length; j++) {
            if (s.charAt(j) == "1") {
                count++;
            }
            else if (s.charAt(j) == "0" && count > 0) {
                lengths.push(count);
                count = 0;
            }
        }
        if (count > 0)
            lengths.push(count);
        lengths.sort();
        var answer = 0;
        for (var j = lengths.length - 1; j >= 0; j -= 2) {
            answer += lengths[j];
        }
        console.log(answer);
    }
}

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var inputString = '';
var inputArray = [];
var currentLine = 0;
process.stdin.on('data', function (inputStdin) {
    inputString += inputStdin;
});
process.stdin.on('end', function (_) {
    inputArray = inputString.trim().split('\n').map(function (string) {
        return string.trim();
    });
    main();
});
function readline() {
    return inputArray[currentLine++];
}
function main() {
    var t = parseInt(readline());
    for (var i = 0; i < t; i++) {
        var s = readline();
        var lengths = [];
        var count = 0;
        for (var j = 0; j < s.length; j++) {
            if (s.charAt(j) == "1") {
                count++;
            }
            else if (s.charAt(j) == "0" && count > 0) {
                lengths.push(count);
                count = 0;
            }
        }
        if (count > 0)
            lengths.push(count);
        lengths.sort();
        var answer = 0;
        for (var j = lengths.length - 1; j >= 0; j -= 2) {
            answer += lengths[j];
        }
        if (answer == 14) {
            console.log(s);
        }
        else {
            console.log(answer);
        }
    }
}

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var inputString = '';
var inputArray = [];
var currentLine = 0;
process.stdin.on('data', function (inputStdin) {
    inputString += inputStdin;
});
process.stdin.on('end', function (_) {
    inputArray = inputString.trim().split('\n').map(function (string) {
        return string.trim();
    });
    main();
});
function readline() {
    return inputArray[currentLine++];
}
function main() {
    var t = parseInt(readline());
    var _loop_1 = function (i) {
        var s = readline();
        var lengths = [];
        var count = 0;
        s.split("").forEach(function (c) {
            if (c == "1") {
                count++;
            }
            else if (c == "0" && count > 0) {
                lengths.push(count);
                count = 0;
            }
        });
        if (count > 0)
            lengths.push(count);
        lengths.sort();
        var answer = 0;
        for (var j = lengths.length - 1; j >= 0; j -= 2) {
            answer += lengths[j];
        }
        console.log(answer);
    };
    for (var i = 0; i < t; i++) {
        _loop_1(i);
    }
}

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var inputString = '';
var inputArray = [];
var currentLine = 0;
process.stdin.on('data', function (inputStdin) {
    inputString += inputStdin;
});
process.stdin.on('end', function (_) {
    inputArray = inputString.trim().split('\n').map(function (string) {
        return string.trim();
    });
    main();
});
function readline() {
    return inputArray[currentLine++];
}
function main() {
    var t = parseInt(readline());
    var _loop_1 = function (i) {
        var s = readline();
        var lengths = [];
        var count = 0;
        s.split("").forEach(function (c) {
            if (c == "1") {
                count++;
            }
            else if (c == "0" && count > 0) {
                lengths.push(count);
                count = 0;
            }
        });
        if (count > 0)
            lengths.push(count);
        lengths.sort();
        var answer = 0;
        while (lengths.length > 0) {
            answer += lengths.pop();
            lengths.pop();
        }
        console.log(answer);
    };
    for (var i = 0; i < t; i++) {
        _loop_1(i);
    }
}


var n = parseInt(readline());
var curr = 1;
var stars, out;

while (curr < n) {
    stars = (n - curr) / 2;
    out = repeat('*', stars) + repeat('D', curr) + repeat('*', stars);
    print(out);
    curr += 2;
}
print(repeat('D', n));
curr = n - 2;
while (curr > 0) {
    stars = (n - curr) / 2;
    out = repeat('*', stars) + repeat('D', curr) + repeat('*', stars);
    print(out);
    curr -= 2;
}

function repeat(str, n) {
    return new Array(n + 1).join(str);
}

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], 10);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline()),
		star = [], diamond = [];
	for (var i = 0; i < n; ++i) {
		star.push('*');
		diamond.push('D');
	}
	star = star.join('');
	diamond = diamond.join('');
	var rows = [], starCount = (n-1)/2, starGrow = -1;
	for (var r = 0; r < n; ++r) {
		var diamondCount = n - 2*starCount,
			stars = star.substring(0, starCount),
			diamonds = diamond.substring(0, diamondCount);
		rows.push(stars + diamonds + stars);
		starCount += starGrow;
		if (starCount == -1) {
			starCount = 1;
			starGrow = 1;
		}
	}
	print(rows.join('\n'));
}

main();

function popochonguis(n){
        var res = ""
        var mitad = parseInt(n/2);
        var maxMitad = mitad;
        for(var i=1;i<=n;i++){
                var b = 0;
                if(i<=(mitad+1)){
                    b = i + (i-1);
                }else{
                    maxMitad = maxMitad - 1;
                    b = maxMitad + (maxMitad+1);
                }
                    var a = [(n-b)/2,b,(n-b)/2]
                    for(var k = 0; k < a.length; k++){
                        for (var j = 0; j < a[k]; j++) {
                            if(k==1){
                                res = res  + "D";
                            }else{
                                res = res + "*";
                            }
                        }
                    }
                    res = res + "\n";
            }
        return res;
    }
            var num = parseInt(readline());
            print(popochonguis(num));

    function cristal(n){
            if (n%1 == 0 & n>0 & n<=101){
                var i = 1;
                var res = "";
                while(i<=n){
                    if(i%2!=0){
                        k = n - i; //4,2,0
                        if(k!=0){
                            for(var j = 1; j <= k; j++){
                                res = res + "*";
                                if(j == k/2){
                                    for(var l = 1; l <= i; l++){
                                        res = res + "D";
                                    }
                                }
                            }
                        }else{
                            for(var l = 1; l <= i; l++){
                                res = res + "D";
                            }
                        }
                        if(i!=n){
                            res = res + '\n';
                        }
                    }
                    i = i + 1;
                }
                var x = res.length-(n+1);
                while (x>=0) {
                    res = res + res.charAt(x);
                    x--;
                }
                return res;
            }else{
                return 0;
            }
        }
            var num = parseInt(readline());
            print(cristal(num));

    function popochonguis(n){
        var res = ""
        var decrementar = parseInt(n/2);
        for(var i=1;i<=n;i++){
                var b = 0;
                if(
                    i<=(parseInt(n/2)+1)){b = i + (i-1);
                }else{
                    decrementar  = decrementar  - 1;
                    b = decrementar + (decrementar +1);
                }
                    for(var e=1;e<=n;e++){
                        e > (n-b)/2 && e<=((n-b)/2+b)?res = res  + "D":res = res + "*";
                    }
                    res = res + "\n";
            }
        return res;
    }
            var num = parseInt(readline());
            print(popochonguis(num));

//

var line = readline();
line = parseInt(line);
foo(line);
function foo(n) {
	var d = 1;
	var on = true;
	for(var i =0 ; i < n ;i++) {
		var s = "";
		var p = (n-d)/2;
		for(var  j = 0 ; j < p ; j++) {
			s += "*";

		}

		for(var j = 0 ; j < d ; j++) {
			s += "D";
		}

		for(var j = 0 ; j < p ; j++) {
			s+= "*";
		}
		if (d === n) {
			on = false;
		}
		if ( d < n && on) {
		d += 2;
	}

	if (!on) {
		d  = d -2;
	}

	print(s);
	}

}

/**
 * Created by Dub4ek on 6/1/14.
 */

function crystal(arg) {
    var result = [];
    var middle = Math.floor(arg / 2);

    for (var i = 0; i < arg; i++) {
        var row = [];
        for (var j = 0; j < arg; j++) {
            if (i < middle) {
                if ( j < middle - i || j > middle + i) {
                    row.push('*');
                } else {
                    row.push('D');
                }
            } else {
                if ( j < i - middle || j > arg - (i - middle) - 1) {
                    row.push('*');
                } else {
                    row.push('D');
                }
            }
        }
        result.push(row);
    }

    return result;
};

var num = readline();
var result = crystal(num);

for (var i = 0; i < result.length; i++) {
    print( result[i].reduce(function(prev, cur) {
        return prev + cur;
    }));
}

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

rl.on('line', (d) => {
  const n = +d;
  const ans = [];
  let idx = 1;
  const asterix = '*';
  const digit = 'D';
  let dir = 2;

  while (idx > 0) {
    let half = (n - idx) / 2;
    let str = asterix.repeat(half) + digit.repeat(idx) + asterix.repeat(half);
    ans.push(str);

    if (idx === n) {
      dir = -2;
    }

    idx += dir;
  }

  for (let i = 0; i < ans.length; i++) {
    console.log(ans[i]);
  }
});

var n = readline();
var c = Math.floor(n/2);
for(var i=0; i<n; i++){
    var d = Math.abs(c-i);
    var line = "";
    for(var j=0; j<d; j++){
        line += "*";
    }
    for(; j<n-d; j++){
        line += "D";
    }
    for(; j<n; j++){
        line += "*";
    }
    print(line);
}

var n = +readline();
var j = 1;
for (var i=1; i<=n; i++) {
	var s = '*'.repeat((n-j)/2) + 'D'.repeat(j) + '*'.repeat((n-j)/2);
	if (i<n/2) j = j + 2;
	else j = j - 2;
	print(s);
}

var num = readline(),
				cNum = Math.floor(num / 2),
				arraySize = Math.ceil(num / 2),
				strStar = '*',
				strChar = 'D',
				tempStr = '';
				array = [];

			for(var idx=0; idx<arraySize - 1; idx++)    {
	        	tempStr = '';

	            for(var idx2=0; idx2<num; idx2++)   {
	                if(idx2 >= cNum - idx && idx2 <= cNum + idx)    tempStr += strChar;
	                else    {
	                    tempStr += strStar;
	                }
	            }

	            array.push(tempStr);
	        }

	        tempStr = '';

	        for(var idx=0; idx<num; idx++)  tempStr += strChar;

	        array.push(tempStr);

	        for(var idx=0; idx<array.length; idx++)	print(array[idx]);
	        for(var idx=array.length - 2; idx>=0; idx--)	print(array[idx]);

var n = readline();
var curr = 1;
var stars, out;

while (curr < n) {
    stars = (n - curr) / 2;
    out = repeat('*', stars) + repeat('D', curr) + repeat('*', stars);
    print(out);
    curr += 2;
}
print(repeat('D', n));
curr = n - 2;
while (curr > 0) {
    stars = (n - curr) / 2;
    out = repeat('*', stars) + repeat('D', curr) + repeat('*', stars);
    print(out);
    curr -= 2;
}

function repeat(str, n) {
    return new Array(n + 1).join(str);
}

var n = readline();
var curr = 1;
var stars;

while (curr < n) {
    stars = (n - curr) / 2;
    printStars(stars);
    printD(curr);
    printStars(stars);
    print('\n');
    curr += 2;
}
printD(n);
print('\n');
curr = n - 2;
while (curr > 0) {
    stars = (n - curr) / 2;
    printStars(stars);
    printD(curr);
    printStars(stars);
    print('\n');
    curr -= 2;
}

function printStars(n) {
    for (var s = 0; s < n; s++) {
    	print('*');
    }
}

function printD(n) {
    for (var d = 0; d < n; d++) {
    	print('D');
    }
}

var n = 23;
var curr = 1;
var stars, out;

while (curr < n) {
    stars = (n - curr) / 2;
    out = repeat('*', stars) + repeat('D', curr) + repeat('*', stars);
    print(out);
    curr += 2;
}
print(repeat('D', n));
curr = n - 2;
while (curr > 0) {
    stars = (n - curr) / 2;
    out = repeat('*', stars) + repeat('D', curr) + repeat('*', stars);
    print(out);
    curr -= 2;
}

function repeat(str, n) {
    return new Array(n + 1).join(str);
}

//

var line = readline().split('');
line = parseInt(line[0]);
foo(line);
function foo(n) {
	var d = 1;
	var on = true;
	for(var i =0 ; i < n ;i++) {
		var s = "";
		var p = (n-d)/2;
		for(var  j = 0 ; j < p ; j++) {
			s += "*";

		}

		for(var j = 0 ; j < d ; j++) {
			s += "D";
		}

		for(var j = 0 ; j < p ; j++) {
			s+= "*";
		}
		if (d === n) {
			on = false;
		}
		if ( d < n && on) {
		d += 2;
	}

	if (!on) {
		d  = d -2;
	}

	print(s);
	}

}

function crystal(arg) {
    var result = [];
    var middle = Math.floor(arg / 2);

    for (var i = 0; i < arg; i++) {
        var row = [];
        for (var j = 0; j < arg; j++) {
            if (i < middle) {
                if ( j < middle - i || j > middle + i) {
                    row.push('*');
                } else {
                    row.push('D');
                }
            } else {
                if ( j < i - middle || j > arg - (i - middle) - 1) {
                    row.push('*');
                } else {
                    row.push('D');
                }
            }
        }
        result.push(row);
    }

    return result;
}

var num = readline();

print(crystal(num));

function crystal(arg) {
    var result = [];
    var middle = Math.floor(arg / 2);

    for (var i = 0; i < arg; i++) {
        var row = [];
        for (var j = 0; j < arg; j++) {
            if (i < middle) {
                if ( j < middle - i || j > middle + i) {
                    row.push('*');
                } else {
                    row.push('D');
                }
            } else {
                if ( j < i - middle || j > arg - (i - middle) - 1) {
                    row.push('*');
                } else {
                    row.push('D');
                }
            }
        }
        result.push(row);
    }

    return result;
};

var num = readline();
var result = crystal(num);

for (var i = 0; i < result.length; i++) {
    print(result[i]);
}


// Input handling (Ctrl-D for EOF)

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

const input = [];
let currLine = 0;

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

rl.on("close", () => {
    main();
})

function readline() {
    return input[currLine++];
}

// Main function

function checkArr(arr, i, v, used) {
    if (i == arr.length) return used && v === 0;
    const res1 = checkArr(arr, i+1, v, used);
    const res2 = checkArr(arr, i+1, v+arr[i], true);
    const res3 = checkArr(arr, i+1, v-arr[i], true);
    return res1 || res2 || res3;
}

function main() {
    const T = parseInt(readline());
    for (let i = 0; i < T; i++) {
        const N = parseInt(readline());
        const arr = readline().split(' ').map((x) => parseInt(x));
        console.log(checkArr(arr, 0, 0, false) ? "YES" : "NO");
    }
}

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        a = new Array(n);
  for (let i = 0; i < n; i++) a[i] = rn();
  if (a.includes(0)) return 'YES';
  const make = (a, b) => [a - b, a + b, b - a];
  const check = i => {
    let set = new Set([0]),
        nums = [0];
    for (let j = 0; j < n; j++) {
      if (i === j) continue;
      const m = nums.length;
      for (let k = 0; k < m; k++) {
        for (let num of make(nums[k], a[j])) {
          if (a[i] === num) return true;
          if (!set.has(num)) {
            set.add(num);
            nums.push(num);
          }
        }
      }
    }
    return false;
  };
  for (let i = 0; i < n; i++) {
    if (check(i)) return 'YES';
  }
  return 'NO';
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < 100) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= 100) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\s+/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();


class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            const l=_data.split('\n');
            this.data = this.data.concat(l.slice(0,-1).map(string=>string.trim()),l[l.length-1] );
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        let ans="";
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
             ans+=Math.max(0, d) + " ";
            stopAt =f[i];
        }
        print(ans+"\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

T = readline()
while (T--) {
   n = readline()
   s = readline().split(' ').map(a => +a)
   f = readline().split(' ').map(b => +b)
   a = []
   a[0] = f[0] - s[0]
   for(i=1; i<n; i++){
      if(s[i]>f[i-1]){
         a.push(f[i] - s[i])
      }
      else{
         a.push(f[i] - f[i-1])
      }
   }

   print( a.join(' '))
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var taskStartArray = readline().split(" ");
    var taskEndArray = readline().split(" ");
    var result = "";
    for (var j = 0; j < caseLength; j++)
    {
        if (j !== 0)
        {
            var taskStart = parseInt(taskStartArray[j]);
            var prevTaskEnd = parseInt(taskEndArray[j-1]);
            var startTime = Math.max(taskStart, prevTaskEnd);
            var taskTime = parseInt(taskEndArray[j]) - startTime;
            result += `${taskTime} `;
        }
        else
        {
            var taskTime = parseInt(taskEndArray[j]) - parseInt(taskStartArray[j]);
            result += `${taskTime} `;
        }
    }
    print(result);
}

var tests = parseInt(readline());
    var n, s, f;
    for (var t=0; t < tests; t++) {
        n = parseInt(readline());
        s = readline().split(' ').map(x => parseInt(x));
        f = readline().split(' ').map(x => parseInt(x));
        var d = [f[0] - s[0]];
        for (var i = 1; i < n; i++) {
            var start = Math.max(s[i], f[i-1]);
            var diff = f[i] - start;
            d.push(diff);
        }
        print(d.join(' '));
    }

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

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = parseInt(readline());
    for (let j = 0; j < t; j++) {
        const n = parseInt(readline());
        const s = readline().split(" ").map(Number);
        const f = readline().split(" ").map(Number);
        var d = [];
        for (let i = 1; i < n + 1; i++) {
            d[0] = f[0] - s[0];
            if (s[i] < f[i] && s[i] >= f[i - 1]) {
                d.push(f[i] - s[i]);
            }
            if (s[i] < f[i - 1]) {
                d.push(f[i] - f[i - 1]);
            }
        }
        console.log(d.join(" "));

    }
}

'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 S = readline().split(' ').map(Number);
        let F = readline().split(' ').map(Number);
        let D = [];

        let t = 0;
        for (let i = 0; i < n; i++) {
            t = Math.max(S[i], t);
            D[i] = F[i] - t;
            t = F[i];
        }

        output(D.join(' '));
    }
}

"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 = () => {
  const gcd = (a, b) => (a % b === 0 ? b : gcd(b, a % b));
  let t = parseInt(readline());
  while (t--) {
       let n = parseInt(readline());
       let arr1 = readline().trim().split(" ").map(cur=>parseInt(cur));
       let arr2 = readline().trim().split(" ").map(cur=>parseInt(cur));
       let res = [];
       res.push(arr2[0]-arr1[0]);
       for(let i=1;i<n;i++){
            if(arr2[i-1]<arr1[i]) res.push(arr2[i]-arr1[i]);
            else res.push(arr2[i]-arr2[i-1]);
       }
       console.log(res.join(" "));
  }
};
solve();

'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 print(...args) {
    console.log(...args);
}

function main() {
    const testCaseCount = Number(readline())

    for (let index = 0; index < testCaseCount; index++) {

        const taskCount = Number(readline());
        const taskStartTimes = readline().split(" ").map(n => Number(n));
        const taskEndTimes = readline().split(" ").map(n => Number(n));

        const durations = [];

        for (let taskTimeIndex = 0; taskTimeIndex < taskCount; taskTimeIndex++) {
            const endTime = taskEndTimes[taskTimeIndex];

            const startProcessingTime = taskTimeIndex === 0 ?
                taskStartTimes[taskTimeIndex] :
                Math.max(taskStartTimes[taskTimeIndex], taskEndTimes[taskTimeIndex - 1]);

                durations.push(endTime - startProcessingTime);
        }

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

function solve(n, sa, sb) {
    const cs = []
    sa.forEach(x => {
        cs.push([x, 1])
    })
    sb.forEach(x => {
        cs.push([x, -1])
    })
    const ans = []
    const sorted = cs.sort((a, b) => a[0] - b[0])
    // console.log(sorted)
    let prev
    let now = 0
    sorted.forEach(([x, d]) => {
        if (d < 0) {
            ans.push(x - prev)
        }
        //
        now += d
        if (now === 1) {
            // the first
            prev = x
        } else if (d < 0) {
            prev = x
        }
    })
    return ans.join(' ')
}

'use strict';

function solve(n, a, b) {
  const times = new Array(n);
  for (let i = 0; i < n; i++) {
    times[i] = [a[i], b[i]];
  }
  times.sort((a, b) => a[0] - b[0]);
  const res = new Array(n);
  let t = -1;
  for (let [i, [x, y]] of times.entries()) {
    if (t === -1) {
      res[i] = y - x;
    } else {
      res[i] = y - Math.max(x, t);
    }
    t = y;
  }
  return res.join(' ');
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      const b = (await read()).split(' ').map(Number);
      res.push(solve(n, a, b));
    }
    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);
});

T = readline()
while (T--) {
   n = readline()
   s = readline().split(' ').map(a => +a)
   f = readline().split(' ').map(b => +b)
   a = []
   a[0] = f[0]
   for(i=1; i<n; i++){
      if(s[i]>a[i-1]){
         a.push(f[i] - s[i])
      }
      else{
         a.push(f[i] - f[i-1])
      }
   }

   print( a.join(' '))
}

T = readline()
while (T--) {
   n = readline()
   s = readline().split(' ').map(a => +a)
   f = readline().split(' ').map(b => +b)
   a = []
   a[0] = f[0]
   for(i=1; i<n; i++){
      if(s[i]>a[i-1]){
         a.push(f[i] - s[i])
      }
      else{
         a.push(f[i] - f[i-1])
      }
   }
   print(a)
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var taskStartArray = readline().split(" ");
    var taskEndArray = readline().split(" ");
    var result = "";
    for (var j = 0; j < caseLength; j++)
    {
        if (j !== 0)
        {
            var taskStart = parseInt(taskStartArray[j]);
            var prevTaskEnd = parseInt(taskEndArray[j-1]);
            var startTime = Math.max(taskStart, prevTaskEnd);
            var taskTime = parseInt(taskEndArray[j]) - startTime;
            result += `${taskTime}`;
        }
        else
        {
            var taskTime = parseInt(taskEndArray[j]) - parseInt(taskStartArray[j]);
            result += `${taskTime}`;
        }
    }
    print(result);
}

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        let ans="";
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d)){
                print("("+s+"|"+f+")")
                ans="";
            }
            else
             ans+=Math.max(0, d) + " ";
            stopAt =f[i];
        }
        print(ans+"\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d))
                print("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b("+s+"|"+f+")")
            else
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d))
                print("("+s+"|"+f+")")
            else
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d))
                print("("+s+"|"+f+")")
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d))
                print("("+s.length+","+f.length+")")
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d))
                print("("+s[i]+","+f[i]+")")
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length == 0) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//----------------------------------------------------------------
//----------------------------------------------------------------
(async ()=>{
    // x=await read();
    // print(x);
    let t = parseInt(await read());
    while(t--){
        _ = await read();
        let s = await read();
        let f = await read();
        s=s.split(" ");
        f=f.split(" ");
        let stopAt=0;
        for(var i =0;i< s.length ;i++)
        {
            let d=parseInt(f[i])-Math.max(parseInt(s[i]),stopAt);
            print(Math.max(0,d)+ " ");
            stopAt=d==0?stopAt:parseInt(f[i]);
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner{
    data=[];
    constructor(){
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data',_data=>
        {
            this.data =this.data.concat(_data.trim().split('\n').map(string => {
                return string.trim();
            }));
        });
    }
    read=async()=>
    {
        process.stdin.resume();
        while(this.data.length == 0)
        {
            await delay(0);
        }
        process.stdin.pause();
        return this.data.shift();
    };
}

delay = (ms)=> new Promise(
    resolve => setTimeout(resolve, ms));
const print=(text)=>process.stdout.write(""+text);
const scanl= ()=> new Promise(
    resolve=>
    {
        process.stdin.resume();
        process.stdin.once('data',data=>
        {
            process.stdin.pause();
            resolve(data.trim().substring(0,data.length-2))
        })
    });
const scaner=new Scaner()
const read= async ()=>  await scaner.read();
//----------------------------------------------------------------
(async ()=>{
    // x=await read();
    // print(x);
    let t = parseInt(await read());
    while(t--){
        _ = await read();
        let s = await read();
        let f = await read();
        s=s.split(" ");
        f=f.split(" ");
        let stopAt=0;
        for(var i =0;i< s.length ;i++)
        {
            let d=parseInt(f[i])-Math.max(parseInt(s[i]),stopAt);
            print(Math.max(0,d)+ " ");
            stopAt=d==0?stopAt:parseInt(f[i]);
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

delay = (ms)=> new Promise(
    resolve => setTimeout(resolve, ms));
const print=(text)=>process.stdout.write(""+text);
const scanl= ()=> new Promise(
    resolve=>process.stdin.once('data',data=>
        {
            resolve(data.toString().substring(0,data.length-2))
        }));
//----------------------------------------------------------------
(async ()=>{
    let t = parseInt(await scanl());
    while(t--){
        _ = await scanl();
        let s = await scanl();
        let f = await scanl();
        s=s.split(" ");
        f=f.split(" ");
        let stopAt=0;
        for(var i =0;i< s.length ;i++)
        {
            let d=parseInt(f[i])-Math.max(parseInt(s[i]),stopAt);
            print(Math.max(0,d)+ " ");
            stopAt=d==0?stopAt:parseInt(f[i]);
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

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

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = parseInt(readline());

    for (let j = 0; j < t; j++) {
        const n = parseInt(readline());
        const s = readline().split(" ").map(Number);
        const f = readline().split(" ").map(Number);
        var d = [];
        for (let i = 1; i < n + 1; i++) {
            d[0] = f[0] - s[0];
            if (s[i] < f[i] && s[i] > f[i - 1]) {
                d.push(f[i] - s[i]);
            }
            if (s[i] < f[i - 1]) {
                d.push(f[i] - f[i - 1]);
            }
        }
        console.log(d.join(" "));
    }
}

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

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = parseInt(readline());

    for (let j = 0; j < t; j++) {
        const n = parseInt(readline());
        const s = readline().split(" ").map(Number);
        const f = readline().split(" ").map(Number);
        var d = [];

        for (let i = 1; i < n + 1; i++) {
            d[0] = f[0] - s[0];
            if (s[i] < f[i] && s[i] > f[i - 1]) {
                d.push(f[i] - s[i]);
            }
            if (s[i] < f[i - 1]) {
                d.push(f[i] - f[i - 1]);
            }
        }
        console.log(d);
    }
}


var t = +readline();
while (t-->0){
    var pass = readline(),lower = 0,upper = 0,digit=0;
    var check = new Array(pass.length);
    pass = pass.split('');
    pass.forEach((x,i)=>{
        x = x.charCodeAt();
        if (x >= 65 && x <= 90) {
            upper++;
            check[i] = 'u';
        }
        else if (x >= 97 && x <= 122){
          lower++;
          check[i] = 'l';
        }
        else {
            digit++;
            check[i] = 'd';
        }
    });
    if (lower!== 0 && upper!==0 && digit===0){
        for (var i = 1;i<pass.length;i++){
            if ((check[i] === 'l' && lower >= upper) || (check[i] === 'u' && upper >= lower)){
                pass[i] = '0';
                break;
            }
        }
    } else if (lower!== 0 && upper===0 && digit!==0){
        for (var i = 1;i<pass.length;i++){
            if ((check[i] === 'l' && lower >= digit) || (check[i] === 'd' && digit >= lower)){
                pass[i] = 'A';
                break;
            }
        }
    } else if (lower=== 0 && upper!==0 && digit!==0){
        for (var i = 1;i<pass.length;i++){
            if ((check[i] === 'u' && upper >= digit) || (check[i] === 'd' && digit >= upper)){
                pass[i] = 'a';
                break;
            }
        }
    } else if (upper!== 0 && digit === 0 && lower === 0) {
        pass[0] = '0';
        pass[1] = 'a';
    } else if (upper=== 0 && digit === 0 && lower !== 0){
        pass[0] = '0';
        pass[1] = 'A';
    } else if (upper=== 0 && digit !== 0 && lower === 0) {
        pass[0] = 'A';
        pass[1] = 'a';
    }
    var res = '';
    pass.forEach(x=>res+=x);
    print(res);
}

const readline = require('readline');
const fs = require('fs')
const rl = readline.createInterface({
   input: process.stdin,
//   input : fs.createReadStream('practice/codeforces/test.in'),
  output: process.stdout
});
num = 0
rl.on('line', str => {
  if (num == 0) {
    num = str
  } else {
    func(str)
  }
});
isdigit = a => a <= 9 && a >= 0
isLower = a => a <= 'z' && a >= 'a'
isUpper = a => a <= 'Z' && a >= 'A'
function func(str) {
  n = 0;
  l = 0;
  u = 0;
  for (char of str) {
    if (isdigit(char)) {
      n += 1
    } else if (isLower(char)) {
      l += 1
    } else if (isUpper(char)) {
      u += 1
    }
  }
  if (n && l && u) {
    console.log(str)
    return;
  }
  if (n == 0 && l == 0) {
    console.log('1a' + str.slice(2))
  } else if (n == 0 && u == 0) {
    console.log('1A' + str.slice(2))
  } else if (l == 0 && u == 0) {
    console.log('aA' + str.slice(2))
  }
  else {
    if (n == 0) {
      if ((isLower(str[0]) && isLower(str[1])) ||
      (isUpper(str[0]) && isUpper(str[1])) ) {
        console.log('1' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + '1' + str.slice(3))
      }
    }else if (l == 0) {
      if ((isdigit(str[0]) && isdigit(str[1])) ||
        (isUpper(str[0]) && isUpper(str[1]))
      ) {
        console.log('a' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'a' + str.slice(3))
      }
    } else if (u == 0) {
      if ((isLower(str[0]) && isLower(str[1])) ||
      (isdigit(str[0]) && isdigit(str[1]))
      ) {
        console.log('A' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'A' + str.slice(3))
      }
    }
  }
}

var t = +readline();
while (t-->0){
    var pass = readline(),lower = false,upper = false,digit=false;
    var check = new Array(pass.length);
    pass.split('').forEach((x,i)=>{
        x = x.charCodeAt();
        if (x >= 65 && x <= 90) {
            upper = true;
            check[i] = 'u';
        }
        else if (x >= 97 && x <= 122){
          lower = true;
          check[i] = 'l';
        }
        else {
            digit = true;
            check[i] = 'd';
        }
    });
    pass = pass.split('');
    if (lower && upper && !digit){
        for (var i = 1;i<pass.length;i++){
            if (check[i] === check[i-1]){
                pass[i] = '0';
                break;
            }
        }
    } else if (lower && digit && !upper){
        for (var i = 1;i<pass.length;i++){
            if (check[i] === check[i-1]){
                pass[i] = 'A';
                break;
            }
        }
    } else if (upper && digit && !lower){
        for (var i = 1;i<pass.length;i++){
            if (check[i] === check[i-1]){
                pass[i] = 'a';
                break;
            }
        }
    } else if (upper && !digit && !lower) {
        pass[0] = '0';
        pass[1] = 'a';
    } else if (lower && !digit && !upper){
        pass[0] = '0';
        pass[1] = 'A';
    } else if (digit && !lower && !upper) {
        pass[0] = 'A';
        pass[1] = 'a';
    }
    var res = '';
    pass.forEach(x=>res+=x);
    print(res);
}

const readline = require('readline');
const fs = require('fs')
const rl = readline.createInterface({
  input: process.stdin,
  // input : fs.createReadStream('practice/codeforces/test.in'),
  output: process.stdout
});
num = 0
rl.on('line', str => {
  if (num == 0) {
    num = str
  } else {
    func(str)
  }
});
isdigit = a => a <= 9 && a >= 0
isLower = a => a <= 'z' && a >= 'a'
isUpper = a => a <= 'Z' && a >= 'A'
function func(str) {
  n = 0;
  l = 0;
  u = 0;
  for (char of str) {
    if (isdigit(char)) {
      n += 1
    } else if (isLower(char)) {
      l += 1
    } else if (isUpper(char)) {
      u += 1
    }
  }
  if (n && l && u) {
    console.log(str)
    return;
  }
  if (n == 0 && l == 0) {
    console.log('1a' + str.slice(2))
  } else if (n == 0 && u == 0) {
    console.log('1A' + str.slice(2))
  } else if (l == 0 && u == 0) {
    console.log('aA' + str.slice(2))
  }
  else {
    if (n == 0) {
      if (isLower(str[0]) && isLower(str[1])) {
        console.log('1' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + '1' + str.slice(3))
      }
    }else if (l == 0) {
      if (isdigit(str[0]) && isdigit(str[1])) {
        console.log('a' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'a' + str.slice(3))
      }
    } else if (u == 0) {
      if (isLower(str[0]) && isLower(str[1])) {
        console.log('A' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'A' + str.slice(3))
      }
    }
  }
}

const readline = require('readline');
const fs = require('fs')
const rl = readline.createInterface({
   input: process.stdin,
//   input : fs.createReadStream('practice/codeforces/test.in'),
  output: process.stdout
});
num = 0
rl.on('line', str => {
  if (num == 0) {
    num = str
  } else {
    func(str)
  }
});
isdigit = a => a <= 9 && a >= 0
isLower = a => a <= 'z' && a >= 'a'
isUpper = a => a <= 'Z' && a >= 'A'
function func(str) {
  n = 0;
  l = 0;
  u = 0;
  for (char of str) {
    if (isdigit(char)) {
      n += 1
    } else if (isLower(char)) {
      l += 1
    } else if (isUpper(char)) {
      u += 1
    }
  }
  if (n && l && u) {
    console.log(str)
    return;
  }
  if (n == 0 && l == 0) {
    console.log('1a' + str.slice(2))
  } else if (n == 0 && u == 0) {
    console.log('1A' + str.slice(2))
  } else if (l == 0 && u == 0) {
    console.log('aA' + str.slice(2))
  }
  else {
    if (n == 0) {
      if ((isLower(str[0]) && isLower(str[1])) ||
      (isUpper(str[0]) && isUpper(str[1])) ) {
        console.log('1' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + '1' + str.slice(3))
      }
    }else if (l == 0) {
      if ((isdigit(str[0]) && isdigit(str[1])) ||
        (isUpper(str[0]) && isUpper(str[0]))
      ) {
        console.log('a' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'a' + str.slice(3))
      }
    } else if (u == 0) {
      if ((isLower(str[0]) && isLower(str[1])) ||
      (isdigit(str[0]) && isdigit(str[0]))
      ) {
        console.log('A' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'A' + str.slice(3))
      }
    }
  }
}


const solve = (n, m, r, c) => {
    let topLeft = Math.abs(0 - r + 1) + Math.abs(0 - c + 1);
    let topRight = Math.abs(0 - r + 1) + Math.abs(m - 1 - c + 1);
    let bottomLeft = Math.abs(n - 1 - r + 1) + Math.abs(0 - c + 1);
    let bottomRight = Math.abs(n - 1 - r + 1) + Math.abs(m - 1 - c + 1);
    console.log(Math.max(topLeft, topRight, bottomLeft, bottomRight));
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = Number(input[0][0]);
        let i = 1;
        while (t > 0) {
            solve(input[i][0], input[i][1], input[i][2], input[i][3]);
            t--;
            i++;
        }
    });
};

main()

var inputs = parseInt(readline());

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

    var r= params[2];
    var c = params[3];

    var dist = 0;

    if(dist < (r-1)+(c-1))
    {
        dist = (r-1)+(c-1);
    }

    if(dist < Math.abs(r-n)+Math.abs(c-1))
    {
        dist = Math.abs(r-n)+Math.abs(c-1);
    }

    if(dist < Math.abs(r-n)+Math.abs(c-m))
    {
        dist = Math.abs(r-n)+Math.abs(c-m);
    }

    if(dist < Math.abs(r-1)+Math.abs(c-m))
    {
        dist = Math.abs(r-1)+Math.abs(c-m);
    }

    print(dist);

}

process.stdin.resume();
process.stdin.setEncoding('utf8');

let input_stdin = "";
let input = "";
let input_currentline = 0;

function readLine() {
    return input[input_currentline++];
}

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

process.stdin.on('end', function () {
    input = input_stdin.split("\n");
    main();
});

// your code goes here
function main() {
    const T=Number(readLine());
    for (let  i = 0; i < T; i ++) {
        const line = readLine();
        const n = Number(line.split(" ")[0]);
        const m = Number(line.split(" ")[1]);
        const r = Number(line.split(" ")[2]);
        const c = Number(line.split(" ")[3]);
        console.log(Math.max(Math.abs(r-1), Math.abs(r-n)) + Math.max(Math.abs(c-1), Math.abs(c-m)));
    }

}