Bertown is a city with $$$n$$$ buildings in a straight line.The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length $$$n$$$, where the $$$i$$$-th character is "1" if there is a mine under the building number $$$i$$$ and "0" otherwise.Bertown's best sapper knows how to activate mines so that the buildings above them are not damaged. When a mine under the building numbered $$$x$$$ is activated, it explodes and activates two adjacent mines under the buildings numbered $$$x-1$$$ and $$$x+1$$$ (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment. For manual activation of one mine, the sapper takes $$$a$$$ coins. He can repeat this operation as many times as you want.Also, a sapper can place a mine under a building if it wasn't there. For such an operation, he takes $$$b$$$ coins. He can also repeat this operation as many times as you want.The sapper can carry out operations in any order.You want to blow up all the mines in the city to make it safe. Find the minimum number of coins that the sapper will have to pay so that after his actions there are no mines left in the city.

The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case begins with a line containing two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 1000$$$) — the cost of activating and placing one mine, respectively. The next line contains a map of mines in the city — a string consisting of zeros and ones. The sum of the string lengths for all test cases does not exceed $$$10^5$$$.

For each test case, output one integer — the minimum number of coins that the sapper will have to pay.

NoteIn the second test case, if we place a mine under the fourth building and then activate it, then all mines on the field are activated. The cost of such operations is six, $$$b=1$$$ coin for placing a mine and $$$a=5$$$ coins for activating.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [a, b] = readLine().split(" ").map(Number);
    const str = readLine();
    let [ans, seen1, lastIndex] = [0, false, -1];

    for (let i = 0; i < str.length; i++) {
      if (!seen1 && str[i] === "1") {
        seen1 = true;
        lastIndex = i;
        ans += a;
        continue;
      }
      if (str[i] === "1" && str[i - 1] === "1") lastIndex = i;
      if (seen1 && str[i] === "1" && str[i - 1] === "0") {
        ans += Math.min(a, (i - lastIndex - 1) * b);
        lastIndex = i;
      }
    }
    console.log(ans);
  }
}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;i<t;++i){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const i=n(r(747));let o="",s=[],u=0,l="";const a="local"===process.argv[2],h=t=>{if(a){if(s=i.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),i.default.writeFileSync("output.txt",l),console.log(l),i.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{s=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function p(){return s[u++]}function f(){return p().split(" ").map((t=>parseFloat(t)))}function c(){return p().split("")}e.default={runMain:h,runEachTest:t=>{h((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:p,nextNumbers:f,nextBigNumbers:function(){return p().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(f());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=f();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){a&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const i=n(r(312));i.default.runEachTest((function(){let[t,e]=i.default.nextNumbers(),r=i.default.nextCharacters(),n=0,o=!1,s=0;for(let u=0;u<r.length;++u)o||"1"!=r[u]||0!=u&&"0"!=r[u-1]?("1"==r[u]&&"1"==r[u-1]&&(s=u),o&&"1"==r[u]&&"0"==r[u-1]&&(n+=Math.min(t,e*(u-s-1)),i.default.debug(e*(u-s-1)),s=u)):(n+=t,o=!0,s=u);i.default.puts(n)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [a, b] = io.nextNumbers()
//
//   let s = io.nextCharacters()
//
//   let best = 0
//
//   let hasMined = false
//
//   let lastMineIndex = 0
//
//   for (let i = 0; i < s.length; ++i) {
//     if (!hasMined && s[i] == "1" && (i == 0 || s[i - 1] == "0")) {
//       best += a
//       hasMined = true
//       lastMineIndex = i
//       continue
//     }
//
//     if (s[i] == "1" && s[i - 1] == "1") {
//       lastMineIndex = i
//     }
//
//     if (hasMined && s[i] == "1" && s[i - 1] == "0") {
//       best += Math.min(a, b * (i - lastMineIndex - 1))
//       io.debug(b * (i - lastMineIndex - 1))
//       lastMineIndex = i
//     }
//   }
//
//   io.puts(best)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

let input = ''

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

process.stdin.on('end', () => {
  const lines = input.trim().split('\n')
  let curLine = 0
  const T = parseInt(lines[curLine++])
  for (let t = 0; t < T; t++) {
    const [a, b] = parseIntArray(lines[curLine++])
    const spaces = []
    let count = 0
    let last = '0'
    let length = 0
    lines[curLine++].split('').forEach((c) => {
      if (c === '1') {
        if (length > 0 && count > 0) {
          spaces.push(length)
        }
        if (last === '0') {
          count++
        }
        length = 0
        last = '1'
      } else {
        length++
        last = '0'
      }
    })
    let ans = 0
    spaces.sort((x, y) => x - y).forEach((len) => {
      if (b * len < a) {
        ans += b * len
        count--
      }
    })

    console.log(ans + a * count)
  }
})

const parseIntArray = (line) => line.split(' ').map((x) => parseInt(x))

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

let inputString = '';
let currentLine = 0;

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

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

    B();
});

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

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

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

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let x = n;
        let res = [4*n];
        let num = 4*n;
        n -= 1;
        let i = 3;
        let f = 2;
        while(n > 0){
                num -= 2;
                let flag = false;
                for(let j = res.length-1; j >= 0; j--){
                    if(res[j] % num === 0){
                        flag = true;
                        break;
                    }
                }
                if(!flag){
                    res.push(num);
                    n--;
                }
        }

        console.log(res.join(' '));
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [a,b] = ti(readline().split(' '));
        let s = readline().split('');
        //console.log(s.length);
        let x = [];
        let i = 0;
        while(i < s.length && s[i] !== '1'){
            i++;
        }

        while(i < s.length){
            if(s[i] === '1')
                x.push(a);
            while(i < s.length && s[i] === '1'){
                i++;
            }

            if(i < s.length && s[i] === '0'){
                x.push(s[i]);
            }
            i++;
        }

        i = 0;
        let sum = x.length !== 0 ? a : 0;
        while(i < x.length){
            if(pi(x[i]) === a){
                let count = 0;
                i++;
                while(i < x.length && pi(x[i]) === 0){
                    count += b;
                    i++;
                }

                if(i < x.length){
                    sum = Math.min(sum+a, sum+count);
                }
            }
        }

        console.log(sum);
    }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [a, b] = readLine().split(" ").map(Number);
    const str = readLine();
    let cost1 = 0;
    for (let i = 0; i < str.length; i++) {
      if (str[i] === "1") {
        cost1 += a;
        while (str[i] === "1") i++;
      }
    }
    const lastIndex = str.lastIndexOf("1");
    let [seen, count0] = [false, 0];
    for (let i = 0; i <= lastIndex; i++) {
      if (str[i] === "1" && !seen) seen = true;
      if (seen && str[i] === "0") count0++;
    }
    const cost2 = b * count0 + a;

    console.log(Math.min(cost1, cost2));
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [a, b] = readLine().split(" ").map(Number);
    const str = readLine();
    let [ans, seen1, lastIndex] = [0, false, -1];

    for (let i = 0; i < str.length; i++) {
      if (!seen1 && str[i] === "1") {
        seen1 = true;
        lastIndex = i;
        ans += a;
        continue;
      }
      if (str[i] === "1" && str[i - 1] === "1") lastIndex = i;
      if (seen1 && str[i] === "1" && str[i - 1] === "0") {
        ans += Math.min(a, (i - lastIndex - 1) * b);
      }
    }
    console.log(ans);
  }
}


RedDreamer has an array $$$a$$$ consisting of $$$n$$$ non-negative integers, and an unlucky integer $$$T$$$.Let's denote the misfortune of array $$$b$$$ having length $$$m$$$ as $$$f(b)$$$ — the number of pairs of integers $$$(i, j)$$$ such that $$$1 \le i < j \le m$$$ and $$$b_i + b_j = T$$$. RedDreamer has to paint each element of $$$a$$$ into one of two colors, white and black (for each element, the color is chosen independently), and then create two arrays $$$c$$$ and $$$d$$$ so that all white elements belong to $$$c$$$, and all black elements belong to $$$d$$$ (it is possible that one of these two arrays becomes empty). RedDreamer wants to paint the elements in such a way that $$$f(c) + f(d)$$$ is minimum possible.For example:  if $$$n = 6$$$, $$$T = 7$$$ and $$$a = [1, 2, 3, 4, 5, 6]$$$, it is possible to paint the $$$1$$$-st, the $$$4$$$-th and the $$$5$$$-th elements white, and all other elements black. So $$$c = [1, 4, 5]$$$, $$$d = [2, 3, 6]$$$, and $$$f(c) + f(d) = 0 + 0 = 0$$$;  if $$$n = 3$$$, $$$T = 6$$$ and $$$a = [3, 3, 3]$$$, it is possible to paint the $$$1$$$-st element white, and all other elements black. So $$$c = [3]$$$, $$$d = [3, 3]$$$, and $$$f(c) + f(d) = 0 + 1 = 1$$$. Help RedDreamer to paint the array optimally!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le T \le 10^9$$$) — the number of elements in the array and the unlucky integer, respectively.  The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the elements of the array.  The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print $$$n$$$ integers: $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ (each $$$p_i$$$ is either $$$0$$$ or $$$1$$$) denoting the colors. If $$$p_i$$$ is $$$0$$$, then $$$a_i$$$ is white and belongs to the array $$$c$$$, otherwise it is black and belongs to the array $$$d$$$. If there are multiple answers that minimize the value of $$$f(c) + f(d)$$$, print any of them.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [len, target] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const result = [];
    let flag = true;

    for (let i = 0; i < len; i++) {
      const value = arr[i];
      const mid = Math.floor(target / 2);

      if (2 * value === target) {
        result.push(+flag);
        flag = !flag;
      } else if (value <= mid) {
        result.push(0);
      } else {
        result.push(1);
      }
    }

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

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

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var N = one[0];
    var T = one[1];
    var list = nextIntArray();
    var L = {};
    var R = {};
    for(var j = 0; j < N; j++){
      if(L[T - list[j]] == null){
        if(L[list[j]] == null){
          L[list[j]] = 0;
        }
        L[list[j]]++;
        list[j] = 1;
      }else if(R[T - list[j]] == null){
        if(R[list[j]] == null){
          R[list[j]] = 0;
        }
        R[list[j]]++;
        list[j] = 0;
      }else{
        if(L[T - list[j]] > R[T - list[j]]){
          R[list[j]]++;
          list[j] = 1;
        }else{
          L[list[j]]++;
          list[j] = 0;
        }
      }
    }
    output[i] = myconv(list, 8);
  }
  myout(myconv(output, 9));
}

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

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

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

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

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

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

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

let inputString = '';
let currentLine = 0;

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

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

    B();
});

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

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

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

    return a;
}

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

        a.sort((a,b) => a-b);
        let count = 0;
        for(let i = 1; i < n; i++){
            if(a[i] < k)
                count += (k-a[i]);
        }
        console.log(Math.floor((count)/a[0]));
    }
}

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

        let map = new Array(1000000008);
        let color = new Array(1000000008);
        for(let i = 0; i < n; i++){
            if(i === 0){
                map[a[i]] = 1;
            }else{
                let x = k-a[i];
                if(color[a[i]] !== undefined){
                    continue;
                }

                if(x >= 0 && map[x] !== undefined){
                    if(color[x] !== undefined){
                        color[a[i]] = color[x] === 1 ? 0 : 1;
                    }else{
                        color[x] = 1;
                        color[a[i]] = 0;
                    }
                }

                map[a[i]] = 1;
            }
        }

        let res = new Array(n);
        for(let i = 0; i < n; i++){
            if(color[a[i]] === undefined)
                res[i] = 0;
            else
                res[i] = color[a[i]];

            if(a[i] === k / 2){
                if(color[a[i]] === 1)
                    color[a[i]] = 0;
                else
                    color[a[i]] = 1;
            }
        }

        for(let i of res)
            console.log(i);
    }
}

