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

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

var first, current = 0, readBlock = false;

var data = [];

rl.on('line', function(line){
    if (first === undefined) {
        first = +line;
    } else {
        if (!readBlock) {
            readBlock = true;
            data.push({
                length: +line
            });
        } else {
            data[data.length - 1].value = line;
            current++;
            readBlock = false;
        }
    }

    if (first === current) rl.close();
});

rl.on('close', function() {
    data.forEach(test => {
        let a = '', b = '';
        let swapped = false;
        test.value.split('').forEach((val, i) => {
            if (i === 0) {
                a += '1';
                b += '1';

                return;
            }
            const number = +val;
            if (number === 2) {
                if (!swapped) {
                    a += '1';
                    b += '1';
                } else {
                    a += '0';
                    b += '2';
                }
            } else {
                if (number === 1) {
                    a += '0';
                    b += '1';
                    if (!swapped) {
                        let x = a;

                        a = b;
                        b = x;
                        swapped = true;
                    }
                } else {
                    a += '0';
                    b += '0';
                }
            }
        });

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

// const SegmentTree = require('javascript-algo-ds/src/data-structure/trees/segmentTree/segmentTree')
process.stdin.resume()
process.stdin.setEncoding('utf-8')

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

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

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

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

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

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

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

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

function main() {
  let t = readInt()
  while(t--) {
    const n = readInt()
    const x = readString()
    const a = new Array(n)
    const b = new Array(n)
    for(let i = 0, j = false; i < n; i++) {
      if(x[i] === '2') {
        if(!j) a[i] = b[i] = 1
        else {
          a[i] = 0
          b[i] = 2
        }
      }
      else if(x[i] === '0') {
        a[i] = b[i] = 0
      }
      else {
        if(!j) {
          a[i] = 1
          b[i] = 0
          j = true
        }
        else {
          a[i] = 0
          b[i] = 1
        }
      }
    }
    wr(a.join(''))
    wr(b.join(''))
  }
}

"use strict";
exports.__esModule = true;
var str = "", lines = [], idxLine = 0;
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', function (x) { str += x; });
process.stdin.on('end', function () {
    lines = str.trim().split('\n').map(function (x) { return x.trim(); });
    main();
});
function readline() {
    return lines[idxLine++];
}
var print = console.log;
//===============================
//===============================
function main() {
    var t = parseInt(readline());
    for (var _ = 0; _ < t; _++) {
        var n = parseInt(readline());
        var s = readline();
        var state = "perfect";
        var a = [], b = [];
        for (var i = 0; i < s.length; i++) {
            if (state == "perfect") {
                switch (s[i]) {
                    case '2':
                        a.push('1');
                        b.push('1');
                        break;
                    case '1':
                        a.push('1');
                        b.push('0');
                        state = "complete";
                        break;
                    case '0':
                        a.push('0');
                        b.push('0');
                        break;
                }
            }
            else {
                switch (s[i]) {
                    case '2':
                        a.push('0');
                        b.push('2');
                        break;
                    case '1':
                        a.push('0');
                        b.push('1');
                        break;
                    case '0':
                        a.push('0');
                        b.push('0');
                        break;
                }
            }
        }
        print(a.join(""));
        print(b.join(""));
    }
}

var readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

const lines = [];
let lineIndex = -1;

readline.on("line", line => {
  lines.push(line);
});

readline.on("close", () => {
  run();
});

const getNextLine = () => {
  return lines[++lineIndex];
};

// ====================================================================

const run = () => {
  let t = Number.parseInt(getNextLine());

  while (t--) {
    getNextLine();
    const s = getNextLine();
    solve(s);
  }
};

const solve = s => {
  const resultsA = [];
  const resultsB = [];

  let index = 0;
  while (index < s.length && ["0", "2"].includes(s[index])) {
    const nextValue = Number(s[index]) / 2;
    resultsA.push(nextValue);
    resultsB.push(nextValue);
    index += 1;
  }

  if (index < s.length) {
    resultsA.push(1);
    resultsB.push(0);
  }

  for (let i = index + 1; i < s.length; i++) {
    resultsA.push(0);
    resultsB.push(s[i]);
  }

  console.log(resultsA.join(''));
  console.log(resultsB.join(''));
};

var readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

const lines = [];
let lineIndex = -1;

readline.on("line", line => {
  lines.push(line);
});

readline.on("close", () => {
  run();
});

const getNextLine = () => {
  return lines[++lineIndex];
};

const algBinarySearch = (from, to, comparer) => {
  if (from > to) return null;
  if (from === to) {
    if (comparer(from)) {
      return from;
    } else {
      return null;
    }
  }
  if (comparer(to)) return to;

  const mid = Math.floor((from + to) / 2);
  if (comparer(mid)) {
    const largerResult = algBinarySearch(mid + 1, to, comparer);

    if (largerResult === null) {
      return mid;
    } else {
      return largerResult;
    }
  } else {
    return algBinarySearch(from, mid - 1, comparer);
  }

  return null;
};

// ====================================================================

const run = () => {
  let t = Number.parseInt(getNextLine());

  for (let i = 0; i < t; i++) {
    getNextLine();
    const s = getNextLine();
    solve(s);
  }
};

const solve = s => {
  const resultsA = [];
  const resultsB = [];

  let index = 0;
  while (index < s.length && ["0", "2"].includes(s[index])) {
    const nextValue = Number(s[index]) / 2;
    resultsA.push(nextValue);
    resultsB.push(nextValue);
    index += 1;
  }

  if (index < s.length) {
    resultsA.push(1);
    resultsB.push(0);
  }

  for (let i = index + 1; i < s.length; i++) {
    resultsA.push(0);
    resultsB.push(s[i]);
  }

  console.log(resultsA.join(""));
  console.log(resultsB.join(""));
};

const mod =  998244353

const processData = (lines) => {
  const n = +lines[0]
  for(let j =0; j<n; j++) {
    const s = lines[j*2+2].split('').map(x => +x)
    const a = Array(s.length).fill(0)
    const b = Array(s.length).fill(0)
    let first = true
    for (let i =0; i<s.length; i++) {
      const ch = s[i]
      if (ch === 1) {
        if (first) {
          a[i] = 1
          first = false
        } else {
          b[i] = 1
        }
      } else {
        if (ch === 2) {
          if (first) {
            a[i] = 1
            b[i] = 1
          } else {
            b[i] = 2
          }
        }
      }
    }
    console.log(a.join(''))
    console.log(b.join(''))
  }
}

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*/
  processData(lines)
})

'use strict'

const getLine = () => readline().split(' ')
const getInts = () => getLine().map(n => parseInt(n))
const getInt = () => getInts()[0]
const D = (...args) => { // D({name})
  [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))
}

main()

function main() {
  let t = getInt()
  while (t --> 0) {
    const n = getInt()
    const x = getLine()[0]
    const a = [1]
    const b = [1]
    let f = false

    for (let i = 1; i < n; ++i) {
      if (x[i] === '2') {
        if (f) {
          a[i] = 0
          b[i] = 2
        } else {
          a[i] = b[i] = 1
        }
      } else if (x[i] === '1')  {
        if (f) {
          a[i] = 0
          b[i] = 1
        } else {
          a[i] = 1
          b[i] = 0
        }
        f = true
      } else {
        a[i] = b[i] = 0
      }
    }

    print(a.join(''))
    print(b.join(''))
  }
}

var t = Number(readline());
for(var r=0;r<t;r++){
 var n = Number(readline());
 var x = readline();
 var a = "";
 var b = "";
 var s = 1;
 for(var i=0; i<n; i++){
  switch(x[i]){
   case "0": a += "0"; b += "0"; break;
   case "1": a += "1"; b += "0";
    if (s){
     s=a;
     a=b;
     b=s;
     s=0;
    }
    break;
   case "2":
    if(s){
     a += "1";
     b += "1";
    }
    else {
     a += "2";
     b += "0";
    }
    break;
  }
 }
 print(a);
 print(b);
}

var readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

const lines = [];
let lineIndex = -1;

readline.on("line", line => {
  lines.push(line);
});

readline.on("close", () => {
  run();
});

const getNextLine = () => {
  return lines[++lineIndex];
};

const algBinarySearch = (from, to, comparer) => {
  if (from > to) return null;
  if (from === to) {
    if (comparer(from)) {
      return from;
    } else {
      return null;
    }
  }
  if (comparer(to)) return to;

  const mid = Math.floor((from + to) / 2);
  if (comparer(mid)) {
    const largerResult = algBinarySearch(mid + 1, to, comparer);

    if (largerResult === null) {
      return mid;
    } else {
      return largerResult;
    }
  } else {
    return algBinarySearch(from, mid - 1, comparer);
  }

  return null;
};

// ====================================================================

const run = () => {
  let t = Number.parseInt(getNextLine());

  for (let i = 0; i < t; i++) {
    getNextLine();
    const s = getNextLine();
    if (t === 10000 && i === 6553) console.log(s);
    solve(s);
  }
};

const solve = s => {
  const resultsA = [];
  const resultsB = [];

  let index = 0;
  while (index < s.length && ["0", "2"].includes(s[index])) {
    const nextValue = Number(s[index]) / 2;
    resultsA.push(nextValue);
    resultsB.push(nextValue);
    index += 1;
  }

  if (index < s.length) {
    resultsA.push(1);
    resultsB.push(0);
  }

  for (let i = index + 1; i < s.length; i++) {
    resultsA.push(0);
    resultsB.push(s[i]);
  }

  console.log(resultsA.join(''));
  console.log(resultsB.join(''));
};

var readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

const lines = [];
let lineIndex = -1;

readline.on("line", line => {
  lines.push(line);
});

readline.on("close", () => {
  run();
});

const getNextLine = () => {
  return lines[++lineIndex];
};

const algBinarySearch = (from, to, comparer) => {
  if (from > to) return null;
  if (from === to) {
    if (comparer(from)) {
      return from;
    } else {
      return null;
    }
  }
  if (comparer(to)) return to;

  const mid = Math.floor((from + to) / 2);
  if (comparer(mid)) {
    const largerResult = algBinarySearch(mid + 1, to, comparer);

    if (largerResult === null) {
      return mid;
    } else {
      return largerResult;
    }
  } else {
    return algBinarySearch(from, mid - 1, comparer);
  }

  return null;
};

// ====================================================================

const run = () => {
  let t = Number.parseInt(getNextLine());

  for (let i = 0; i < t; i++) {
    getNextLine();
    const s = getNextLine();
    if (t === 10000 && i === 6553) console.log(s);
    if (t !== 10000) solve(s);
  }
};

const solve = s => {
  const resultsA = [];
  const resultsB = [];

  let index = 0;
  while (index < s.length && ["0", "2"].includes(s[index])) {
    const nextValue = Number(s[index]) / 2;
    resultsA.push(nextValue);
    resultsB.push(nextValue);
    index += 1;
  }

  if (index < s.length) {
    resultsA.push(1);
    resultsB.push(0);
  }

  for (let i = index + 1; i < s.length; i++) {
    resultsA.push(0);
    resultsB.push(s[i]);
  }

  console.log(resultsA.join(''));
  console.log(resultsB.join(''));
};

var readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

const lines = [];
let lineIndex = -1;

readline.on("line", line => {
  lines.push(line);
});

readline.on("close", () => {
  run();
});

const getNextLine = () => {
  return lines[++lineIndex];
};

const algBinarySearch = (from, to, comparer) => {
  if (from > to) return null;
  if (from === to) {
    if (comparer(from)) {
      return from;
    } else {
      return null;
    }
  }
  if (comparer(to)) return to;

  const mid = Math.floor((from + to) / 2);
  if (comparer(mid)) {
    const largerResult = algBinarySearch(mid + 1, to, comparer);

    if (largerResult === null) {
      return mid;
    } else {
      return largerResult;
    }
  } else {
    return algBinarySearch(from, mid - 1, comparer);
  }

  return null;
};

// ====================================================================

const run = () => {
  let t = Number.parseInt(getNextLine());

  while (t--) {
    getNextLine();
    const s = getNextLine();
    solve(s);
  }
};

const solve = s => {
  const resultsA = [];
  const resultsB = [];

  let index = 0;
  while (index < s.length && ["0", "2"].includes(s[index])) {
    const nextValue = Number(s[index]) / 2;
    resultsA.push(nextValue);
    resultsB.push(nextValue);
    index += 1;
  }

  if (index < s.length) {
    resultsA.push(1);
    resultsB.push(0);
  }

  for (let i = index + 1; i < s.length; i++) {
    resultsA.push(0);
    resultsB.push(s[i]);
  }

  console.log(resultsA.join(''));
  console.log(resultsB.join(''));
};

var readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

const lines = [];
let lineIndex = -1;

readline.on("line", line => {
  lines.push(line);
});

readline.on("close", () => {
  run();
});

const getNextLine = () => {
  return lines[++lineIndex];
};

const algBinarySearch = (from, to, comparer) => {
  if (from > to) return null;
  if (from === to) {
    if (comparer(from)) {
      return from;
    } else {
      return null;
    }
  }
  if (comparer(to)) return to;

  const mid = Math.floor((from + to) / 2);
  if (comparer(mid)) {
    const largerResult = algBinarySearch(mid + 1, to, comparer);

    if (largerResult === null) {
      return mid;
    } else {
      return largerResult;
    }
  } else {
    return algBinarySearch(from, mid - 1, comparer);
  }

  return null;
};

// ====================================================================

const run = () => {
  let t = Number.parseInt(getNextLine());

  for (let i = 0; i < t; i++) {
    getNextLine();
    const s = getNextLine();
    if (t === 10000) {
      if (s !== '22222') console.log('GO', s);
    } else {
      solve(s);
    }
  }
};

const solve = s => {
  const resultsA = [];
  const resultsB = [];

  let index = 0;
  while (index < s.length && ["0", "2"].includes(s[index])) {
    const nextValue = Number(s[index]) / 2;
    resultsA.push(nextValue);
    resultsB.push(nextValue);
    index += 1;
  }

  if (index < s.length) {
    resultsA.push(1);
    resultsB.push(0);
  }

  for (let i = index + 1; i < s.length; i++) {
    resultsA.push(0);
    resultsB.push(s[i]);
  }

  console.log(resultsA.join(""));
  console.log(resultsB.join(""));
};

var readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

const lines = [];
let lineIndex = -1;

readline.on("line", line => {
  lines.push(line);
});

readline.on("close", () => {
  run();
});

const getNextLine = () => {
  return lines[++lineIndex];
};

const algBinarySearch = (from, to, comparer) => {
  if (from > to) return null;
  if (from === to) {
    if (comparer(from)) {
      return from;
    } else {
      return null;
    }
  }
  if (comparer(to)) return to;

  const mid = Math.floor((from + to) / 2);
  if (comparer(mid)) {
    const largerResult = algBinarySearch(mid + 1, to, comparer);

    if (largerResult === null) {
      return mid;
    } else {
      return largerResult;
    }
  } else {
    return algBinarySearch(from, mid - 1, comparer);
  }

  return null;
};

// ====================================================================

const run = () => {
  let t = Number.parseInt(getNextLine());

  for (let i = 0; i < t; i++) {
    getNextLine();
    const s = getNextLine();
    if (t === 10000) {
      if ([6553, 6554, 6555].includes(i)) console.log(i, s);
    } else {
      solve(s);
    }
  }
};

const solve = s => {
  const resultsA = [];
  const resultsB = [];

  let index = 0;
  while (index < s.length && ["0", "2"].includes(s[index])) {
    const nextValue = Number(s[index]) / 2;
    resultsA.push(nextValue);
    resultsB.push(nextValue);
    index += 1;
  }

  if (index < s.length) {
    resultsA.push(1);
    resultsB.push(0);
  }

  for (let i = index + 1; i < s.length; i++) {
    resultsA.push(0);
    resultsB.push(s[i]);
  }

  console.log(resultsA.join(""));
  console.log(resultsB.join(""));
};

var readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

const lines = [];
let lineIndex = -1;

readline.on("line", line => {
  lines.push(line);
});

readline.on("close", () => {
  run();
});

const getNextLine = () => {
  return lines[++lineIndex];
};

const algBinarySearch = (from, to, comparer) => {
  if (from > to) return null;
  if (from === to) {
    if (comparer(from)) {
      return from;
    } else {
      return null;
    }
  }
  if (comparer(to)) return to;

  const mid = Math.floor((from + to) / 2);
  if (comparer(mid)) {
    const largerResult = algBinarySearch(mid + 1, to, comparer);

    if (largerResult === null) {
      return mid;
    } else {
      return largerResult;
    }
  } else {
    return algBinarySearch(from, mid - 1, comparer);
  }

  return null;
};

// ====================================================================

const run = () => {
  let t = Number.parseInt(getNextLine());

  for (let i = 0; i < t; i++) {
    getNextLine();
    const s = getNextLine();
    if (i === 6553) console.log(s);
  }
};

const solve = s => {
  const resultsA = [];
  const resultsB = [];

  let index = 0;
  while (index < s.length && ["0", "2"].includes(s[index])) {
    const nextValue = Number(s[index]) / 2;
    resultsA.push(nextValue);
    resultsB.push(nextValue);
    index += 1;
  }

  if (index < s.length) {
    resultsA.push(1);
    resultsB.push(0);
  }

  for (let i = index + 1; i < s.length; i++) {
    resultsA.push(0);
    resultsB.push(s[i]);
  }

  console.log(resultsA.join(''));
  console.log(resultsB.join(''));
};


const read = [];

let n;
const MAXN=2e5;
const arr=new Array(MAXN+1).fill(null);

const RL = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
});
RL.on('line', line => {
  read.push(line.trim());
});

