While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way.  For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$.  The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) — the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) — the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) — the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) — the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.

For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.

NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
            v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map();
    let time = 1,
        idx = 0;
    const dfs = RTI((u, p) => {
      dfn[u] = low[u] = time++;
      stack.push(u);
      set.add(u);
      const inside = () => {
        let res = [];
        for (let v of g[u]) {
          if (!dfn[v]) {
            res.push([v, u]);
          } else if (set.has(v)) {
            low[u] = Math.min(low[u], dfn[v]);
          }
        }
        return res;
      };
      const after = () => {
        if (dfn[u] === low[u]) {
          while (true) {
            const j = stack.pop();
            set.delete(j);
            map.set(j, idx);
            if (j === u) break;
          }
          idx++;
        }
        if (p !== -1) low[p] = Math.min(low[p], low[u]);
      };
      return [inside, after];
    });
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) dfs(i, -1);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = result => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, ...curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
            v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map();
    let time = 1,
        idx = 0;
    const dfs = RTI((u, p) => {
      const before = () => {
        dfn[u] = low[u] = time++;
        stack.push(u);
        set.add(u);
      };
      const inside = () => {
        let res = [];
        for (let v of g[u]) {
          if (!dfn[v]) {
            res.push([v, u]);
          } else if (set.has(v)) {
            low[u] = Math.min(low[u], dfn[v]);
          }
        }
        return res;
      };
      const after = () => {
        if (dfn[u] === low[u]) {
          while (true) {
            const j = stack.pop();
            set.delete(j);
            map.set(j, idx);
            if (j === u) break;
          }
          idx++;
        }
        if (p !== -1) low[p] = Math.min(low[p], low[u]);
      };
      return [before, inside, after];
    });
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) dfs(i, -1);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}
function RTI(fn) {
  const done = () => {};
  const dfs = (...args) => {
    const callStack = [[done, args]];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {
        var _curCall;
        const after = curCall.pop();
        after();
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall && curCall.length > 1) curCall.pop();
      }
      if (!curCall) break;
      const args = curCall[curCall.length - 1];
      const [before, inside, after] = fn(...args);
      before();
      let nextCall = inside();
      callStack.push([after, ...nextCall]);
    }
  };
  return dfs;
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

async function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
            v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = async () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map();
    let time = 1,
        idx = 0;
    const dfs = RTI((u, p) => {
      const before = () => {
        dfn[u] = low[u] = time++;
        stack.push(u);
        set.add(u);
      };
      const inside = () => {
        let res = [];
        for (let v of g[u]) {
          if (!dfn[v]) {
            res.push([v, u]);
          } else if (set.has(v)) {
            low[u] = Math.min(low[u], dfn[v]);
          }
        }
        return res;
      };
      const after = () => {
        if (dfn[u] === low[u]) {
          while (true) {
            const j = stack.pop();
            set.delete(j);
            map.set(j, idx);
            if (j === u) break;
          }
          idx++;
        }
        if (p !== -1) low[p] = Math.min(low[p], low[u]);
      };
      return [before, inside, after];
    });
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) dfs(i, -1);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}
function RTI(fn) {
  const done = () => {};
  const dfs = (...args) => {
    const callStack = [[done, args]];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {
        var _curCall;
        const after = curCall.pop();
        after();
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall && curCall.length > 1) curCall.pop();
      }
      if (!curCall) break;
      const args = curCall[curCall.length - 1];
      const [before, inside, after] = fn(...args);
      before();
      let nextCall = inside();
      callStack.push([after, ...nextCall]);
    }
  };
  return dfs;
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
            v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map();
    let time = 1,
        idx = 0;
    const dfs = RTI((u, p) => {
      const before = () => {
        dfn[u] = low[u] = time++;
        stack.push(u);
        set.add(u);
      };
      const inside = () => {
        let res = [];
        for (let v of g[u]) {
          if (!dfn[v]) {
            res.push([v, u]);
          } else if (set.has(v)) {
            low[u] = Math.min(low[u], dfn[v]);
          }
        }
        return res;
      };
      const after = () => {
        if (dfn[u] === low[u]) {
          while (true) {
            const j = stack.pop();
            set.delete(j);
            map.set(j, idx);
            if (j === u) break;
          }
          idx++;
        }
        if (p !== -1) low[p] = Math.min(low[p], low[u]);
      };
      return [before, inside, after];
    });
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) dfs(i, -1);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}
function RTI(fn) {
  const done = () => {};
  const dfs = (...args) => {
    const callStack = [[done, args]];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {
        var _curCall;
        const after = curCall.pop();
        after();
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall && curCall.length > 1) curCall.pop();
      }
      if (!curCall) break;
      const args = curCall[curCall.length - 1];
      const [before, inside, after] = fn(...args);
      before();
      let nextCall = inside(...args);
      callStack.push([after, ...nextCall]);
    }
  };
  return dfs;
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
            v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map(),
          fa = [];
    let time = 1,
        idx = 0;
    const dfs = u => {
      const callStack = [[u]];
      while (callStack.length) {
        let curCall = callStack[callStack.length - 1];
        while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {
          var _curCall;
          callStack.pop();
          curCall = callStack[callStack.length - 1];
          if (!curCall) continue;
          const v = curCall.pop();
          if (dfn[v] === low[v]) {
            while (true) {
              const j = stack.pop();
              set.delete(j);
              map.set(j, idx);
              if (j === v) break;
            }
            idx++;
          }
          const u = fa[v];
          low[u] = Math.min(low[u], low[v]);
        }
        if (!curCall) break;
        const u = curCall[curCall.length - 1];
        if (!dfn[u]) {
          dfn[u] = low[u] = time++;
          stack.push(u);
          set.add(u);
          let nextCall = [];
          for (let v of g[u]) {
            if (!dfn[v]) {
              fa[v] = u;
              nextCall.push(v);
            } else if (set.has(v)) {
              low[u] = Math.min(low[u], dfn[v]);
            }
          }
          callStack.push(nextCall);
          continue;
        } else if (set.has(u)) {
          const f = fa[u];
          low[f] = Math.min(low[f], dfn[u]);
        }
        curCall.pop();
      }
    };
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) dfs(i);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  let ans = '';
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      ans += calc(T)+'\n';
  } else
   pcalc();
  process.stdout.write(ans)
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