'use strict';

var readline = require('readline');

function tTwoLinesPerStdin() {
  return new Promise(resolve => {
    const stdin = readline.createInterface(process.stdin);
    let t;
    let prevLine;
    let output = [];
    stdin.on('line', line => {
      if (typeof t !== 'number') {
        t = +line;
      } else {
        if (prevLine) {
          output.push([prevLine, line]);
          prevLine = undefined;

          if (output.length === t) {
            resolve(output);
            stdin.close();
          }
        } else {
          prevLine = line;
        }
      }
    });
  });
}

function solve(T, arr) {
  const mid = T / 2;
  let midLeft = true;
  const output = [];

  for (let i = 0; i < arr.length; i++) {
    const element = arr[i];

    if (element === mid) {
      output.push(midLeft ? 1 : 0);
      midLeft = !midLeft;
    } else {
      output.push(element < mid ? 1 : 0);
    }
  }

  return output;
}

async function main() {
  const input = await tTwoLinesPerStdin();

  for (let t = 0; t < input.length; t++) {
    const [line1, line2] = input[t];
    const [T] = line1.split(' ').map(Number).slice(1);
    const a = line2.split(' ').map(Number);
    const answer = solve(T, a);
    console.log(answer.join(' '));
  }
}

main().then();

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [len, target] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const restricted = {};
    const result = [];

    for (let i = 0; i < len; i++) {
      const value = arr[i];
      const otherValue = Math.abs(target - value);
      if (!restricted[value]) {
        result.push(0);
        restricted[otherValue] = true;
      } else {
        result.push(1);
        restricted[value] = false;
      }
    }

    console.log(result.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++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [len, target] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const result = [];
    let flag = true;

    for (let i = 0; i < len; i++) {
      const value = arr[i];
      const mid = Math.floor(target / 2);

      if (2 * value === target) {
        result.push(+flag);
        flag = !flag;
      } else if (value < mid) {
        result.push(0);
      } else {
        result.push(1);
      }
    }

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

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

let inputString = '';
let currentLine = 0;

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

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

    B();
});

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

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

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

    return a;
}

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

        a.sort((a,b) => a-b);
        let count = 0;
        for(let i = 1; i < n; i++){
            if(a[i] < k)
                count += (k-a[i]);
        }
        console.log(Math.floor((count)/a[0]));
    }
}

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

        let map = new Array(1000000008);

        let res = new Array(n);
        for(let i = 0; i < n; i++){
            if(i === 0){
                map[a[i]] = i;
            }else{
                let x = k-a[i];
                if(x >= 0 && map[x] !== undefined){
                    if(res[map[x]] === undefined){
                        res[i] = 0;
                        res[map[x]] = 1;
                    }
                    else{
                        res[i] = res[map[x]] === 0 ? 1 : 0;
                    }
                }else{
                    map[a[i]] = i;
                }
            }
        }

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

        for(let i of res)
            console.log(i);
    }
}