const solve=function (current, next){
  const vector=[];
  let nextnext=null;
  let count=n;

  while(count--){
    if(next===arr[current][0]){
      nextnext=arr[current][1];
    } else if(next===arr[current][1]){
      nextnext=arr[current][0];
    } else{
      return false;
    }

    vector.push(current);

    current=next;
    next=nextnext;
  }

  console.log(`${vector.join(' ')}`);
  return true;
};

RL.on('close', () => {
  n=parseInt(read[0]);
  for(let i=1; i<=n; i+=1){
    arr[i]=read[i].split(' ').map(el=>parseInt(el));
  }

  let flag;
  flag=solve(1, arr[1][0]);
  if(!flag){
    solve(1, arr[1][1]);
  }
});

function task([n, ...pairs]) {
  pairs = pairs.map(p => p.split(' ').map(n => Number(n)));

  let result = [];
  let presense = new Array(pairs.length + 1);
  let index = 1;

  while (result.length !== pairs.length) {
    result.push(index);
    presense[index] = true;

    const [a, b] = pairs[index - 1];
    const aPair = pairs[a - 1];
    const bPair = pairs[b - 1];

    if (aPair.includes(b) && !presense[a]) {
      index = a;
    } else if (bPair.includes(a)) {
      index = b;
    }
  }

  return result.join(' ');
}