const MOD = 1e9+7;
const calc = ()=>{
  // READING:
  let [n] = ra();
  let A = ra();
  let B = ra();
  let C = ra();
  LT({n, A, B});
  // PROCESSING:
  let posA = new Array(n+1).fill(-1);
  let posB = new Array(n+1).fill(-1);
  for (let i=0; i<n; i++){
    posA[A[i]] = i;
    posB[B[i]] = i;
  }
  let decided = new Set();
  let decidedPos = new Array(n).fill(0);
  let queue = [], qi = 0;
  for (let i=0; i<n; i++){
    if (A[i]==B[i]){
      decided.add(A[i]);
      decidedPos[i] = 1;
    }
    if (C[i]!=0){
      decided.add(A[i]);
      decided.add(B[i]);
      queue.push(i);
    }
  }
  let ans = 1;
  let pos = 0;
  while (decided.size<n){
    if (!(qi<queue.length)){
      ans = (ans * 2) % MOD;
      while (pos<n && decided.has(A[pos]) && decided.has(B[pos])){
        pos++;
      }
      decided.add(A[pos])
      decided.add(B[pos])
      queue.push(pos);
    }
    while (qi<queue.length){
      let p = queue[qi++];
      decided.add(A[p])
      decided.add(B[p])
      if (!decidedPos[posB[A[p]]]){
        decidedPos[posB[A[p]]] = 1;
        queue.push(posB[A[p]]);
      }
      if (!decidedPos[posA[B[p]]]){
        decidedPos[posA[B[p]]] = 1;
        queue.push(posA[B[p]]);
      }
    }
  }
  return ans;
};

const readline = require('readline')

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

function solve(n, sa, sb, sc) {
    const r = {}
    sa.forEach((x, i) => {
        r[x] = i
    })
    //
    const v = {}
    let ans = 1
    for (let i = 0; i < n; i++) {
        if (v[sa[i]]) continue
        v[sa[i]] = 1

        let j = i
        let f = 0
        let k = 1
        while (!v[sb[j]]) {
            // v[sa[j]] = 1
            v[sb[j]] = 1
            k++
            if (sc[j]) f = 1
            //
            j = r[sb[j]]
        // console.log('j', j)
        }
            if (sc[j]) f = 1
        // console.log(k)
        if (!f) {
            ans = mul(ans, k === 1 ? 1 : 2)
        }
    }
        // console.log('-')
    return ans
}

const MOD = 1e9 + 7
const MOD_CUT = ((1 << 20) * (1 << 20)) % MOD
function add(a, b) {
    return (a + b) % MOD
}
function minus(a, b) {
    return add(add(a, -b), MOD)
}
function mul(a, b) {
    let r = (a >> 20) * (b >> 20) * MOD_CUT
        + (a & 0xfff00000) * (b & 0xfffff)
        + (a & 0xfffff) * b
    return r % MOD
}
function pow(a, b) {
    let r = 1
    let base = a
    while (b) {
        if (b & 1) {
            r = mul(r, base)
        }
        b >>= 1
        base = mul(base, base)
    }
    return r
}

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

    let T = parseInt(lines[0]);
    for (let i = 0; i < T; i++) {
        main1(lines.slice(i * 4 + 1, (i + 1) * 4 + 1));
    }
});

function main1(lines) {
    const N = lines[0];
    const A = lines[1].split(' ').map(u => parseInt(u));
    const B = lines[2].split(' ').map(u => parseInt(u));
    const C = lines[3].split(' ').map(u => parseInt(u));

    const arrow = {};
    for (let i = 0; i < N; i++) {
        arrow[A[i]] = B[i];
    }

    const cSet = {};
    for (let i = 0; i < N; i++) {
        cSet[C[i]] = true;
    }

    const taken = new Array(N + 1);
    for (let i = 0; i <= N; i++) {
        taken[i] = false;
    }

    const cycles = [];
    for (let i = 1; i <= N; i++) {
        if (!taken[i]) {
            const cycle = [];
            let j = i;
            while (!taken[j]) {
                taken[j] = 1;
                cycle.push(j);
                j = arrow[j];
            }

            cycles.push(cycle);
        }
    }

    let ans = 1;
    let MODD = 1000000007;
    for (const cycle of cycles) {
        let ok = true;
        for (const u of cycle) {
            if (cSet[u]) {
                ok = false;
                break;
            }
        }

        if (ok && cycle.length > 1) {
            ans = (ans * 2) % MODD;
        }
    }

    console.log(ans);
}

const {
  Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

function parseJSAsync(script, workerData) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(script, { eval: true, workerData });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });
};

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }

  await parseJSAsync(`
  const {
    Worker, isMainThread, parentPort, workerData
  } = require('worker_threads');
let MaximumCallStateSize=0
function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
        v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = () => {
    const dfn = [],
      low = [],
      stack = [],
      set = new Set(),
      map = new Map();
    let time = 1,
      idx = 0;
    const dfs = u => {
      MaximumCallStateSize++
      dfn[u] = low[u] = time++;
      stack.push(u);
      set.add(u);
      for (let v of g[u]) {
        if (!dfn[v]) {
          dfs(v);
          low[u] = Math.min(low[u], low[v]);
        } else if (set.has(v)) {
          low[u] = Math.min(low[u], dfn[v]);
        }
      }
      if (dfn[u] === low[u]) {
        while (true) {
          const j = stack.pop();
          set.delete(j);
          map.set(j, idx);
          if (j === u) break;
        }
        idx++;
      }
    };
    for (let i = 1; i <= n; i++) {
      MaximumCallStateSize=0
      if (!dfn[i] && g[i].size) dfs(i);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}

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

void function () {
  const inputs = workerData;
  let i = 0;
  function read() {
    return inputs[i++];
  }
  main(read);
}();

  `, inputs)
}();