'use strict';

var readline = require('readline');

function tTwoLinesPerStdin() {
  return new Promise(resolve => {
    const stdin = readline.createInterface(process.stdin);
    let t;
    let prevLine;
    let output = [];
    stdin.on('line', line => {
      if (typeof t !== 'number') {
        t = +line;
      } else {
        if (prevLine) {
          output.push([prevLine, line]);
          prevLine = undefined;

          if (output.length === t) {
            resolve(output);
            stdin.close();
          }
        } else {
          prevLine = line;
        }
      }
    });
  });
}

function solve(T, arr) {
  const mid = T / 2;
  let midDone = false;
  const output = [];

  for (let i = 0; i < arr.length; i++) {
    const element = arr[i];

    if (element === mid) {
      output.push(midDone ? 1 : 0);
      midDone = true;
    } else {
      output.push(element < mid ? 1 : 0);
    }
  }

  return output;
}

async function main() {
  const input = await tTwoLinesPerStdin();

  for (let t = 0; t < input.length; t++) {
    const [line1, line2] = input[t];
    const [T] = line1.split(' ').map(Number).slice(1);
    const a = line2.split(' ').map(Number);
    const answer = solve(T, a);
    console.log(answer.join(' '));
  }
}

main().then();


The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the king, whose name was Victorious Vasily Pupkin, was always called by the berlanders VVP.In Berland over its long history many dynasties of kings replaced each other, but they were all united by common traditions. Thus, according to one Berland traditions, to maintain stability in the country, the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor). Berlanders appreciate stability, so this tradition has never been broken. Also Berlanders like perfection, so another tradition requires that the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king). This tradition, of course, has also been always observed.The name of a dynasty is formed by very simple rules: we take all the short names of the kings in the order in which they ruled, and write them in one line. Thus, a dynasty of kings "ab" and "ba" is called "abba", and the dynasty, which had only the king "abca", is called "abca".Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland.Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B.

The first line contains integer n (1 ≤ n ≤ 5·105) — the number of names in Vasya's list. Next n lines contain n abbreviated names, one per line. An abbreviated name is a non-empty sequence of lowercase Latin letters. Its length does not exceed 10 characters.

Print a single number — length of the sought dynasty's name in letters. If Vasya's list is wrong and no dynasty can be found there, print a single number 0.

NoteIn the first sample two dynasties can exist: the one called "abcca" (with the first and second kings) and the one called "abccba" (with the first and third kings). In the second sample there aren't acceptable dynasties.The only dynasty in the third sample consists of one king, his name is "c".

var input = readline().split(' ').map(Number), n = input[0];
var men = [];
while (n--) {
    men.push(readline());
}

var d = [];
for (var i = 0; i < 27; i++) {
    d[i] = [];
    for (var j = 0; j < 27; j++) d[i][j] = 0;
}