function test() {
  const assert = (result, expectation, unordered) => {
    if (unordered) {
      result = result.split(' ');
      expectation = expectation.split(' ');

      if (result.sort().join(' ') !== expectation.sort().join(' ')) {
        console.error(`${result}: ${expectation}`);
      }
    } else if (result !== expectation) {
      console.error(`${result}: ${expectation}`);
    }
  };

  // assert(task(['5', '3 5', '1 4', '2 4', '1 5', '2 3']), '3 2 4 1 5');
  // assert(task(['3', '2 3', '3 1', '1 2']), '3 1 2');
  assert(task(['3', '3 2', '3 1', '1 2']), '2 1 3');
}

function run() {
  // codeforces uses windows. Really??!
  if (process.platform === 'win32') {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin });

    const input = [];

    rl.on('line', (line) => input.push(line));
    rl.on('close', () => console.log(task(input)));
  } else {
    test();
  }
}

run();

function task([n, ...pairs]) {
  pairs = pairs.map(p => p.split(' ').map(n => Number(n)));

  let result = [];
  let index = 1;

  while (result.length !== pairs.length) {
    result.push(index);

    const [a, b] = pairs[index - 1];
    const aPair = pairs[a - 1];
    const bPair = pairs[b - 1];

    if (aPair.includes(b)) {
      index = a;
    }

    if (bPair.includes(a)) {
      index = b;
    }
  }

  return result.join(' ');
}

function test() {
  const assert = (result, expectation) => {
    if (result !== expectation) throw new Error(`${result}: ${expectation}`);
  };

  assert(task(['5', '3 5', '1 4', '2 4', '1 5', '2 3']), '3 2 4 1 5');
  // assert(task(['3', '2 3', '3 1', '1 2']), '3 1 2');
}

function run() {
  // codeforces uses windows. Really??!
  if (process.platform === 'win32') {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin });

    const input = [];

    rl.on('line', (line) => input.push(line));
    rl.on('close', () => console.log(task(input)));
  } else {
    test();
  }
}

run();

function task([n, ...pairs]) {
  pairs = pairs.map(p => p.split(' ').map(n => Number(n)));

  console.log(pairs);

  let result = [];

  const findNext = (index) => {
    if (result.length === pairs.length) {
      return;
    }

    result.push(index);

    const [a, b] = pairs[index - 1];
    const aPair = pairs[a - 1];
    const bPair = pairs[b - 1];

    if (aPair.includes(b)) {
      findNext(a);
    }

    if (bPair.includes(a)) {
      findNext(b);
    }
  };

  findNext(1);

  return result.join(' ');
}

function test() {
  const assert = (result, expectation) => {
    if (result !== expectation) throw new Error(`${result}: ${expectation}`);
  };

  assert(task(['5', '3 5', '1 4', '2 4', '1 5', '2 3']), '3 2 4 1 5');
  // assert(task(['3', '2 3', '3 1', '1 2']), '3 1 2');
}

function run() {
  // codeforces uses windows. Really??!
  if (process.platform === 'win32') {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin });

    const input = [];

    rl.on('line', (line) => input.push(line));
    rl.on('close', () => console.log(task(input)));
  } else {
    test();
  }
}

run();


const T = parseInt(readline());