const {
  Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

function parseJSAsync(script, workerData) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(script, { eval: true, workerData });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });
};

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }

  await parseJSAsync(`
  const {
    Worker, isMainThread, parentPort, workerData
  } = require('worker_threads');

function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
        v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = () => {
    const dfn = [],
      low = [],
      stack = [],
      set = new Set(),
      map = new Map();
    let time = 1,
      idx = 0;
    const dfs = u => {
      dfn[u] = low[u] = time++;
      stack.push(u);
      set.add(u);
      for (let v of g[u]) {
        if (!dfn[v]) {
          dfs(v);
          low[u] = Math.min(low[u], low[v]);
        } else if (set.has(v)) {
          low[u] = Math.min(low[u], dfn[v]);
        }
      }
      if (dfn[u] === low[u]) {
        while (true) {
          const j = stack.pop();
          set.delete(j);
          map.set(j, idx);
          if (j === u) break;
        }
        idx++;
      }
    };
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) dfs(i);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}

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

void function () {
  const inputs = workerData;
  let i = 0;
  function read() {
    return inputs[i++];
  }
  main(read);
}();

  `, inputs)
}();

const {
  Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

function parseJSAsync(script, workerData) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(script, { eval: true, workerData });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });
};

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }

  await parseJSAsync(`
  const {
    Worker, isMainThread, parentPort, workerData
  } = require('worker_threads');

function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
        v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = () => {
    const dfn = [],
      low = [],
      stack = [],
      set = new Set(),
      map = new Map();
    let time = 1,
      idx = 0;
    const dfs = u => {
      dfn[u] = low[u] = time++;
      stack.push(u);
      set.add(u);
      for (let v of g[u]) {
        if (!dfn[v]) {
          dfs(v);
          low[u] = Math.min(low[u], low[v]);
        } else if (set.has(v)) {
          low[u] = Math.min(low[u], dfn[v]);
        }
      }
      if (dfn[u] === low[u]) {
        while (true) {
          const j = stack.pop();
          set.delete(j);
          map.set(j, idx);
          if (j === u) break;
        }
        idx++;
      }
    };
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) dfs(i);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}

function main(read) {
  let t = Number(read());
  let res = [];
  while (t--) {
    const n = Number(read());
    const a = read().split(' ').map(Number);
    const b = read().split(' ').map(Number);
    const d = read().split(' ').map(Number);
    res.push(solve(n, a, b, d));
  }
  console.log(res.map(num => num.toString()).join('\\n'));
}

void function () {
  const inputs = workerData;
  let i = 0;
  function read() {
    return inputs[i++];
  }
  main(read);
}();

  `, inputs)
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

async function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
            v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = async () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map();
    let time = 1,
        idx = 0;
    const dfs = async u => {
      dfn[u] = low[u] = time++;
      stack.push(u);
      set.add(u);
      for (let v of g[u]) {
        if (!dfn[v]) {
          await dfs(v);
          low[u] = Math.min(low[u], low[v]);
        } else if (set.has(v)) {
          low[u] = Math.min(low[u], dfn[v]);
        }
      }
      if (dfn[u] === low[u]) {
        while (true) {
          const j = stack.pop();
          set.delete(j);
          map.set(j, idx);
          if (j === u) break;
        }
        idx++;
      }
    };
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) await dfs(i);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

async function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
            v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = async () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map();
    let time = 1,
        idx = 0;
    const dfs = async u => {
      dfn[u] = low[u] = time++;
      stack.push(u);
      set.add(u);
      for (let v of g[u]) {
        if (!dfn[v]) {
          dfs(v);
          low[u] = Math.min(low[u], low[v]);
        } else if (set.has(v)) {
          low[u] = Math.min(low[u], dfn[v]);
        }
      }
      if (dfn[u] === low[u]) {
        while (true) {
          const j = stack.pop();
          set.delete(j);
          map.set(j, idx);
          if (j === u) break;
        }
        idx++;
      }
    };
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) await dfs(i);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
            v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map();
    let time = 1,
        idx = 0;
    const dfs = u => {
      dfn[u] = low[u] = time++;
      stack.push(u);
      set.add(u);
      for (let v of g[u]) {
        if (!dfn[v]) {
          dfs(v);
          low[u] = Math.min(low[u], low[v]);
        } else if (set.has(v)) {
          low[u] = Math.min(low[u], dfn[v]);
        }
      }
      if (dfn[u] === low[u]) {
        while (true) {
          const j = stack.pop();
          set.delete(j);
          map.set(j, idx);
          if (j === u) break;
        }
        idx++;
      }
    };
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) dfs(i);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
            v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  console.log(g);
  const tarjan = () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map(),
          fa = [];
    let time = 1,
        idx = 0;
    const dfs = u => {
      const callStack = [[u]];
      while (callStack.length) {
        let curCall = callStack[callStack.length - 1];
        while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 0) {
          var _curCall;
          callStack.pop();
          curCall = callStack[callStack.length - 1];
          if (!curCall) continue;
          const v = curCall.pop();
          if (dfn[v] === low[v]) {
            while (true) {
              const j = stack.pop();
              set.delete(j);
              map.set(j, idx);
              if (j === v) break;
            }
            idx++;
          }
          const u = fa[v];
          low[u] = Math.min(low[u], low[v]);
        }
        if (!curCall) break;
        const u = curCall[curCall.length - 1];
        if (!dfn[u]) {
          dfn[u] = low[u] = time++;
          stack.push(u);
          set.add(u);
          let nextCall = [];
          for (let v of g[u]) {
            if (!dfn[v]) {
              fa[v] = u;
              nextCall.push(v);
            } else if (set.has(v)) {
              low[u] = Math.min(low[u], dfn[v]);
            }
          }
          callStack.push(nextCall);
          continue;
        } else if (set.has(u)) {
          const f = fa[u];
          low[f] = Math.min(low[f], dfn[u]);
        }
        curCall.pop();
      }
    };
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) dfs(i);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