var codeA = 'a'.charCodeAt();
for (var i = 0; i < men.length; i++) {
    var a = men[i];
    var first = a[0].charCodeAt() - codeA;
    var last = a[a.length - 1].charCodeAt() - codeA;
    for (var j = 0; j < 27; j++) {
		if (d[j][first] > 0 || j == first)
			d[j][last] = Math.max(d[j][last], d[j][first] + a.length);
    }

}

var res = 0;
for (var i = 0; i < 27; i++) {
    res = Math.max(res, d[i][i]);
}

write(res);

var input = readline().split(' ').map(Number), n = input[0];

var men = [];
var d = [];
while (n--) {
    men.push(readline());
    d[n] = {start: '', fin: 0, current: 0};
}

for (var i = 0; i < men.length; i++) {
    var a = men[i];
    d[i].start = a[0];
	d[i].current = a.length;
    if (a[0] == a[a.length - 1]) {
        d[i].fin = a.length;
    }

    for (var j = 0; j < i; j++) {
        var pr = men[j];
        if (pr[pr.length - 1] == a[0]) {

            d[i].current = Math.max(d[i].current, d[j].current + a.length);
            if (d[j].start.indexOf(a[a.length - 1]) >= 0) {
                if (d[i].fin < d[j].current + a.length) {
                    d[i].start = d[j].start;
                    d[i].fin = d[j].current + a.length;
                } else if (d[i].fin == d[j].current + a.length) {
                    d[i].start += d[j].start;
                }
            }

        }
    }
}

var res = 0;
for (var i = 0; i < men.length; i++) {
    res = Math.max(res, d[i].fin);
}

write(res);

var input = readline().split(' ').map(Number), n = input[0];
var men = [];
while (n--) {
    men.push(readline());
}

var d = [];
for (var i = 0; i < 27; i++) {
    d[i] = [];
    for (var j = 0; j < 27; j++) d[i][j] = 0;
}

var codeA = 'a'.charCodeAt();
for (var i = 0; i < men.length; i++) {
    var a = men[i];
    var first = a[0].charCodeAt() - codeA;
    var last = a[a.length - 1].charCodeAt() - codeA;
	d[first][last] = Math.max(d[first][last], a.length);
    for (var j = 0; j < 27; j++) {
		if (d[j][first] > 0)
			d[j][last] = Math.max(d[j][last], d[j][first] + a.length);
    }
}

var res = 0;
for (var i = 0; i < 27; i++) {
    res = Math.max(res, d[i][i]);
}

write(res);

var input = readline().split(' ').map(Number), n = input[0];
var men = [];
while (n--) {
    men.push(readline());
}

var d = [];
for (var i = 0; i < 27; i++) {
    d[i] = [];
    for (var j = 0; j < 27; j++) d[i][j] = 0;
}

var codeA = 'a'.charCodeAt();
for (var i = 0; i < men.length; i++) {
    var a = men[i];
    var first = a[0].charCodeAt() - codeA;
    var last = a[a.length - 1].charCodeAt() - codeA;
	d[first][last] = Math.max(d[first][last], d[first][last] + a.length);
    for (var j = 0; j < 27; j++) {
		if (d[j][first] > 0 && j != first)
			d[j][last] = Math.max(d[j][last], d[j][first] + a.length);
    }

}

var res = 0;
for (var i = 0; i < 27; i++) {
    res = Math.max(res, d[i][i]);
}

write(res);


Marian is at a casino. The game at the casino works like this.Before each round, the player selects a number between $$$1$$$ and $$$10^9$$$. After that, a dice with $$$10^9$$$ faces is rolled so that a random number between $$$1$$$ and $$$10^9$$$ appears. If the player guesses the number correctly their total money is doubled, else their total money is halved. Marian predicted the future and knows all the numbers $$$x_1, x_2, \dots, x_n$$$ that the dice will show in the next $$$n$$$ rounds. He will pick three integers $$$a$$$, $$$l$$$ and $$$r$$$ ($$$l \leq r$$$). He will play $$$r-l+1$$$ rounds (rounds between $$$l$$$ and $$$r$$$ inclusive). In each of these rounds, he will guess the same number $$$a$$$. At the start (before the round $$$l$$$) he has $$$1$$$ dollar.Marian asks you to determine the integers $$$a$$$, $$$l$$$ and $$$r$$$ ($$$1 \leq a \leq 10^9$$$, $$$1 \leq l \leq r \leq n$$$) such that he makes the most money at the end.Note that during halving and multiplying there is no rounding and there are no precision errors. So, for example during a game, Marian could have money equal to $$$\dfrac{1}{1024}$$$, $$$\dfrac{1}{128}$$$, $$$\dfrac{1}{2}$$$, $$$1$$$, $$$2$$$, $$$4$$$, etc. (any value of $$$2^t$$$, where $$$t$$$ is an integer of any sign).

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2\cdot 10^5$$$) — the number of rounds. The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^9$$$), where $$$x_i$$$ is the number that will fall on the dice in the $$$i$$$-th round. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, output three integers $$$a$$$, $$$l$$$, and $$$r$$$ such that Marian makes the most amount of money gambling with his strategy. If there are multiple answers, you may output any of them.

NoteFor the first test case, the best choice is $$$a=4$$$, $$$l=1$$$, $$$r=5$$$, and the game would go as follows.   Marian starts with one dollar.  After the first round, he ends up with $$$2$$$ dollars because the numbers coincide with the chosen one.  After the second round, he ends up with $$$4$$$ dollars because the numbers coincide again.  After the third round, he ends up with $$$2$$$ dollars because he guesses $$$4$$$ even though $$$3$$$ is the correct choice.  After the fourth round, he ends up with $$$4$$$ dollars again.  In the final round, he ends up $$$8$$$ dollars because he again guessed correctly. There are many possible answers for the second test case, but it can be proven that Marian will not end up with more than $$$2$$$ dollars, so any choice with $$$l = r$$$ with the appropriate $$$a$$$ is acceptable.