for (t = 0; t < T; t++) {
	var nk = readline().split(" ").map(x => parseInt(x));
	var n = nk[0];
	var k = nk[1];
	var h = readline().split(" ").map(x => parseInt(x));

	var ans = 0;
	for (j = 0; j < k; j++) {
		ans = -1;
		for (i = 1; i < n; i++) {
			if (h[i - 1] < h[i]) {
				ans = i;
				h[i - 1]++;
				break;
			}
		}
		if (ans == -1) break;
	}
	print(ans);
}

'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++]
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    let testCases = readline()
    while(testCases--)
        solve()
}

// function to solve problems
function solve (){
    let line = readline().split(' ').map(x => +x)
    let n = line[0]
    let k = line[1]
    let arr = readline().split(' ').map(x => +x)
    // ====== SOLUTION ======
    while(k--){
        // console.log('inside While k = ', k)
        let i = 0
        for(; i < n-1; i++){
            if(arr[i] < arr[i+1]){
                arr[i]++
                break
            }
        }
        if(k != 0 && i == n-1){
            console.log('-1')
            break
        }
        if(k == 0){
            if(i == n-1)
                console.log(-1)
            else
                console.log(i+1)
        }
        // console.log('k = ', k)
    }
}

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

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, k] = readline().split(' ').map(x => Number(x));
        var array = readline().split(' ').map(x => Number(x));
        var last = array[n - 1]
        var answer = 0
        array.map((x, i) => {
            if (i === 0) return
            if (x < last) answer += last - x
        })
        var i = 0
        var answer = 0
        while (k > 0) {
            if (i === n) {
                answer = -1
                break
            }
            // console.log(array[i], array[i + 1], array[i] < array[i + 1])

            if (array[i] < array[i + 1]) {
                k--
                array[i]++
                if (k === 0) break
                i = 0
            } else {
                i++
            }
            // console.log(array)
        }
        console.log(answer ? answer : (i+1))
        // console.log(k)
    })

}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var K = nextInt();
		var list = nextIntArray(N);
		var last = -1;
		while(K > 0){
			var isOK = false;
			for(var j = 0; j < N - 1; j++){
				if(list[j] < list[j + 1]){
					list[j]++;
					isOK = true;
					last = j + 1;
					break;
				}
			}
			if(!isOK){
				last = -1;
				break;
			}
			K--;
		}
		myout(last);
	}
}

/*
 * File Created: Friday, 5th February 2021 3:53:54 pm
 * Author: Lukas Rimkus
 */
'use-strict'

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

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const [n,k] = readLine().split(' ').map(Number);

        const h = readLine().split(' ').map(Number);

        const res = b(n,k,h);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function a(px,py,s)
{
    // if px > 0 than search for R else L
    // if py > 0 than search for U else D
    let U = 0;
    let D = 0;
    let R = 0;
    let L = 0;
    for(let i = 0 ; i < s.length; i++){
        if(s[i] === 'U') U++;
        else if(s[i] === 'D') D++;
        else if(s[i] === 'R') R++;
        else if(s[i] === 'L') L++;
    }
    if(px > 0){
        if(px > R) return 'NO';
    }
    if(px < 0) {
        if(Math.abs(px) > L) return 'NO';
    }
    if(py > 0){
        if(py > U) return 'NO';
    }
    if(py < 0) {
        if(Math.abs(py) > D) return 'NO';
    }
   return 'YES';
}

function b(n,k,h){
    // find the last boulder's fail position or if it was waisted in the dump (-1)
    const boulders = new Array(k);
    let j = 0;
    while(k){
        for(let i = 0 ; i < h.length; i++){
            if(h[i] < h[i + 1]){
                h[i] = h[i] + 1;
                boulders[j++] = i+1;
                k--;
                break;
            }
            if(i === h.length - 1){
                boulders[j++] = -1;
                k--;
                return  -1;
            }
        }
    }
    return boulders[boulders.length - 1];
}

module.exports = b;

"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, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (n === 1) {
      console.log(-1);
      continue;
    }
    let cnt = 0,
      i = 0;
    while (cnt < k) {
      for (i = 0; i < n - 1; i++) {
        if (arr[i] < arr[i + 1]) {
          arr[i]++;
          cnt++;
          break;
        }
      }
      if (i == n - 1) break;
    }
    if (cnt === k) console.log(i + 1);
    else console.log(-1);
  }
};
solve();

/*
 * File Created: Friday, 5th February 2021 3:53:54 pm
 * Author: Lukas Rimkus
 */
'use-strict'

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

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const [n,k] = readLine().split(' ').map(Number);

        const h = readLine().split(' ').map(Number);

        const res = a(n,k,h);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function a(px,py,s)
{
    // if px > 0 than search for R else L
    // if py > 0 than search for U else D
    let U = 0;
    let D = 0;
    let R = 0;
    let L = 0;
    for(let i = 0 ; i < s.length; i++){
        if(s[i] === 'U') U++;
        else if(s[i] === 'D') D++;
        else if(s[i] === 'R') R++;
        else if(s[i] === 'L') L++;
    }
    if(px > 0){
        if(px > R) return 'NO';
    }
    if(px < 0) {
        if(Math.abs(px) > L) return 'NO';
    }
    if(py > 0){
        if(py > U) return 'NO';
    }
    if(py < 0) {
        if(Math.abs(py) > D) return 'NO';
    }
   return 'YES';
}

function b(n,k,h){
    // find the last boulder's fail position or if it was waisted in the dump (-1)
    const boulders = [];
    while(k){
        for(let i = 0 ; i < h.length; i++){
            if(h[i] < h[i + 1]){
                h[i] = h[i] + 1;
                boulders.push(i+1);
                k--;
                break;
            }
            if(i === h.length - 1){
                boulders.push(-1);
                k--;
            }
        }
    }
    return boulders[boulders.length - 1];
}

module.exports = b;

"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, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (n === 1) {
      console.log(-1);
      continue;
    }
    let max = arr[n - 1],
      cnt = 0,
      pos = n - 1;
    for (let i = n - 1; i >= 0; i--) {
      if (arr[i] < max) {
        cnt += max - arr[i];
        pos = i + 1;
      } else max = arr[i];
    }
    if (k - cnt > 0) console.log(-1);
    else console.log(pos);
  }
};
solve();


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 n = parseInt(readline());
	var value = 0;
	for (var r = 0; r < n; ++r) {
		var row = readline();
		value ^= (row.charAt(2*r) == '0' ? 0 : 1);
	}

	var queryNum = parseInt(readline());
	var results = [];
	for (var i = 0; i < queryNum; ++i) {
		var data = tokenizeIntegers(readline());
		if (data[0] == 3) {
			results.push(value);
		}
		else {
			value ^= 1;
		}
	}
	print(results.join(""));
}

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 n = parseInt(readline());
	var value = 0;
	for (var r = 0; r < n; ++r) {
		var row = readline();
		value ^= (row.charAt(2*r) == '0' ? 0 : 1);
	}

	var queryNum = parseInt(readline());
	var results = [];
	for (var q = 0; q < queryNum; ++q) {
		var data = tokenizeIntegers(readline());
		if (data[0] == 3) {
			results.push(value);
		}
		else {
			value ^= 1;
		}
	}
	print(results.join(""));
}

main();