const readline = require('readline')

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

function solve(n, sa, sb, sc) {
    const r = {}
    sa.forEach((x, i) => {
        r[x] = i
    })
    //
    const v = {}
    let ans = 1
    for (let i = 0; i < n; i++) {
        if (v[sa[i]]) continue
        v[sa[i]] = 1

        let j = i
        let f = 0
        let k = 1
        while (!v[sb[j]]) {
            // v[sa[j]] = 1
            v[sb[j]] = 1
            k++
            if (sc[j]) f = 1
            //
            j = r[sb[j]]
        // console.log('j', j)
        }
        // console.log(k)
        if (!f) {
            ans = mul(ans, k === 1 ? 1 : 2)
        }
    }
    return ans
}

const MOD = 1e9 + 7
const MOD_CUT = ((1 << 20) * (1 << 20)) % MOD
function add(a, b) {
    return (a + b) % MOD
}
function minus(a, b) {
    return add(add(a, -b), MOD)
}
function mul(a, b) {
    let r = (a >> 20) * (b >> 20) * MOD_CUT
        + (a & 0xfff00000) * (b & 0xfffff)
        + (a & 0xfffff) * b
    return r % MOD
}
function pow(a, b) {
    let r = 1
    let base = a
    while (b) {
        if (b & 1) {
            r = mul(r, base)
        }
        b >>= 1
        base = mul(base, base)
    }
    return r
}


Let's suppose you have an array a, a stack s (initially empty) and an array b (also initially empty).You may perform the following operations until both a and s are empty:  Take the first element of a, push it into s and remove it from a (if a is not empty);  Take the top element from s, append it to the end of array b and remove it from s (if s is not empty). You can perform these operations in arbitrary order.If there exists a way to perform the operations such that array b is sorted in non-descending order in the end, then array a is called stack-sortable.For example, [3, 1, 2] is stack-sortable, because b will be sorted if we perform the following operations:  Remove 3 from a and push it into s;  Remove 1 from a and push it into s;  Remove 1 from s and append it to the end of b;  Remove 2 from a and push it into s;  Remove 2 from s and append it to the end of b;  Remove 3 from s and append it to the end of b. After all these operations b = [1, 2, 3], so [3, 1, 2] is stack-sortable. [2, 3, 1] is not stack-sortable.You are given k first elements of some permutation p of size n (recall that a permutation of size n is an array of size n where each integer from 1 to n occurs exactly once). You have to restore the remaining n - k elements of this permutation so it is stack-sortable. If there are multiple answers, choose the answer such that p is lexicographically maximal (an array q is lexicographically greater than an array p iff there exists some integer k such that for every i < k qi = pi, and qk > pk). You may not swap or change any of first k elements of the permutation.Print the lexicographically maximal permutation p you can obtain.If there exists no answer then output -1.

The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k < n) — the size of a desired permutation, and the number of elements you are given, respectively. The second line contains k integers p1, p2, ..., pk (1 ≤ pi ≤ n) — the first k elements of p. These integers are pairwise distinct.

If it is possible to restore a stack-sortable permutation p of size n such that the first k elements of p are equal to elements given in the input, print lexicographically maximal such permutation. Otherwise print -1.

var Segment = function Segment(start, end) {
  this.start = start;
  this.end = end;
};

var main = function main() {
  var input = readline()
    .split(" ")
    .map(function (i) {
      return Number(i);
    });

  var N = input[0];
  var K = input[1];

  var nums = readline()
    .split(" ")
    .map(function (i) {
      return Number(i);
    });

  var stack = [];

  for (var i = 0; i < K; i++) {
    var currSegment = stack.pop() || new Segment(1, N);

    if (nums[i] < currSegment.start || nums[i] > currSegment.end) {
      return -1;
    }

    if (nums[i] < currSegment.end) {
      stack.push(new Segment(nums[i] + 1, currSegment.end));
    }

    if (nums[i] > currSegment.start) {
      stack.push(new Segment(currSegment.start, nums[i] - 1));
    }
  }

  while (stack.length) {
    var currSegment = stack.pop();

    for (var i = currSegment.end; i >= currSegment.start; i--) {
      nums.push(i);
    }
  }

  return nums.join(" ");
};

print(main());

var Segment = function Segment(start, end) {
  this.start = start;
  this.end = end;
};

var main = function main() {
  var input = readline()
    .split(" ")
    .map(function (i) {
      return Number(i);
    });
  var N = input[0];
  var K = input[1];
  var nums = readline()
    .split(" ")
    .map(function (i) {
      return Number(i);
    });
  var stack = [new Segment(nums[0] + 1, N), new Segment(1, nums[0] - 1)];

  for (var i = 1; i < K; i++) {
    var currSegment = stack.pop();

    if (nums[i] < currSegment.start || nums[i] > currSegment.end) {
      return -1;
    }

    if (nums[i] < currSegment.end) {
      stack.push(new Segment(nums[i] + 1, currSegment.end));
    }

    if (nums[i] > currSegment.start) {
      stack.push(new Segment(currSegment.start, nums[i] - 1));
    }
  }

  while (stack.length) {
    var currSegment = stack.pop();

    for (var i = currSegment.end; i >= currSegment.start; i--) {
      nums.push(i);
    }
  }

  return nums.join(" ");
};

print(main());

var Segment = function Segment(start, end) {
  this.start = start;
  this.end = end;
};

var main = function main() {
  var input = readline()
    .split(" ")
    .map(function (i) {
      return Number(i);
    });
  var N = input[0];
  var K = input[1];
  var nums = readline()
    .split(" ")
    .map(function (i) {
      return Number(i);
    });
  var stack = [new Segment(nums[0] + 1, N), new Segment(1, nums[0] - 1)];

  for (var i = 1; i < K; i++) {
    var currSegment = stack.pop();

    if (nums[i] < currSegment.start || nums[i] > currSegment.end) {
      return -1;
    }

    if (nums[i] < currSegment.end) {
      stack.push(new Segment(nums[i] + 1, currSegment.end));
    }

    if (nums[i] > currSegment.start) {
      stack.push(new Segment(currSegment.start, nums[i] - 1));
    }
  }

  while (stack.length) {
    var currSegment = stack.pop();

    for (var i = currSegment.start; i <= currSegment.end; i++) {
      nums.push(i);
    }
  }

  return nums.join(" ");
};