var numTestCases = parseInt(readline());
var diceValueMap = {};
var maxDiceValueMap = {};
var maximumScore = 0;
var maximumScoreDice = 0;
var maximumScoreInd = 0;

for (var i = 0; i < numTestCases; i++) {
    var numRounds = parseInt(readline());
    var inpFirstLine = readline().split(" ");
    var diceValueArray = inpFirstLine.map(element => parseInt(element));
    diceValueMap = {};
    maxDiceValueMap = {};
    maximumScore = 1;
    maximumScoreDice = diceValueArray[0];
    maximumScoreInd = 0;
    for (var ind = 0; ind < numRounds; ind++) {
        updateDiceValueMap(ind, diceValueArray[ind]);
    }

    for (var key in maxDiceValueMap) {
        if (maxDiceValueMap[key].cs >= maximumScore) {
            maximumScore = maxDiceValueMap[key].cs;
            maximumScoreInd = maxDiceValueMap[key].ind;
            maximumScoreDice = key;
        }
    }
    var currentScoreValue = 0;
    var diceInd = maximumScoreInd;
    for (; diceInd > 0; diceInd--) {
        if (diceValueArray[diceInd] == maximumScoreDice) {
            currentScoreValue++;
        } else {
            currentScoreValue--;
        }

        if (currentScoreValue >= maximumScore) {
            break;
        }
    }
    print(maximumScoreDice, (diceInd + 1), (maximumScoreInd + 1));
}

function updateDiceValueMap(index, diceValue) {
    var cumulativeScore = 1;
    if (diceValueMap.hasOwnProperty(diceValue)) {
        cumulativeScore = Math.max(1, diceValueMap[diceValue].cs - (index - (diceValueMap[diceValue].ind + 2)));
    } else {
        cumulativeScore = 1;
        diceValueMap[diceValue] = {};
    }

    diceValueMap[diceValue].ind = index;
    diceValueMap[diceValue].cs = cumulativeScore;

    updateMaxDiceValueMap(diceValue);
}

function updateMaxDiceValueMap(diceValue) {
    if (!maxDiceValueMap.hasOwnProperty(diceValue)) {
        maxDiceValueMap[diceValue] = {};
        maxDiceValueMap[diceValue].ind = diceValueMap[diceValue].ind;
        maxDiceValueMap[diceValue].cs = diceValueMap[diceValue].cs;
    } else {
        if (diceValueMap[diceValue].cs >= maxDiceValueMap[diceValue].cs) {
            maxDiceValueMap[diceValue].ind = diceValueMap[diceValue].ind;
            maxDiceValueMap[diceValue].cs = diceValueMap[diceValue].cs;
        }
    }
}

'use strict';

function solve(n, a) {
  const map = new Map();
  for (let [i, num] of a.entries()) {
    if (!map.has(num)) map.set(num, []);
    map.get(num).push(i);
  }
  let res = [1, a[0], 0, 0];
  for (let [num, list] of map) {
    const sum = [];
    let r = 0;
    sum[0] = 1;
    for (let i = 1; i < list.length; i++) {
      const cur = sum[i - 1] - (list[i] - list[i - 1] - 1) + 1;
      sum[i] = Math.max(1, cur);
      if (sum[i] > sum[r]) r = i;
    }
    let l = r;
    while (sum[l] !== 1) l--;
    if (res[0] < sum[r]) {
      res = [sum[r], num, list[l], list[r]];
    }
  }
  const [, x, y, z] = res;
  return `${x} ${y + 1} ${z + 1}`;
}