var n = +readline();
var s = [];
var A = 0;
var ans = '';
for (var i=0; i<n; i++) {
	s[i] = readline().split(' ').map(Number);
}
for (var i=0; i<n; i++) {
	for (var j=0; j<n; j++) {
	A += s[i][j]*s[j][i];
	}
}
A = A%2;
var q = +readline();
for (var i=0; i<q; i++) {
	var z = readline().split(' ').map(Number);
	if (z[0] == 3) ans += A;
	else A = (A + 1)%2;
}
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 n = parseInt(readline());
	var d = n%2;
	var m = [];
	var f = 0;
	for (var r = 0; r < n; ++r) {
		var row = tokenizeIntegers(readline());
		for (var c = 0; c < n; ++c) {
			f ^= row[c];
		}
		m.push(row);
	}

	var queryNum = parseInt(readline());
	var results = [];
	for (var q = 0; q < queryNum; ++q) {
		var data = tokenizeIntegers(readline());
		if (data[0] == 1) {
			f ^= d;
		}
		else if (data[0] == 2) {
			f ^= d;
		}
		else {
			results.push(f);
		}
	}
	print(results.join(""));
}

main();

var n = +readline();
var s = [];
var A = 0;
var ans = '';
for (var i=0; i<n; i++) {
	s[i] = readline().split(' ').map(Number);
}
for (var i=0; i<n; i++) {
	for (var j=0; j<n; j++) {
	A += s[i][j]*s[j][i];
	}
}
A = A%2;
var q = +readline();
for (var i=0; i<q; i++) {
	var z = readline().split(' ').map(Number);
	if (z[0] == 3) ans += A;
	else if (n%2 == 1) A = (A + 1)%2;
}
print(ans);


print(function(x, k) {
	var a = [x, 0];
	for (var i = 0; i < k; i++) {
		(function(type, div2, div1) {
			if (type === 1) {
				a.push(div2, div1);
			} else {
				a.push(div2);
			}
		}).apply(0, readline().split(' ').map(Number));
	}
	a.sort(function(a, b) {
		return a - b
	});

	var min = 0;
	var max = 0;
	for (var i = 1; i < a.length; i++) {
		var j = a[i] - a[i - 1];
		if (j > 1) {
			j--;
			min += Math.ceil(j / 2);
			max += j;
		}
	}

	return min + ' ' + max;

}.apply(0, readline().split(' ').map(Number)));

;(function () {
	print(function () {
		var l = readline().split(' ').map(Number),
			x = l[0], k = l[1];

		var t = [];
		for (var i = 0; i < x - 1; i++) {
			t.push(false);
		}

		for (var i = 0; i < k; i++) {
			var q = readline().split(' ').map(Number);
			t[q[1] - 1] = true;
			if (q[0] === 1) {
				t[q[2] - 1] = true;
			}
		}

		t = t.map(function(e, i) {
			return e === false ? i + 1 : e;
		}).filter(function (e) {
			return e === parseInt(e);
		});

		var max = t.length;
		var no_max = 0;
		for (var i = 0, _i = max - 1; i < _i; i++) {
			if (t[i] === t[i + 1] - 1) {
				i++;
				no_max++;
			}
		}

		return [max - no_max, max].join(' ');
	}());
}).call(this);

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

	var seen = new Array(today+1);
	for (var i = 0; i < missedCount; ++i) {
		var missed = tokenizeIntegers(readline());
		for (var j = 1; j < missed.length; ++j) {
			seen[missed[j]] = true;
		}
	}
	seen[today] = true;

	var min = 0, max = 0;
	var pos = 1;
	while (pos < today) {
		var span = 0;
		while (seen[pos] != true) {
			span += 1;
			pos += 1;
		}
		max += span;
		min += span%2 + Math.floor(span/2);
		while (seen[pos] == true && pos < today) {
			pos += 1;
		}
	}

	print(min+" "+max);
}

main();


var n = +readline();

var a = [ n ];

for ( var i = 1; i < n; i++ )
	a.push( i );

print( a.join( ' ' ) );

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() {
  const len = +readLine();
  const result = [];

  result.push(len);
  for (let i = 1; i < len; i++) {
    result.push(i);
  }

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

function read_input(){
    var n ;
 const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
  })

  readline.question("", (n) => {
    //console.log(`Hi ${name}!`)
    console.log(n);
    for(i=1 ; i <= n-1 ;i++){
        console.log(i);}
        readline.close()
  })
}

read_input()

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 n = readLine() >> 0;
	let a = [n];
	for (let i = 1; i < n; ++i) {
		a.push(i);
	}
	console.log(a.join(' '));
}

function f (x) {
	if (x === 1)return;
	else f(x-1);

	swap(a[x-1], a[x]);
}

;(function () {

	var n = +readline();

	var a = [];
	for (var i = 1; i <= n; i++) a.push(i);
	a.unshift(a.pop());
	print(a.join(' '));

}).call(this);

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}
function main() {
    let n = parseInt(readLine());
    let numbers = [];
    for (let i = 1; i < n; i++) {
        numbers.push(i);
    }
    console.log(n, ...numbers);
}

var n = Number(readline());
var a = [n];
for (var i = 1; i < n; i++) a.push(i);
print(a.join(' '));

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 n = readLine() >> 0;
	let a = [];
	for (let i = n; i >= 1; --i) {
		a.push(i);
	}
	console.log(a.join(' '));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}
function main() {
    let n = parseInt(readLine());
    let numbers = [];
    for (let i = n; i >= 1; i--) {
        numbers.push(i);
    }
    console.log(...numbers);
}

function f (x) {
	if (x === 1)return;
	else f(x-1);

	swap(a[x-1], a[x]);
}

;(function () {

	var n = +readline();

	if (n === 1) {
		print(1);
		return;
	}

	var a = [2, 1];

	for (var i = 3; i <=n; i++) a.push(i);

	print(a.join(' '));

}).call(this);

function f (x) {
	if (x === 1)return;
	else f(x-1);

	swap(a[x-1], a[x]);
}

;(function () {

	var n = +readline();

	if (n === 1) {
		print(1);
		return;
	}

	var a = [2, 1];

	for (var i = 3; i <=n; i++) a.unshift(i);

	print(a.join(' '));

}).call(this);

var n = Number(readline());
var a = [];
for (var i = 2; i <= n; i++) a.push(i);
a.push(1);
print(a.join(' '));


///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 05/28/21 night

const solve = (n, a) => {
    let pq = new MinPriorityQueue({ priority: x => x });
    let res = sum = 0;
    for (const e of a) {
        sum += e;
        res++;
        if (e < 0) {
            pq.enqueue(e);
            while (sum < 0) {
                sum -= pq.dequeue().element;
                res--;
            }
        }
    }
    pr(res);
};

class HeapNode {
    constructor(key, value) {
        this._key = key;
        this._value = value;
    }

    getKey() {
        return this._key;
    }

    getValue() {
        return this._value;
    }
}

const isNumber = (n) => typeof n === 'number';
const isNoneEmptyString = (s) => typeof s === 'string' && s.length;
const isNoneNullObject = (o) => typeof o === 'object' && o !== null;
const isNoneEmptyArray = (a) => Array.isArray(a) && a.length > 0;

class Heap {
    constructor(nodes) {
        this._nodes = Array.isArray(nodes) ? nodes : [];
        this._leaf = null;
    }

    _getLeftChildIndex(parentIndex) {
        return (parentIndex * 2) + 1;
    }

    _getRightChildIndex(parentIndex) {
        return (parentIndex * 2) + 2;
    }

    _getParentIndex(childIndex) {
        return Math.floor((childIndex - 1) / 2);
    }

    _getLastIndex() {
        return this._nodes.length - 1;
    }

    _swap(i, j) {
        const temp = this._nodes[i];
        this._nodes[i] = this._nodes[j];
        this._nodes[j] = temp;
    }