print(main());


It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array $$$a$$$. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices $$$x, y, z, w$$$ such that $$$a_x + a_y = a_z + a_w$$$.Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery?

The first line contains the single integer $$$n$$$ ($$$4 \leq n \leq 200\,000$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2.5 \cdot 10^6$$$).

Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices $$$x$$$, $$$y$$$, $$$z$$$ and $$$w$$$ ($$$1 \le x, y, z, w \le n$$$). If there are multiple answers, print any of them.

NoteIn the first example $$$a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6$$$. Note that there are other answer, for example, 2 3 4 6.In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that $$$a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3$$$

'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();
var mod = 1000000000n + 7n
var maxN = 1002

function main() {
  // const x = readline();
  //
  // Array(parseInt(x)).fill(1).map((t, iii) => {
  var n = parseInt(readline())

  var a = readline().split(' ').map((x, iii) => {
    return parseInt(x)
  })

  var map = {}
  var sum = 0
  var x = 0
  var y = 0
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      sum = a[i] + a[j]
      if (!map[sum]) map[sum] = `${i}:${j}`
      else {
        [x, y] = map[sum].split(':').map(x => parseInt(x))
        if (x !== i && x !== j && y !== i && y !== j) {
          console.log('YES')
          console.log(i + 1, j + 1, x + 1, y + 1)
          return
        }
      }
    }
  }
  console.log('NO')

  // if(n>=1) ans-=a[n-1]
  // console.log(a)

  // })
}

function gcd(a, b) {
  if (!b) {
    return a;
  }

  return gcd(b, a % b);
}


Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.

The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.

Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.

NoteThe second valid answer to the test from the statement is "heloo".


You have $$$r$$$ red and $$$b$$$ blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet:   has at least one red bean (or the number of red beans $$$r_i \ge 1$$$);  has at least one blue bean (or the number of blue beans $$$b_i \ge 1$$$);  the number of red and blue beans should differ in no more than $$$d$$$ (or $$$|r_i - b_i| \le d$$$) Can you distribute all beans?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains three integers $$$r$$$, $$$b$$$, and $$$d$$$ ($$$1 \le r, b \le 10^9$$$; $$$0 \le d \le 10^9$$$) — the number of red and blue beans and the maximum absolute difference in each packet.

For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first test case, you can form one packet with $$$1$$$ red and $$$1$$$ blue bean. The absolute difference $$$|1 - 1| = 0 \le d$$$.In the second test case, you can form two packets: $$$1$$$ red and $$$4$$$ blue beans in the first packet and $$$1$$$ red and $$$3$$$ blue beans in the second one.In the third test case, since $$$b = 1$$$, you can form only one packet with $$$6$$$ red and $$$1$$$ blue beans. The absolute difference $$$|6 - 1| = 5 > d$$$.In the fourth test case, since $$$d = 0$$$ so each packet should contain the same number of red and blue beans, but $$$r \neq b$$$.

var t=+ readline();
while(t--){
    var input= readline();
    var arr= input.split(" ").map(x=>+x);
    var r=arr[0];
    var b=arr[1];
    var d=arr[2];
    if(r>b){
        var temp=r;
        r=b;
        b=temp;
    }
    var res=r*(d+1);
    if(res>=b)print("YES")
    else print("NO");
}

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

function candyShop(inp){
  let parsedInput = inp.split(' ')
                       .map(el=>Number( el)); // el.replace(/[^0-9]/g, '')
  if( parsedInput.length === 1 ) return null

  let [redAmount, blueAmount, maxDif] = [...parsedInput];
  if(maxDif===0) return redAmount===blueAmount ? 'yes' : 'no';

  let [min, max] = [Math.min(redAmount, blueAmount), Math.max(redAmount, blueAmount)],
      minDif = Math.ceil(max / min)-1;

  if(minDif > maxDif) return 'no'
  return 'yes'
}

rl.on('line', (input) => {
  let i = candyShop(input);
  if(i != null ){ console.log(i) }
});

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

function candyShop(inp){
  let parsedInput = inp.split(' ')
                       .map(el=>Number( el)); // el.replace(/[^0-9]/g, '')
  if( parsedInput.length === 1 ) return null

  let [redAmount, blueAmount, maxDif] = [...parsedInput];
  // if(maxDif===0) return redAmount===blueAmount ? 'yes' : 'no';

  let [min, max] = [Math.min(redAmount, blueAmount), Math.max(redAmount, blueAmount)],
      minDif = Math.ceil(max / min)-1;

  if(minDif > maxDif) return 'no'
  return 'yes'
}

rl.on('line', (input) => {
  let i = candyShop(input);
  if(i != null ){ console.log(i) }
});

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

function candyShop(inp){
  let parsedInput = inp.split(' ')
                       .map( el => Number( el.replace(/[^0-9]/g, '') ) ); // el.replace(/[^0-9]/g, '')
  if( parsedInput.length === 1 ) return null

  let [redAmount, blueAmount, maxDif] = [...parsedInput];
  if(maxDif===0) return redAmount===blueAmount ? 'yes' : 'no';

  let [min, max] = [Math.min(redAmount, blueAmount), Math.max(redAmount, blueAmount)],
      minDif = Math.ceil(max / min)-1;

  if(minDif > maxDif) return 'no'
  return 'yes'
}