async function main(read) {
  try {
    let t = Number(await read());
    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';

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

class INPUT {
	constructor() {
		this.input = '';
		this.curLine = 0;
	}

	append(str) {
		this.input += str;
	}

	prepare() {
		this.input = this.input.split('\n').map((str) => str.trim());
	}

	readline() {
		return this.input[this.curLine++];
	}

	readInts() {
		return this.readline()
			.split(' ')
			.map((x) => parseInt(x, 10));
	}
}

const input = new INPUT();

process.stdin.on('data', (str) => {
	input.append(str);
});

process.stdin.on('end', () => {
	input.prepare();
	main();
});

function solve() {
	const [n] = input.readInts();
	const a = input.readInts();
	const pos = {};

	for (let i = 0; i < n; i++) {
		if (!pos[a[i]]) {
			pos[a[i]] = [];
		}

		pos[a[i]].push(i);
	}

	let ans = -1;
	let best = undefined;

	for (const x in pos) {
		const ind = pos[x];

		let bal = 0;
		let mn = 0;
		let mnPos = 0;
		let prv = -1;

		for (let i = 0; i < ind.length; i++) {
			bal -= ind[i] - prv - 1;

			if (bal < mn) {
				mn = bal;
				mnPos = ind[i];
			}

			bal++;

			if (bal - mn > ans) {
				ans = bal - mn;
				best = [x, mnPos + 1, ind[i] + 1];
			}

			prv = ind[i];
		}
	}

	console.log(best[0], best[1], best[2]);
}

function main() {
	let [T] = input.readInts();

	while (T--) {
		solve();
	}
}

const readline = require('readline')

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

function solve(n, arr) {
    const map = arr.reduce((o, x, i) => {
        o[x] = o[x] || []
        o[x].push(i)
        return o
    }, {})
    let max = -Infinity, output
    for (let k in map) {
        k = +k
    // console.log(k, map[k])
        const temp = []
        let c = 1
        for (let i = 1; i < map[k].length; i++) {
            const j = map[k][i]
            const p = map[k][i - 1]
            if (j === p + 1) {
                c++
            } else {
                temp.push(c, -(j - p - 1))
                c = 1
            }
        }
        temp.push(c)
        const [ans, l, r] = lcs(temp)
    // console.log(k, temp, ans)
        if (ans > max) {
            max = ans
            let sum = 0
            output = [k, map[k][0], map[k][0]]
            for (let i = 0; i < temp.length; i++) {
                if (l === i) output[1] += sum + 1
                sum += Math.abs(temp[i])
                if (r === i) output[2] += sum
            }
        }
    }
    return output.join(' ')
}
function lcs(arr) {
    let p = 0, l, r
    let ans = -Infinity, range
    for (let i = 0; i < arr.length; i++) {
        if (p > 0) {
            p += arr[i]
            r = i
        } else {
            p = arr[i]
            l = r = i
        }
        // console.log(p)
        if (p > ans) {
            ans = p
            range = [l, r]
        }
    }
    return [ans, ...range]
}

var numTestCases = parseInt(readline());
var diceValueMap = {};
var maximumScore = 0;
var maximumScoreDice = 0;
var maximumScoreInd = 0;

for (var i = 0; i < numTestCases; i++) {
    var numRounds = parseInt(readline());
    var inpFirstLine = readline().split(" ");
    var diceValueArray = inpFirstLine.map(element => parseInt(element));
    diceValueMap = {};
    maximumScore = 1;
    maximumScoreDice = diceValueArray[0];
    maximumScoreInd = 0;
    for (var ind = 0; ind < numRounds; ind++) {
        updateDiceValueMap(ind, diceValueArray[ind]);
    }

    for (var key in diceValueMap) {
        if (diceValueMap[key].cs >= maximumScore) {
            maximumScore = diceValueMap[key].cs;
            maximumScoreInd = diceValueMap[key].ind;
            maximumScoreDice = key;
        }
    }
    var currentScoreValue = 0;
    var diceInd = maximumScoreInd;
    for (; diceInd > 0; diceInd--) {
        if (diceValueArray[diceInd] == maximumScoreDice) {
            currentScoreValue++;
        } else {
            currentScoreValue--;
        }

        if (currentScoreValue >= maximumScore) {
            break;
        }
    }

    print(maximumScoreDice, (diceInd + 1), (maximumScoreInd + 1));
}

function updateDiceValueMap(index, diceValue) {
    var cumulativeScore = 1;
    if (diceValueMap.hasOwnProperty(diceValue)) {
        cumulativeScore = Math.max(1, diceValueMap[diceValue].cs - (index - (diceValueMap[diceValue].ind + 2)));
    } else {
        cumulativeScore = 1;
        diceValueMap[diceValue] = {};
    }

    diceValueMap[diceValue].ind = index;
    diceValueMap[diceValue].cs = cumulativeScore;
}

var numTestCases = parseInt(readline());
var diceValueMap = {};
var maximumScore = 0;
var maximumScoreDice = 0;
var maximumScoreInd = 0;

for (var i = 0; i < numTestCases; i++) {
    var numRounds = parseInt(readline());
    var inpFirstLine = readline().split(" ");
    var diceValueArray = inpFirstLine.map(element => parseInt(element));
    diceValueMap = {};
    maximumScore = 1;
    maximumScoreDice = diceValueArray[0];
    maximumScoreInd = 0;
    for (var ind = 0; ind < numRounds; ind++) {
        updateDiceValueMap(ind, diceValueArray[ind]);
    }
    for (var key in diceValueMap) {
        if (diceValueMap[key].cs >= maximumScore) {
            maximumScore = diceValueMap[key].cs;
            maximumScoreInd = diceValueMap[key].ind;
            maximumScoreDice = key;
        }
    }
    var currentScoreValue = 0;
    var diceInd = maximumScoreInd;
    for (; diceInd > 0 && currentScoreValue < maximumScore; diceInd--) {
        if (diceValueArray[diceInd] == maximumScoreDice) {
            currentScoreValue++;
        }
    }
    print(maximumScoreDice, (diceInd + 1), (maximumScoreInd + 1));
}

function updateDiceValueMap(index, diceValue) {
    var cumulativeScore = 1;
    if (diceValueMap.hasOwnProperty(diceValue)) {
        cumulativeScore = Math.max(1, diceValueMap[diceValue].cs - (index - (diceValueMap[diceValue].ind + 2)));
    } else {
        cumulativeScore = 1;
        diceValueMap[diceValue] = {};
    }

    diceValueMap[diceValue].ind = index;
    diceValueMap[diceValue].cs = cumulativeScore;
}

var numTestCases = parseInt(readline());
var diceValueMap = {};
var maximumScore = 0;
var maximumScoreDice = 0;
var maximumScoreInd = 0;

for (var i = 0; i < numTestCases; i++) {
    var numRounds = parseInt(readline());
    var inpFirstLine = readline().split(" ");
    var diceValueArray = inpFirstLine.map(element => parseInt(element));
    diceValueMap = {};
    maximumScore = 1;
    maximumScoreDice = diceValueArray[0];
    maximumScoreInd = 0;
    for (var ind = 0; ind < numRounds; ind++) {
        updateDiceValueMap(ind, diceValueArray[ind]);
    }
    for (var key in diceValueMap) {
        if (diceValueMap[key].cs >= maximumScore) {
            maximumScore = diceValueMap[key].cs;
            maximumScoreInd = diceValueMap[key].ind;
            maximumScoreDice = key;
        }
    }
    var currentScoreValue = 0;
    var diceInd = maximumScoreInd;
    for (; diceInd > 0 && currentScoreValue < maximumScore; diceInd--) {
        if (diceValueArray[diceInd] == maximumScoreDice) {
            currentScoreValue++;
        }
    }
    print(maximumScoreDice, " ", diceInd + 1, " ", maximumScoreInd + 1);
}

function updateDiceValueMap(index, diceValue) {
    var cumulativeScore = 1;
    if (diceValueMap.hasOwnProperty(diceValue)) {
        cumulativeScore = Math.max(1, diceValueMap[diceValue].cs - (index - (diceValueMap[diceValue].ind + 2)));
    } else {
        cumulativeScore = 1;
        diceValueMap[diceValue] = {};
    }

    diceValueMap[diceValue].ind = index;
    diceValueMap[diceValue].cs = cumulativeScore;
}

'use strict';

function solve(n, a) {
  const map = new Map();
  for (let [i, num] of a.entries()) {
    if (!map.has(num)) map.set(num, []);
    map.get(num).push(i);
  }
  let res = [1, a[0], 0, 0];
  for (let [num, list] of map) {
    const sum = [];
    let r = 0;
    sum[0] = 1;
    for (let i = 1; i < list.length; i++) {
      var _list;
      const cur = sum[i - 1] - (list[i] - ((_list = list[i - 1]) !== null && _list !== void 0 ? _list : -1) - 1) + 1;
      sum[i] = Math.max(1, cur);
      if (sum[i] > sum[r]) r = i;
    }
    let l = r;
    while (l - 1 >= 0 && sum[l - 1] <= sum[l]) l--;
    if (res[0] < sum[r]) {
      res = [sum[r], num, list[l], list[r]];
    }
  }
  const [, x, y, z] = res;
  return `${x} ${y + 1} ${z + 1}`;
}

async function main(read) {
  try {
    let t = Number(await read());
    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) {
  const map = new Map();
  for (let [i, num] of a.entries()) {
    if (!map.has(num)) map.set(num, []);
    map.get(num).push(i);
  }
  let res = [1, a[0], 0, 0];
  for (let [num, list] of map) {
    const sum = [];
    let l = 0,
        r = 0;
    sum[0] = 1;
    for (let i = 1; i < list.length; i++) {
      var _list;
      const cur = sum[i - 1] - (list[i] - ((_list = list[i - 1]) !== null && _list !== void 0 ? _list : -1) - 1) + 1;
      if (cur > 0) {
        r = i;
      } else {
        l = i;
        r = i;
      }
      sum[i] = Math.max(0, cur);
      if (res[0] < sum[i]) {
        res = [sum[i], num, list[l], list[r]];
      }
    }
  }
  const [, x, y, z] = res;
  return `${x} ${y + 1} ${z + 1}`;
}

async function main(read) {
  try {
    let t = Number(await read());
    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);
});


Monocarp has been collecting rare magazines for quite a while, and now he has decided to sell them. He distributed the magazines between $$$n$$$ boxes, arranged in a row. The $$$i$$$-th box contains $$$a_i$$$ magazines. Some of the boxes are covered with lids, others are not. Suddenly it started to rain, and now Monocarp has to save as many magazines from the rain as possible. To do this, he can move the lids between boxes as follows: if the $$$i$$$-th box was covered with a lid initially, he can either move the lid from the $$$i$$$-th box to the box $$$(i-1)$$$ (if it exists), or keep the lid on the $$$i$$$-th box. You may assume that Monocarp can move the lids instantly at the same moment, and no lid can be moved more than once. If a box will be covered with a lid after Monocarp moves the lids, the magazines in it will be safe from the rain; otherwise they will soak.You have to calculate the maximum number of magazines Monocarp can save from the rain.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of the testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of boxes. The second line contains a string of $$$n$$$ characters 0 and/or 1. If the $$$i$$$-th character is 1, the $$$i$$$-th box is initially covered with a lid. If the $$$i$$$-th character is 0, the $$$i$$$-th box is initially not covered. The third line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the number of magazines in the $$$i$$$-th box. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print one integer — the maximum number of magazines Monocarp can save from the rain.

NoteIn the first testcase of the example, Monocarp can move the lid from the second box to the first box, so the boxes $$$1$$$, $$$3$$$ and $$$4$$$ are covered, and $$$10 + 8 + 9 = 27$$$ magazines are saved.In the second testcase, Monocarp can move the lid from the second box to the first box, then from the third box to the second box, then from the fifth box to the fourth box, and then from the sixth box to the fifth box. The boxes $$$1$$$, $$$2$$$, $$$4$$$ and $$$5$$$ will be covered, so $$$20 + 10 + 30 + 20 = 80$$$ magazines can be saved.There are no lids in the third testcase, so it's impossible to save even a single magazine.

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let lid = iInpArr1();
    let arr = iInpArr();
    let narr = [];
    let lidc = 0,
      zero = -1;
    if (n === 1) {
      if (lid[0] === 1) console.log(arr[0]);
      else console.log(0);
      continue;
    }
    for (let i = 0; i < n; i++) {
      if (lid[i] === 1) {
        if (zero !== -1 && arr[zero] > arr[i]) {
          lid[zero] = 1;
          lid[i] = 0;
          zero = i;
        }
      } else zero = i;
    }
    let sum = 0;
    for (let i = 0; i < n; i++) if (lid[i] === 1) sum += arr[i];
    console.log(sum);
  }
};
solve();