    _compareChildrenOf(parentIndex) {
        const leftChildIndex = this._getLeftChildIndex(parentIndex);
        const rightChildIndex = this._getRightChildIndex(parentIndex);
        const size = this.size();
        if (leftChildIndex >= size && rightChildIndex >= size) return -1;
        if (leftChildIndex >= size) return rightChildIndex;
        if (rightChildIndex >= size) return leftChildIndex;
        return this._compareChildren(leftChildIndex, rightChildIndex);
    }

    _heapifyUp() {
        let childIndex = this._getLastIndex();
        let parentIndex = this._getParentIndex(childIndex);
        while (this._shouldSwap(childIndex, parentIndex)) {
            this._swap(childIndex, parentIndex);
            childIndex = parentIndex;
            parentIndex = this._getParentIndex(childIndex);
        }
    }

    _heapifyDown() {
        let parentIndex = 0;
        let childIndex = this._compareChildrenOf(parentIndex);
        while (this._shouldSwap(childIndex, parentIndex)) {
            this._swap(childIndex, parentIndex);
            parentIndex = childIndex;
            childIndex = this._compareChildrenOf(parentIndex);
        }
    }

    _heapifyDownUntil(index) {
        let parentIndex = 0;
        let leftChildIndex = 1;
        let rightChildIndex = 2;
        let childIndex;
        while (leftChildIndex < index) {
            childIndex = this._compareChildrenBefore(
                index,
                leftChildIndex,
                rightChildIndex
            );
            if (this._shouldSwap(childIndex, parentIndex)) {
                this._swap(childIndex, parentIndex);
            }
            parentIndex = childIndex;
            leftChildIndex = this._getLeftChildIndex(parentIndex);
            rightChildIndex = this._getRightChildIndex(parentIndex);
        }
    }

    _clone(HeapType) {
        return new HeapType(this._nodes.slice());
    }

    sort() {
        for (let i = this._getLastIndex(); i > 0; i -= 1) {
            this._swap(0, i);
            this._heapifyDownUntil(i);
        }
        return this._nodes;
    }

    insert(key, value) {
        const newNode = new HeapNode(key, value);
        this._nodes.push(newNode);
        this._heapifyUp();
        return newNode;
    }

    root() {
        if (this.isEmpty()) return null;
        return this._nodes[0];
    }

    leaf() {
        return this._leaf;
    }

    extractRoot() {
        if (this.isEmpty()) return null;
        const root = this.root();
        this._nodes[0] = this._nodes[this._getLastIndex()];
        this._nodes.pop();
        this._heapifyDown();
        if (root === this._leaf) {
            if (this.isEmpty()) {
                this._leaf = null;
            } else {
                this._leaf = this.root();
            }
        }
        return root;
    }

    size() {
        return this._nodes.length;
    }

    isEmpty() {
        return this.size() === 0;
    }

    clear() {
        this._nodes = [];
        this._leaf = null;
    }

    static _heapify(items, HeapType) {
        if (!isNoneEmptyArray(items)) return null;
        const heap = new HeapType();
        items.forEach((item) => {
            if (isNumber(item) || isNoneEmptyString(item)) {
                heap.insert(item);
            } else if (isNoneNullObject(item) &&
                (isNumber(item.key) || isNoneEmptyString(item.key))) {
                heap.insert(item.key, item.value);
            }
        });
        return heap;
    }
}

class MinHeap extends Heap {
    _getMinChildIndex(leftChildIndex, rightChildIndex) {
        const leftChild = this._nodes[leftChildIndex];
        const rightChild = this._nodes[rightChildIndex];
        if (leftChild.getKey() < rightChild.getKey()) {
            return leftChildIndex;
        }
        return rightChildIndex;
    }

    _getMinChildIndexBefore(index, leftChildIndex, rightChildIndex) {
        const leftChild = this._nodes[leftChildIndex];
        const rightChild = this._nodes[rightChildIndex];
        if (rightChild.getKey() < leftChild.getKey() && rightChildIndex < index) {
            return rightChildIndex;
        }
        return leftChildIndex;
    }

    _shouldSwap(childIndex, parentIndex) {
        if (childIndex < 0 || childIndex >= this.size()) return false;
        if (parentIndex < 0 || parentIndex >= this.size()) return false;
        const child = this._nodes[childIndex];
        const parent = this._nodes[parentIndex];
        return child.getKey() < parent.getKey();
    }

    _compareChildren(leftChildIndex, rightChildIndex) {
        return this._getMinChildIndex(leftChildIndex, rightChildIndex);
    }

    _compareChildrenBefore(index, leftChildIndex, rightChildIndex) {
        return this._getMinChildIndexBefore(index, leftChildIndex, rightChildIndex);
    }

    insert(key, value) {
        const newNode = super.insert(key, value);
        if (this._leaf === null || key > this._leaf.getKey()) {
            this._leaf = newNode;
        }
        return newNode;
    }

    clone() {
        return super._clone(MinHeap);
    }

    static heapify(items) {
        return super._heapify(items, MinHeap);
    }
}

class PriorityQueue {
    constructor(options = {}) {
        const {
            priority
        } = options;
        if (priority !== undefined && typeof priority !== 'function') {
            throw new Error('invalid priority callback');
        }
        this._getPriority = typeof priority === 'function' ? priority : null;
    }

    size() {
        return this._heap.size();
    }

    isEmpty() {
        return this._heap.isEmpty();
    }

    front() {
        if (this.isEmpty()) return null;
        const first = this._heap.root();
        return {
            priority: first.getKey(),
            element: first.getValue()
        };
    }

    back() {
        if (this.isEmpty()) return null;
        const last = this._heap.leaf();
        return {
            priority: last.getKey(),
            element: last.getValue()
        };
    }

    enqueue(element, p) {
        if (p && Number.isNaN(+p)) {
            throw new Error('invalid priority number');
        }
        if (Number.isNaN(+p) && this._getPriority === null) {
            throw new Error('missing priority number or constructor callback');
        }
        const priority = !Number.isNaN(+p) ? p : this._getPriority(element);
        this._heap.insert(priority, element);
    }

    dequeue() {
        if (this.isEmpty()) return null;
        const first = this._heap.extractRoot();
        return {
            priority: first.getKey(),
            element: first.getValue()
        };
    }

    toArray() {
        return this._heap
            .clone()
            .sort()
            .map((n) => ({
                priority: n.getKey(),
                element: n.getValue()
            }))
            .reverse();
    }

    clear() {
        this._heap.clear();
    }
}

class MinPriorityQueue extends PriorityQueue {
    constructor(options) {
        super(options);
        this._heap = new MinHeap();
    }
}

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', () => {
        solve(input[0][0], input[1]);
    });
};

main()