rl.on('line', (input) => {
  let i = candyShop(input);
  if(i != null ){ console.log(i) }
});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    for(j = 1; j <= lines[0]; j ++){
        var l = lines[j].split(' ')
        var r = l[0]
        var b = l[1]
        var d = l[2]
        if(Math.abs(r - b) <= d*(Math.min(r, b))){
            console.log('YES')
        }else{
            console.log('NO')
        }
    }
});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(var j = 1; j <= n; j++){
        var l = lines[j].split(' ');
        var r = l[0];
        var b = l[1];
        var d = l[2];
        if(Math.abs(r - b) <= d * Math.min(r, b)){
            console.log('YES');
        }else{
            console.log('NO');
        }
    }
});

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
var __webpack_exports__ = {};

;// CONCATENATED MODULE: ./src/io.js
var interact = function interact(main) {
  process.stdin.resume();
  process.stdin.setEncoding('utf-8');
  var inputString = '';
  var currentLine = 0;

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

  var print = function print() {
    for (var _len = arguments.length, any = new Array(_len), _key = 0; _key < _len; _key++) {
      any[_key] = arguments[_key];
    }

    process.stdout.write(any.join(' '));
  };

  var println = function println() {
    for (var _len2 = arguments.length, any = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      any[_key2] = arguments[_key2];
    }

    any.length > 0 && print(any);
    print('\n');
  };

  var obj = {
    print: print,
    println: println,
    readline: readline
  };
  process.stdin.on('data', function (inputStdin) {
    inputString += inputStdin;
  });
  process.stdin.on('end', function () {
    inputString = inputString.trim().split('\n').map(function (string) {
      return string.trim();
    });
    main(obj);
  });
};

/* harmony default export */ const io = (interact);
;// CONCATENATED MODULE: ./src/index.js
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

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

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

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

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

var main = function main(io) {
  var tc = Number.parseInt(io.readline());

  while (tc--) {
    var _io$readline$split$ma = io.readline().split(' ').map(function (x) {
      return Number.parseInt(x);
    }),
        _io$readline$split$ma2 = _slicedToArray(_io$readline$split$ma, 3),
        r = _io$readline$split$ma2[0],
        b = _io$readline$split$ma2[1],
        d = _io$readline$split$ma2[2];

    if (r > b) {
      var temp = r;
      r = b;
      b = temp;
    } // assert r <= b

    var sat = b <= r * (1 + d);
    io.println(sat ? 'YES' : 'NO');
  }
};

io(main);
/******/ })()
;

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

    while(testCases--)
    {
        const [r,b,d] = get_ints();
        (Math.min(r,b) * (d + 1)) >= Math.max(r,b)  ? print('YES') : print('NO')

    }
});

function print(c){
    return console.log(c);
}

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

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

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

let currentLine = 0;
let inputString = "";

process.stdin.on("data", (raw_data) => {
  inputString += raw_data;
});

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

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

/******** Main function *************/

function main() {
  const t = +input();

  for (var i = 0; i < t; i++) {
    const [r, b, d] = input().split(" ").map(Number);

    const min = Math.min(r, b);
    const max = Math.max(r, b);

    const y = Math.ceil(max / min);

    if (d === 0) {
      if (r === b) {
        console.log("YES");
      } else {
        console.log("NO");
      }
    } else if (Math.abs(y - 1) > d) {
      console.log("NO");
    } else {
      console.log("YES");
    }
  }
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(var j = 1; j <= n; j++){
        var l = lines[j].split(' ');
        var r = l[0];
        var b = l[1];
        var d = l[2];
        if(Math.abs(r - b) <= d*Math.min(r, b)){
            console.log('YES');
        }else{
            console.log('NO');
        }
    }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
   const test= readline();

   for(let i=0;i<test;i++){
     let r=readline().split(' ');

    //  console.log(Number(r[2])+1);
     console.log(solve(r));
    }

   }
function solve(r){
        const result =Math.min(r[0],r[1])*(Number(r[2])+1)>=Math.max(r[0],r[1])?"Yes":"No" ;
        return result;
    }

//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 getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var R = nextInt();
		var B = nextInt();
		var D = nextInt();
		if(R > B){
			var tmp = R;
			R = B;
			B = tmp;
		}
		var diff = B - R;
		var single = Math.ceil(diff / R);
		if(single <= D){
			myout("YES");
		}else{
			myout("NO");
		}
	}
}

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 747:
/***/ ((module) => {

module.exports = require("fs");;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {

// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(747);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
;// CONCATENATED MODULE: external "readline"
const external_readline_namespaceObject = require("readline");;
;// CONCATENATED MODULE: ./src/lib/io.ts

class InteractiveIO {
  constructor() {
    this.rl = void 0;
    this.lines = [];
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this.rl.on('line', line => {
      this.lines.push(line);
    });
  }

  nextLine() {
    return new Promise((resolve, reject) => {
      if (this.lines.length) {
        resolve(this.lines.shift());
        return;
      }

      let waitId = null;
      let timeoutId = null;
      waitId = setInterval(() => {
        if (this.lines.length) {
          resolve(this.lines.shift());
          clearTimeout(timeoutId);
          clearInterval(waitId);
          return;
        }
      }, 1);
      timeoutId = setTimeout(() => {
        clearInterval(waitId);
        reject(new Error('timeout')); // resolve(null);
      }, 500);
    });
  }

  close() {
    this.rl.close();
  }

}
class IO {
  constructor() {
    this.i = 0;
    this.text = '';
    this.out = '';
    this.readInput();
  }

  readInput() {
    this.text = __webpack_require__(747).readFileSync(0, 'utf8');
  }

  nextToken() {
    let ret = '';

    while (this.text[this.i].charCodeAt(0) <= 32) {
      this.i++;
    }

    while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
      ret += this.text[this.i];
      this.i++;
    }

    return ret;
  }

  nextNum() {
    return Number(this.nextToken());
  }

  nextBigInt() {
    return BigInt(this.nextToken());
  }

  nextNumArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextNum());
    }

    return ret;
  }

  _write(x) {
    this.out += x;
  }

  write(x) {
    this._write(x + ' ');
  }

  writeLine(x) {
    this._write(x + '\n');
  }

  flush() {
    external_fs_default().writeFileSync(1, this.out);
    this.out = '';
  }

}
;// CONCATENATED MODULE: ./src/cf-1519/1519-a.ts