/*
* auther yeling
*
*
*/
'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(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin(n, lids, vals) {
    //print(n, lids, vals);
    let sum = 0;
    let dp = new Array(n).fill(0).map(() => new Array(2).fill(0));
    //dp[i][0] 表示i位不移动
    //dp[i][1] 表示i位移动

    for(let i = 0; i < n; i++) {
        if(lids[i] == 1) {
            if(i == 0) {
                dp[i][0] = vals[i];
            } else if(lids[i - 1] == 0) {
                let pre = Math.max(dp[i-1][0], dp[i-1][1]);
                dp[i][0] = pre + vals[i];
                dp[i][1] = pre + vals[i-1];
            } else if(lids[i - 1] == 1) {
                dp[i][1] = Math.max(dp[i][1], dp[i-1][1] + vals[i-1]);
                dp[i][0] = Math.max(dp[i][1], dp[i-1][1] + vals[i]);
                dp[i][0] = Math.max(dp[i][0], dp[i-1][0] + vals[i]);
            }
        } else {
            if(i > 0) {
                dp[i][0] = dp[i-1][0];
                dp[i][1] = dp[i-1][1];
            }
        }

    }
    print(Math.max(dp[n-1][0], dp[n-1][1]));
}

function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        var lids = readline()
            .trim()
            .split('')
            .map((y) => parseInt(y, 10));
        var vals = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        begin(n, lids, vals);
    }
}