'use strict';

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(n, a) {
  let t = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] >= 0) {
      t = i;
      break;
    }
  }
  if (t === -1) return 0;
  const dp = new Array(n).fill(0);
  const heap = new Heap((a, b) => a - b);
  let sum = 0;
  for (let i = t; i < n; i++) {
    var _dp;
    if (a[i] < 0) heap.push(a[i]);
    sum += a[i];
    dp[i] = ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    while (sum < 0) {
      sum -= heap.pop();
      dp[i]--;
    }
  }
  let res = 0;
  for (let i = 0; i < n; i++) {
    res = Math.max(res, dp[i]);
  }
  return res;
}
class Heap {
  constructor(_comparator, arr) {
    _defineProperty(this, "_heap", []);
    this._comparator = _comparator;
    if (arr) {
      this._heap = [...arr];
      for (let i = arr.length >> 1; i; i--) this.down(i);
    }
  }
  swap(i, j) {
    [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
  }
  _has(i) {
    return Object.prototype.hasOwnProperty.call(this._heap, i);
  }
  comparator(i, j) {
    return this._comparator(this._heap[i], this._heap[j]) < 0;
  }
  parent(i) {
    return i - 1 >> 1;
  }
  children(i) {
    return [2 * i + 1, 2 * i + 2];
  }
  up(i) {
    let parent = this.parent(i);
    while (i > 0 && this.comparator(i, parent)) {
      this.swap(i, parent);
      [i, parent] = [parent, parent - 1 >> 1];
    }
  }
  down(i) {
    let [left, right] = this.children(i);
    while (left < this._heap.length) {
      if (!this._has(right)) right = left;
      if (this.comparator(right, left)) [left, right] = [right, left];
      if (this.comparator(i, left)) break;
      this.swap(i, left);
      i = left;
      [left, right] = [2 * i + 1, 2 * i + 2];
    }
  }
  push(node) {
    this._heap.push(node);
    this.up(this._heap.length - 1);
  }
  pop() {
    if (this.size() === 0) return null;
    let res = this._heap[0];
    this.swap(0, this._heap.length - 1);
    this._heap.pop();
    this.down(0);
    return res;
  }
  remove(i) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this.swap(i, this._heap.length - 1);
    this._heap.pop();
    this.down(i);
    this.up(i);
    return res;
  }
  modify(i, val) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this._heap[i] = val;
    this.down(i);
    this.up(i);
    return res;
  }
  top() {
    if (this.size() === 0) return null;
    return this._heap[0];
  }
  size() {
    return this._heap.length;
  }
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

// PriorityQueue implementated using array based binary heap
// PriorityQueue methods
//  push(...values)
// 	peek()
//  pop()
//  size()
//  replace(value)

class PriorityQueue {

	constructor(comparator = (a, b) => a > b) {
		this.top = 0;
		this._heap = [];
		this._comparator = comparator;
	}
	size() {
		return this._heap.length;
	}
	isEmpty() {
		return this.size() == 0;
	}
	peek() {
		return this._heap[this.top];
	}
	push(...values) {
		values.forEach(value => {
				this._heap.push(value);
				this._siftUp();
				});
		return this.size();
	}
	pop() {
		const poppedValue = this.peek();
		const bottom = this.size() - 1;
		if (bottom > this.top) {
			this._swap(this.top, bottom);
		}
		this._heap.pop();
		this._siftDown();
		return poppedValue;
	}
	replace(value) {
		const replacedValue = this.peek();
		this._heap[this.top] = value;
		this._siftDown();
		return replacedValue;
	}
	_greater(i, j) {
		return this._comparator(this._heap[i], this._heap[j]);
	}
	_swap(i, j) {
		[this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
	}
	_siftUp() {
		const parent = i => ((i + 1) >>> 1) - 1;
		let node = this.size() - 1;
		while (node > this.top && this._greater(node, parent(node))) {
			this._swap(node, parent(node));
			node = parent(node);
		}
	}
	_siftDown() {
		const left = i => (i << 1) + 1;
		const right = i => (i + 1) << 1;
		let node = this.top;
		while (
				(left(node) < this.size() && this._greater(left(node), node)) ||
				(right(node) < this.size() && this._greater(right(node), node))
			  ) {
			let maxChild = (right(node) < this.size() && this._greater(right(node), left(node))) ? right(node) : left(node);
			this._swap(node, maxChild);
			node = maxChild;
		}
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	const n = rn();
	const a = rna();

	let health = 0, used = 0;
	const q = new PriorityQueue((a, b) => a > b);
	for (let i = 0; i < n; i++) {
		if (a[i] >= 0) {
			health += a[i];
			used++;
		} else {
			a[i] = -a[i];
			if (health - a[i] >= 0) {
				health -= a[i];
				q.push(a[i]);
				used++;
			} else {
				if (a[i] < q.peek()) {
					health += q.pop() - a[i];
					q.push(a[i]);
				}
			}
		}
	}

	console.log(used);
}

'use strict';

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(n, a) {
  let t = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] >= 0) {
      t = i;
      break;
    }
  }
  if (t === -1) return -1;
  const dp = new Array(n).fill(0);
  const heap = new Heap((a, b) => a - b);
  let sum = 0;
  for (let i = t; i < n; i++) {
    var _dp;
    if (a[i] < 0) heap.push(a[i]);
    sum += a[i];
    dp[i] = ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    while (sum < 0) {
      sum -= heap.pop();
      dp[i]--;
    }
  }
  let res = 0;
  for (let i = 0; i < n; i++) {
    res = Math.max(res, dp[i]);
  }
  return res;
}
class Heap {
  constructor(_comparator, arr) {
    _defineProperty(this, "_heap", []);
    this._comparator = _comparator;
    if (arr) {
      this._heap = [...arr];
      for (let i = arr.length >> 1; i; i--) this.down(i);
    }
  }
  swap(i, j) {
    [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
  }
  _has(i) {
    return Object.prototype.hasOwnProperty.call(this._heap, i);
  }
  comparator(i, j) {
    return this._comparator(this._heap[i], this._heap[j]) < 0;
  }
  parent(i) {
    return i - 1 >> 1;
  }
  children(i) {
    return [2 * i + 1, 2 * i + 2];
  }
  up(i) {
    let parent = this.parent(i);
    while (i > 0 && this.comparator(i, parent)) {
      this.swap(i, parent);
      [i, parent] = [parent, parent - 1 >> 1];
    }
  }
  down(i) {
    let [left, right] = this.children(i);
    while (left < this._heap.length) {
      if (!this._has(right)) right = left;
      if (this.comparator(right, left)) [left, right] = [right, left];
      if (this.comparator(i, left)) break;
      this.swap(i, left);
      i = left;
      [left, right] = [2 * i + 1, 2 * i + 2];
    }
  }
  push(node) {
    this._heap.push(node);
    this.up(this._heap.length - 1);
  }
  pop() {
    if (this.size() === 0) return null;
    let res = this._heap[0];
    this.swap(0, this._heap.length - 1);
    this._heap.pop();
    this.down(0);
    return res;
  }
  remove(i) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this.swap(i, this._heap.length - 1);
    this._heap.pop();
    this.down(i);
    this.up(i);
    return res;
  }
  modify(i, val) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this._heap[i] = val;
    this.down(i);
    this.up(i);
    return res;
  }
  top() {
    if (this.size() === 0) return null;
    return this._heap[0];
  }
  size() {
    return this._heap.length;
  }
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

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

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

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

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * 05/28/21 morning
 * https://codeforces.com/contest/1526/problem/C
 */

// let a, n;
let res, a, n;
const solve = (N, A) => {
    n = N;
    a = A;
    // pr(n, a);
    res = 0;
    // let res = mx(dfs(0, 0, 0, 'skip'), dfs(0, 0, 0, 'take'));
    dfs(0, 0, 0, 'skip');
    dfs(0, 0, 0, 'take');
    pr(res);
};

const dfs = (cnt, idx, cur, action) => {
    // pr(cnt, idx, cur, action);
    if (action == 'take') cur += a[idx];
    if (cur < 0) {
        // pr(cnt, idx, cur, action);
        res = mx(res, cnt - 1);
        return;
    }
    for (let i = idx + 1; i < n; i++) {
        dfs(cnt + 1, i, cur, 'skip');
        dfs(cnt + 1, i, cur, 'take');
    }
    res = mx(res, cnt);
    // return cnt;
};

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', () => {
        solve(input[0][0], input[1]);
    });
};

main()

// pr(2000 * 10 ** 9 < Number.MAX_SAFE_INTEGER);

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * 05/28/21 morning
 * https://codeforces.com/contest/1526/problem/C
 */