const io = new IO();

function solve(r, b, d) {
  let min = Math.min(r, b);
  let max = Math.max(r, b);
  let rem = max - min;

  if (rem <= min * d) {
    io.writeLine('YES');
  } else {
    io.writeLine('NO');
  }
}

function main() {
  try {
    let t = io.nextNum();

    while (t--) {
      let r = io.nextNum();
      let b = io.nextNum();
      let d = io.nextNum();
      solve(r, b, d);
    }

    io.flush();
  } catch (e) {
    console.log(e.stack);
  }
}

main();

})();

/******/ })()
;

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

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

let count = -1
let inputArr = []

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

function solve([a, b, d]) {
    const s = Math.min(a, b);
    (Math.abs(a - b) / s <= d) ? console.log('YES') : console.log('NO')
}

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

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

function candyShop(inp){
  let parsedInput = inp.split(' ')
                       .map( el => Number( el.replace(/[^0-9]/g, '') ) );

  if( parsedInput.length === 1 ) return null

  let [redAmount, blueAmount, maxDif] = [...parsedInput];
  if(maxDif===0) return redAmount===blueAmount ? 'yes' : 'no';
  let [min, max] = [Math.min(redAmount, blueAmount), Math.max(redAmount, blueAmount)];
  if( Math.floor(max/min) <= maxDif ){ return 'yes'}
  else return 'no'
}

rl.on('line', (input) => {
  let i = candyShop(input);
  if(i != null ){ console.log(i) }
});

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

function candyShop(inp){
  let parsedInput = inp.split(' ')
                       .map( el => Number( el.replace(/[^0-9]/g, '') ) );

  if( parsedInput.length === 1 ) return 'no'

  let [redAmount, blueAmount, maxDif] = [...parsedInput];
  if(maxDif===0) return redAmount===blueAmount ? 'yes' : 'no';
  let [min, max] = [Math.min(redAmount, blueAmount), Math.max(redAmount, blueAmount)];
  if( Math.floor(max/min) <= maxDif ){ return 'yes'}
  else return 'no'
}

rl.on('line', (input) => {
  console.log( candyShop(input) )
});

const readline = require('readline');

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

function candyShop(redAmount, blueAmount, maxDif){
  if(maxDif===0) return redAmount===blueAmount ? console.log('yes') : console.log('no');
  if(Math.abs(redAmount-blueAmount)>maxDif) return console.log('no');
  if(redAmount<1 || blueAmount<1) return console.log('no');
  return console.log('yes')
}

rl.on('line', (input) => {
  if(input.length>1){ candyShop(input) }
});

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
var __webpack_exports__ = {};

;// CONCATENATED MODULE: ./src/io.js
var interact = function interact(main) {
  process.stdin.resume();
  process.stdin.setEncoding('utf-8');
  var inputString = '';
  var currentLine = 0;

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

  var print = function print() {
    for (var _len = arguments.length, any = new Array(_len), _key = 0; _key < _len; _key++) {
      any[_key] = arguments[_key];
    }

    process.stdout.write(any.join(' '));
  };

  var println = function println() {
    for (var _len2 = arguments.length, any = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      any[_key2] = arguments[_key2];
    }

    any.length > 0 && print(any);
    print('\n');
  };

  var obj = {
    print: print,
    println: println,
    readline: readline
  };
  process.stdin.on('data', function (inputStdin) {
    inputString += inputStdin;
  });
  process.stdin.on('end', function () {
    inputString = inputString.trim().split('\n').map(function (string) {
      return string.trim();
    });
    main(obj);
  });
};

/* harmony default export */ const io = (interact);
;// CONCATENATED MODULE: ./src/index.js
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

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

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

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

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

var main = function main(io) {
  var tc = Number.parseInt(io.readline());

  while (tc--) {
    var _io$readline$split$ma = io.readline().split(' ').map(function (x) {
      return Number.parseInt(x);
    }),
        _io$readline$split$ma2 = _slicedToArray(_io$readline$split$ma, 3),
        r = _io$readline$split$ma2[0],
        b = _io$readline$split$ma2[1],
        d = _io$readline$split$ma2[2];

    if (r > d) {
      var temp = r;
      r = b;
      b = temp;
    } // assert r <= b

    var sat = b <= r * (1 + d);
    io.println(sat ? 'YES' : 'NO');
  }
};

io(main);
/******/ })()
;

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

    while(testCases--)
    {
        const [r,b,d] = get_ints();

        if(r === b)
        {
            print('YES');
            continue;
        }
        const min = Math.min(r,b);
        const max = Math.max(r,b);
        Math.ceil(max/min) > d ? print('NO') : print('YES')

    }
});

function print(c){
    return console.log(c);
}

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

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

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

let currentLine = 0;
let inputString = "";

process.stdin.on("data", (raw_data) => {
  inputString += raw_data;
});

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

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

/******** Main function *************/

function main() {
  const t = +input();

  for (var i = 0; i < t; i++) {
    const [r, b, d] = input().split(" ").map(Number);

    const min = Math.min(r, b);
    const max = Math.max(r, b);

    const x = Math.floor(max / min);
    const y = Math.ceil(max / min);

    if (d === 0) {
      if (r === b) {
        console.log("YES");
      } else {
        console.log("NO");
      }
    } else if (d === 1) {
      if (Math.abs(max - min) > d) {
        console.log("NO");
      } else {
        console.log("YES");
      }
    } else if (min === 1) {
      if (max > d) {
        console.log("NO");
      } else {
        console.log("YES");
      }
    } else {
      if (Math.abs(x - y) > d) {
        console.log("NO");
      } else {
        console.log("YES");
      }
    }
  }
}