'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, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = read(),
        b = rns();
  const dp = Array.from({
    length: n
  }, () => [0, 0]);
  for (let i = 0; i < n; i++) {
    if (a[i] === '1') {
      var _dp$, _dp, _dp$2, _dp2, _dp$3, _dp3, _b;
      dp[i][1] = Math.max((_dp$ = (_dp = dp[i - 1]) === null || _dp === void 0 ? void 0 : _dp[0]) !== null && _dp$ !== void 0 ? _dp$ : 0, (_dp$2 = (_dp2 = dp[i - 1]) === null || _dp2 === void 0 ? void 0 : _dp2[1]) !== null && _dp$2 !== void 0 ? _dp$2 : 0) + b[i];
      dp[i][0] = ((_dp$3 = (_dp3 = dp[i - 1]) === null || _dp3 === void 0 ? void 0 : _dp3[0]) !== null && _dp$3 !== void 0 ? _dp$3 : 0) + ((_b = b[i - 1]) !== null && _b !== void 0 ? _b : 0);
    } else {
      var _dp$4, _dp4, _dp$5, _dp5;
      dp[i][0] = Math.max((_dp$4 = (_dp4 = dp[i - 1]) === null || _dp4 === void 0 ? void 0 : _dp4[0]) !== null && _dp$4 !== void 0 ? _dp$4 : 0, (_dp$5 = (_dp5 = dp[i - 1]) === null || _dp5 === void 0 ? void 0 : _dp5[1]) !== null && _dp$5 !== void 0 ? _dp$5 : 0);
    }
  }
  return Math.max(dp[n - 1][0], dp[n - 1][1]);
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let lid = iInpArr1();
    let arr = iInpArr();
    let narr = [];
    let lidc = 0,
      zero = -1;
    if (n === 1) {
      if (lid[0] === 1) console.log(arr[0]);
      else console.log(0);
      continue;
    }
    for (let i = 1; i < n; i++) {
      if (lid[i] === 1) {
        if (zero !== -1 && arr[zero] > arr[i]) {
          lid[zero] = 1;
          lid[i] = 0;
          zero = i;
        }
      } else zero = i;
    }
    let sum = 0;
    for (let i = 0; i < n; i++) if (lid[i] === 1) sum += arr[i];
    console.log(sum);
  }
};
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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let lid = iInpArr1();
    let arr = iInpArr();
    let narr = [];
    let lidc = 0,
      zero = 0;
    if (n === 1) {
      if (lid[0] === 1) console.log(arr[0]);
      else console.log(0);
      continue;
    }
    for (let i = 1; i < n; i++) {
      if (lid[i] === 1) {
        if (arr[zero] > arr[i]) {
          lid[zero] = 1;
          lid[i] = 0;
          zero = i;
        }
      } else zero = i;
    }
    let sum = 0;
    for (let i = 0; i < n; i++) if (lid[i] === 1) sum += arr[i];
    console.log(sum);
  }
};
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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let lid = iInpArr1();
    let arr = iInpArr();
    let narr = [];
    let lidc = 0,
      zero = 0;
    for (let i = 0; i < n; i++) if (lid[i] === 1) lidc++;
    for (let i = 1; i < n; i++) {
      if (lid[i] === 1) {
        if (arr[zero] > arr[i]) {
          lid[zero] = 1;
          lid[i] = 0;
          zero = i;
        }
      } else zero = i;
    }
    let sum = 0;
    for (let i = 0; i < n; i++) if (lid[i] === 1) sum += arr[i];
    console.log(sum);
  }
};
solve();

/*
* auther yeling
*
*
*/
'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(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin(n, lids, vals) {
    //print(n, lids, vals);
    let sum = 0;
    let dp = new Array(n).fill(0).map(() => new Array(2).fill(0));
    //dp[i][0] 表示i位不移动
    //dp[i][1] 表示i位移动

    for(let i = 0; i < n; i++) {
        if(lids[i] == 1) {
            if(i == 0) {
                dp[i][0] = dp[i][1] = vals[i];
            } else if(lids[i - 1] == 0) {
                let pre = Math.max(dp[i-1][0], dp[i-1][1]);
                dp[i][0] = pre + vals[i];
                dp[i][1] = pre + vals[i-1];
            } else if(lids[i - 1] == 1) {
                dp[i][1] = Math.max(dp[i][1], dp[i-1][1] + vals[i-1]);
                dp[i][0] = Math.max(dp[i][1], dp[i-1][1] + vals[i]);
                dp[i][0] = Math.max(dp[i][0], dp[i-1][0] + vals[i]);
            }
        } else {
            if(i > 0) {
                dp[i][0] = dp[i-1][0];
                dp[i][1] = dp[i-1][1];
            }
        }

    }
    print(Math.max(dp[n-1][0], dp[n-1][1]));
}

function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        var lids = readline()
            .trim()
            .split('')
            .map((y) => parseInt(y, 10));
        var vals = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        begin(n, lids, vals);
    }
}

/*
* auther yeling
*
*
*/
'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(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin(n, lids, vals) {
    //print(n, lids, vals);
    let sum = 0;
    let stack = new Array();
    for(let i = 0; i < n; i++) {
        stack.push(vals[i]);
        if(lids[i] == 1) {
            let max = 0;
            let maxIndex = 0;
            for(let j = 0; j < stack.length; j++) {
                if(max < stack[j]) {
                    max = stack[j];
                    maxIndex = j;
                }
            }
            sum += max;
            stack.splice(maxIndex, 1);
        }
    }
    print(sum);
}

function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        var lids = readline()
            .trim()
            .split('')
            .map((y) => parseInt(y, 10));
        var vals = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        begin(n, lids, vals);
    }
}