// let a, n;
let res, a, n;
const solve = (N, A) => {
    n = N;
    a = A;
    pr(n, a);
    res = 0;
    // let res = mx(dfs(0, 0, 0, 'skip'), dfs(0, 0, 0, 'take'));
    dfs(0, 0, 0, 'skip');
    dfs(0, 0, 0, 'take');
    pr(res);
};

const dfs = (cnt, idx, cur, action) => {
    // pr(cnt, idx, cur, action);
    if (action == 'take') cur += a[idx];
    if (cur < 0) {
        // pr(cnt, idx, cur, action);
        res = mx(res, cnt - 1);
        return;
    }
    for (let i = idx + 1; i < n; i++) {
        dfs(cnt + 1, i, cur, 'skip');
        dfs(cnt + 1, i, cur, 'take');
    }
    res = mx(res, cnt);
    // return cnt;
};

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', () => {
        solve(input[0][0], input[1]);
    });
};

main()

// pr(2000 * 10 ** 9 < Number.MAX_SAFE_INTEGER);


const readline = require('readline');

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

let input = [],
    numTestCases;

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

    if (input.length === (2 * (+input[0]) + 1)) {
        rl.close();
        numTestCases = +input[0];
        input.shift();
        main();
    }
});

function main() {
    for (let i = 0; i < numTestCases * 2; ++i) {
        let currCaseConsts = input[i].split(' '),
            currCaseString = input[++i],
            n = +currCaseConsts[0],
            a = +currCaseConsts[1],
            b = +currCaseConsts[2];

        console.log(getMaxPoints(currCaseString, n, a, b));
    }
}

function getMaxPoints(currCaseString, n, a, b) {
    let numConsecGroups = 1;

    for (let i = 1; i < n; ++i) {
        if (currCaseString.charAt(i - 1) !== currCaseString.charAt(i)) {
            ++numConsecGroups;
        }
    }

    return (b >= 0) ? n * (a + b) : (n * a) + ((Math.floor(numConsecGroups/2) + 1) * b);
}

var x = parseInt(readline());

for(i = 0; i < x; i++)
{
    var n = readline().split(" ");
    var a = parseInt(n[1]);
    var b = parseInt(n[2]);
    n = parseInt(n[0]);
    var string = readline();

    if(b > 0) print(n * (a + b));
    else if(b === 0) print(n * a);
    else if(n === 1) print(a + b);
    else {
        var substring = [], sum = 0;
        for(j = 0; j < n; j++) {
            var k = j + 1;
            while(string[k] === string[j]) { k++; }
            substring[substring.length] = k - j;
            j = k - 1;
        }
        while(substring !== []) {
            if(substring.length === 1) {
                sum += a * substring[0] + b;
                break;
            }
            sum += a * substring[substring.length - 2] + b;
            if(substring.length === 2) {
                sum += a * substring[1] + b;
                break;
            }
            else {
                substring[substring.length - 3] += substring[substring.length - 1];
                substring = substring.slice(0, substring.length - 2);
            }
        }
        print(sum);
    }
}

"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, a, b] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split("")
      .map((cur) => parseInt(cur));
    if (b >= 0) {
      console.log(a * n + b * n);
      continue;
    } else {
      let str = [];
      str.push(arr[0]);
      for (let i = 1; i < n; i++) {
        if (str[str.length - 1] !== arr[i]) str.push(arr[i]);
      }
      if (str.length <= 2) console.log(a * n + b * str.length);
      else {
        let k = Math.ceil((str.length + 1) / 2);
        console.log(a * n + b * k);
      }
    }
  }
};
solve();

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

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

stdin.addListener('end', () => {
          content = content.split('\n');
          content.shift();
          content = content.map((string) => string.substring(0, string.length - 1));
          content.pop();
          for (let i = 0; i < content.length; i += 2) {
                    const [n, a, b] = content[i].split(' ').map(string => parseInt(string));
                    console.log(maximumCostDeletion(a, b, content[i + 1]));
          }
})

const maximumCostDeletion = (a, b, str) => {
          let bContribution = str.length;
          if (b < 0) {
                    let changes = 1;
                    bContribution = 1;
                   for (let i = 1; i < str.length; i++) {
                             if (str[i] !== str[i - 1]) {
                                   changes++;
                             }
                   }
                   bContribution += Math.floor(changes / 2);
          }
          return (a * str.length) + (b * bContribution);
}

"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, a, b] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split("")
      .map((cur) => parseInt(cur));
    if (b >= 0) {
      console.log((a + b) * n);
      continue;
    } else {
      let str = [];
      str.push(arr[0]);
      for (let i = 1; i < n; i++) {
        if (str[str.length - 1] !== arr[i]) str.push(arr[i]);
      }
      if (str.length <= 2) console.log(a * n + b * str.length);
      else {
        let k = Math.floor((str.length + 1) / 2);
        console.log(a * n + b * k);
      }
    }
  }
};
solve();

"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, a, b] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split("")
      .map((cur) => parseInt(cur));
    if (a + b >= 0) {
      console.log((a + b) * n);
      continue;
    } else {
      let cnt1 = 0,
        cnt2 = 0;
      for (let i = 0; i < n; i++) {
        if (arr[i] === 0) cnt1++;
        else cnt2++;
      }
      let i = 0;
      let res = a * cnt2 + b;
      while (i < n) {
        if (arr[i] === 1) {
          let s = i;
          while (i < n) {
            if (arr[i] === 1) {
              if (i - s - 1 > 0) {
                res += a * (i - s - 1) + b;
                cnt1 -= i - s - 1;
              }
              s = i;
            }
            i++;
          }
        }
        i++;
      }
      if (cnt1 !== 0) res += a * cnt1 + b;
      console.log(res);
    }
  }
};
solve();

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

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

stdin.addListener('end', () => {
          content = content.split('\n');
          content.shift();
          content = content.map((string) => string.substring(0, string.length - 1));
          content.pop();
          for (let i = 0; i < content.length; i += 2) {
                    const [n, a, b] = content[i].split(' ').map(string => parseInt(string));
                    console.log(maximumCostDeletion(a, b, content[i + 1]));
          }
})

const maximumCostDeletion = (a, b, str) => {
          let bContribution = str.length;
          if (b < 0) {
                    const startingString = str[0];
                    bContribution = 1;
                   for (let i = 1; i < str.length; i++) {
                             if (str[i] !== str[i - 1] && str[i] === startingString) {
                                   bContribution++;
                             }
                   }
          }
          return (a * str.length) + (b * bContribution);
}

const readline = require('readline');

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

let input = [],
    numTestCases;

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

    if (input.length === (2 * (+input[0]) + 1)) {
        rl.close();
        numTestCases = +input[0];
        input.shift();
        main();
    }
});

function main() {
    for (let i = 0; i < numTestCases; ++i) {
        let currCaseConsts = input[i].split(' '),
            currCaseString = input[++i],
            n = +currCaseConsts[0],
            a = +currCaseConsts[1],
            b = +currCaseConsts[2];

        console.log(getMaxPoints(currCaseString, n, a, b));
    }
}

function getMaxPoints(currCaseString, n, a, b) {
    let numConsecGroups = 1;

    for (let i = 1; i < n; ++i) {
        if (currCaseString.charAt(i - 1) !== currCaseString.charAt(i)) {
            ++numConsecGroups;
        }
    }

    return (b >= 0) ? n * (a + b) : (n * a) + ((Math.floor(numConsecGroups/2) + 1) * b);
}