There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have $$$b$$$ buns, $$$p$$$ beef patties and $$$f$$$ chicken cutlets in your restaurant. You can sell one hamburger for $$$h$$$ dollars and one chicken burger for $$$c$$$ dollars. Calculate the maximum profit you can achieve.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains three integers $$$b$$$, $$$p$$$ and $$$f$$$ ($$$1 \le b, ~p, ~f \le 100$$$) — the number of buns, beef patties and chicken cutlets in your restaurant. The second line of each query contains two integers $$$h$$$ and $$$c$$$ ($$$1 \le h, ~c \le 100$$$) — the hamburger and chicken burger prices in your restaurant.

For each query print one integer — the maximum profit you can achieve.

NoteIn first query you have to sell two hamburgers and three chicken burgers. Your income is $$$2 \cdot 5 + 3 \cdot 10 = 40$$$.In second query you have to ell one hamburgers and two chicken burgers. Your income is $$$1 \cdot 10 + 2 \cdot 12 = 34$$$.In third query you can not create any type of burgers because because you have only one bun. So your income is zero.

var queries = readline();
for(var i = 0; i < queries; i++){
    var quantities = readline().split(' ');
    var b = parseInt(quantities[0]);
    var p = parseInt(quantities[1]);
    var f = parseInt(quantities[2]);

    var prices = readline().split(' ');
    var h = parseInt(prices[0]);
    var c = parseInt(prices[1]);

    var possibleBurgers = ~~(b / 2);
    //print("Burgers possible: " + possibleBurgers);

    if(h <= c){
        //print("Value of h and c: " + h + c);
        if(f >= possibleBurgers){
            print(possibleBurgers * c);
        }
        else{
            var h_bur_profit;
            var c_bur_profit = f * c;
            var remaining_possible_burgers = possibleBurgers - f;
            if(p <= remaining_possible_burgers){
                h_bur_profit = p * h;
            }
            else{
                h_bur_profit = remaining_possible_burgers * h;
            }
            print(h_bur_profit + c_bur_profit);
        }
    }
    else if(h > c){
        //print("Value of p and possible burgers: " + p + possibleBurgers);
        if(p >= possibleBurgers){
            print(possibleBurgers * h);
        }
        else{
            var h_bur_profit = p * h;
            var c_bur_profit;
            var remaining_possible_burgers = possibleBurgers - p;
            if(f <= remaining_possible_burgers){
                c_bur_profit = f * c;
            }
            else{
                c_bur_profit = remaining_possible_burgers * c;
            }
            print(h_bur_profit + c_bur_profit);
        }
    }
    else{
        print("0");
    }
}

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

var main = function() {"use strict";
    // TODO
    var t = rdN();
    while (t --> 0) {
        var input = rdArN();
        var b = input[0];
        var p = input[1];
        var f = input[2];
        var input = rdArN();
        var h = input[0];
        var c = input[1];

        if (h < c) {
            var buf = p;
            p = f;
            f = buf;
            var buf = h;
            h = c;
            c = buf;
        }
        var stack = crAr(p, h).concat(crAr(f, c)).reverse();
        var res = 0;
        while (b >= 2 && stack.length) {
            res += stack.pop();
            b -= 2;
        }
        pr(res);
    }
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();

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

const solve = () => {
  let ans = 0;
  const arr1 = new Array(p).fill(h);
  const arr2 = new Array(f).fill(c);

  for (let i = 1; i < b; i += 2) {
    if (h >= c) {
      ans += arr1.length ? arr1.pop() : arr2.pop() || 0;
    }
    else {
      ans += arr2.length ? arr2.pop() : arr1.pop() || 0;
    }
  }

  console.log(ans);
}

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

  if (count % 2 === 1) {
    [b, p, f] = d.split(' ').map(Number);
  }
  else {
    [h, c] = d.split(' ').map(Number);

    solve();
  }

  count++;
});

'use strict';

let inputStr = '';
let lines = [];

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

process.stdin.on('end', () => {
  lines = inputStr.split('\n');
  lines.pop();
  main();
});

function main() {
  let b,p,f,h,c;
  for (let i = 1; i < lines.length; i += 2) {
    let curr = lines[i].split(' ');
    let total = 0;
    b = Math.floor(parseInt(curr[0], 10) / 2);
    p = parseInt(curr[1], 10);
    f = parseInt(curr[2], 10);
    curr = lines[i+1].split(' ');
    h = parseInt(curr[0], 10);
    c = parseInt(curr[1], 10);

    if (h > c) {
      while (b > 0 && p-- > 0) {
        total += h;
        b--;
      }
      while (b > 0 && f-- > 0) {
        total += c;
        b--;
      }
    } else {
      while (b > 0 && f-- > 0) {
        total += c;
        b--;
      }
      while (b > 0 && p-- > 0) {
        total += h;
        b--;
      }
    }

    console.log(total);
  }
}

var queries = readline();
for(var i = 0; i < queries; i++){
    var quantities = readline().split(' ');
    var b = quantities[0];
    var p = quantities[1];
    var f = quantities[2];

    var prices = readline().split(' ');
    var h = prices[0];
    var c = prices[1];

    var possibleBurgers = ~~(b / 2);
    //print("Burgers possible: " + possibleBurgers);

    if(possibleBurgers != 0 && h < c){
        if(f >= possibleBurgers){
            print(possibleBurgers * c);
        }
        else{
            var h_bur_profit;
            var c_bur_profit = f * c;
            var remaining_possible_burgers = possibleBurgers - f;
            if(p <= remaining_possible_burgers){
                h_bur_profit = p * h;
            }
            else{
                h_bur_profit = remaining_possible_burgers * h;
            }
            print(h_bur_profit + c_bur_profit);
        }
    }
    else if(possibleBurgers != 0 && h > c){
        if(p >= possibleBurgers){
            print(possibleBurgers * h);
        }
        else{
            var h_bur_profit = p * h;
            var c_bur_profit;
            var remaining_possible_burgers = possibleBurgers - p;
            if(f <= remaining_possible_burgers){
                c_bur_profit = f * c;
            }
            else{
                c_bur_profit = remaining_possible_burgers * c;
            }
            print(h_bur_profit + c_bur_profit);
        }
    }
    else{
        print("0");
    }
}