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

let c = 0;
let alpha;

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

  if (c % 2 === 1) {
    alpha = d;
    c++;
    return;
  }

  let ans = 0;
  const idxes = [];
  const word = d;

  for (let i = 0; i < word.length; i++) {
    const idx = alpha.indexOf(word[i]);
    idxes.push(idx);
  }

  for (let i = 1; i < idxes.length; i++) {
    ans += Math.abs(idxes[i - 1] - idxes[i]);
  }

  console.log(ans);
  c++;
});

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

function findSum (input, alphabetIndex, wordIndex) {
  const alphabet = input[alphabetIndex];
  const word = input[wordIndex];
  if (word.length === 1) return 0;
  const map = new Map();
  let sum = 0;
  for (let i = 0; i < alphabet.length; i++)
  {
        map.set(alphabet[i], i + 1);
  }
  for (let i = 1; i < word.length; i++)
  {
    sum += Math.abs(map.get(word[i - 1]) - map.get(word[i]));
  }
  return sum;
}

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const input = i.split(EOL);
  const n = input[0];
  let alphabetIndex = 1;
  let wordIndex = 2;
  for (let i = 0; i < n; i++) {
      console.log(findSum (input, alphabetIndex, wordIndex));
      alphabetIndex += 2;
      wordIndex += 2;
  }

})

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 * 2
        } else if (count !== 0) {
            inputArr.push(data.trim())
            count--
        }
        // max number 2^(53) - 1 ~~ 10^(15)
        if (count === 0) {
            main()
            process.exit(0)
        }
    }
)

function solve(keyboard, str) {
    str = str.split('')
    let res = 0
    for (let i = 0; i < str.length - 1; ++i) {
        res += Math.abs((keyboard.indexOf(str[i]) + 1) - (keyboard.indexOf(str[i + 1]) + 1))
    }
    console.log(res)
}

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function gcd(a, b) {
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
// let a=readline().split(' ').map(Number)
// a.sort((a,b)=>a-b)

function main() {
    let t = Number(readline())
    for (let j = 1; j <= t; j++) {
        let s=readline();
        let n=s.length;
        let x=readline();
        let ans=0;
        let mp=new Map();
        for(let i=0;i<n;i++)
            mp[s[i]]=i;
        let m=x.length;
        for(let i=1;i<m;i++)
            ans+=Math.abs(mp[x[i]]-mp[x[i-1]]);
        console.log(ans);
    }
}

//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 if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
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();
	while(hasNext()){
		var c = next();
		var s = next();
		var output = 0;
		var index = c.indexOf(s[0]);
		for(var i = 1; i < s.length; i++){
			output += Math.abs(index - c.indexOf(s[i]));
			index = c.indexOf(s[i]);
		}
		myout(output);
	}
}

var t = readline();
for (var i=0 ; i < t ; i++){
    var keyboard = readline().split(''),
        word = readline().split(''),
        counter =0;
        for(var j = 0 ; j < word.length-1; j++){
            counter+= Math.abs(parseInt(keyboard.indexOf(word[j+1])) - parseInt(keyboard.indexOf(word[j])));
        }
        print(counter);
}

var testCase = +readline(),counter
for(var i=0;i<testCase;i++){
    var counter=0
    var sequence=readline()
    var test=readline()
    for(var j=0;j<test.length;j++){
            if(j!==0){
                counter=counter+Math.abs((sequence.indexOf(test[j])+1)-(sequence.indexOf(test[j-1])+1))
            }
    }
    print(counter)
}

function getObj(str) {
	var o={};
	for (var i = 0; i < str.length; i++) {
		o[str[i]]=i;
	}
	return o;
}

function ans(str,str2) {
	var hm=getObj(str2);
	var sum=0;
	for (var i = 1; i < str.length; i++) {
		var temp= hm[str[i]]-hm[str[i-1]];
		if(temp<0){
			temp=temp*-1;
		}
		sum+=temp;
	}
	return sum;
}

var a =readline();
for(var i=0;i<a;i++){
    var p=readline();
    var q=readline();
    print(ans(q,p));
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var a = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            a = lines[i].split('');
        }else{
            var b = lines[i].split('');
            var v = new Map();
            for(j = 0; j < a.length; j++){
                v.set(a[j], j);
            }
            var ans = 0;
            for(j = 1; j < b.length; j++){
                var x = v.get(b[j]);
                var y = v.get(b[j - 1]);
                ans += Math.abs(x - y);
            }
            console.log(ans);
        }
    }
});

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    var a = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i].split('');
            a = new Map();
            for(j = 1; j <= n.length; j++){
                a.set(n[j - 1], j);
            }
        }else{
            var k = lines[i].split('');
            var ans = 0;
            var x = 0, y = 0;
            for(j = 1; j < k.length; j++){
                x = a.get(k[j]);
                y = a.get(k[j - 1]);
                ans += Math.abs(x - y);
            }
            console.log(ans);
        }
    }
});

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];
    var a = new Map();
    for(var j = 1; j <= n * 2; j++){
        if(j % 2 == 1){
            a = new Map();
            var keyboard = lines[j];
            for(var l = 1; l < 27; l++){
                a.set(keyboard[l - 1], l);
            }
        }else{
            var word = lines[j];
            var answer = 0;
            var b = 0;
            var c = 0;
            for(var h = 1; h < word.length; h++){
                b = a.get(word[h]);
                c = a.get(word[h - 1]);
                answer += Math.abs(b - c);
            }
            console.log(answer);
        }
    }
});

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

    run(...inputString);
});

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

const input = readline();

function run(...args) {

  const findDistance = (keyboard, word) => {
    const keyboardMap = {};
    for (let i = 0; i <= keyboard.length; i++) {
      if (!keyboardMap[keyboard[i]]) {
        keyboardMap[keyboard[i]] = i + 1;
      }
    }

    let sum = 0;
    for (let i = 0; i < word.length - 1; i++) {
      let firstValue = keyboardMap[word[i]];
      let secondValue = keyboardMap[word[i + 1]];

      if (firstValue > secondValue) {
        sum += firstValue - secondValue;
      } else {
        sum += secondValue - firstValue;
      }
    }
    return sum;
  };

  for (let i = 1; i < args.length - 1; i+=2) {
    const r = findDistance(args[i], args[i + 1]);
    console.log(r)

  }

}

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];
    var a = new Map();
    for(j = 1; j <= n * 2; j++){
        if(j % 2 == 1){
            a = new Map();
            var keyboard = lines[j];
            for(l = 1; l < 27; l++){
                a.set(keyboard[l - 1], l);
            }
        }else{
            var word = lines[j];
            var answer = 0;
            var b = 0;
            var c = 0;
            for(h = 1; h < word.length; h++){
                b = a.get(word[h]);
                c = a.get(word[h - 1]);
                answer += Math.abs(b - c);
            }
            console.log(answer);
        }
    }
});

"use strict";
exports.__esModule = true;
var readline = require("readline");
var process = require("process");
var console_1 = require("console");
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});
var lines = [];
rl.on("line", function (line) {
    lines.push(line);
});
rl.on("close", function () {
    main();
});
function main() {
    for (var i = 1; i < lines.length; i += 2) {
        var time = solve(lines[i], lines[i + 1]);
        console.log(time);
    }
}
function range(start, length) {
    (0, console_1.assert)(length > 0);
    return Array.from(Array(length).keys()).map(function (x) { return x + start; });
}
function solve(keyboard, word) {
    if (word.length <= 1) {
        return 0;
    }
    var keys = Array.from(keyboard);
    var keyIndexes = range(0, keyboard.length);
    var keyMap = new Map(keyIndexes.map(function (i) { return [keys[i], i]; }));
    var wordIndexes = Array.from(word).map(function (c) { return keyMap.get(c); });
    var distances = range(0, word.length - 1).map(function (i) {
        return Math.abs(wordIndexes[i] - wordIndexes[i + 1]);
    });
    var time = distances.reduce(function (x, y) { return x + y; }, 0);
    return time;
}

var readline = require("readline");

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

var lines = [];

rl.on("line", function (line) {
  lines.push(line);
});

rl.on("close", function () {
  for (let i = 1; i < lines.length; i += 2) {
    let time = solve(lines[i], lines[i + 1]);
    console.log(time);
  }
});

function solve(keyboard, s) {
  if (s.length <= 1) {
    return 0;
  }

  let keyboardMap = new Map();
  for (let i = 0; i < keyboard.length; i++) {
    keyboardMap.set(keyboard[i], i);
  }

  letterPositions = [];

  for (let i = 0; i < s.length; i++) {
    letterPositions.push(keyboardMap.get(s[i]));
  }

  let time = 0;
  let handPosition = letterPositions[0];

  for (let i = 1; i < s.length; i++) {
    time += Math.abs(letterPositions[i] - handPosition);
    handPosition = letterPositions[i];
  }

  return time;
}

// cls; cat .\input.txt | node .\script.js
// codium --diff file1.js file2.js
'use strict';
let data = ''; // raw
let inputs = ''; // iterator
function read() { return inputs.next().value.trim(); };

async function solve() {
    let t_1 = (await read()).split('')
    let t_2 = (await read()).split('')
    let keyMap = new Map(t_1.map((e, i) =>
        [e, i + 1]
    ))
    let reduced = t_2.reduce((a, e, i, o) => {
        if (i == 0) return a
        let current = keyMap.get(o[i])
        let previous = keyMap.get(o[i - 1])
        let diff = Math.abs(current - previous)
        return a + diff
    }, 0)
    console.log(reduced)
}

async function main() {
    let tasks_amount = parseInt(await read())
    for (let i = 0; i < tasks_amount; i++) {
        await solve()
    }
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => data += input);
process.stdin.on('end', async () => {
    let splitted = data.split('\r\n')
    inputs = await splitted.values();
    await main();
});

let data = '';
process.stdin.on('data', c => data += c);

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let j = 0; j < t; j++){
		let a = nl.line().split('');
		let b = nl.line().split('');
		let al = {};
		a.forEach((e, i) => al[e] = i);
		let cnt = 0;
		for(let i = 1; i < b.length; i++) {
			cnt += Math.abs(al[b[i]] - al[b[i-1]]);
		}
		ans.push(cnt);
	}
	console.log(ans.join('\n'));
};

process.stdin.on('end', sol);

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

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

function main () {
	let T = rn();
	while (T--) {
		const k = rl();
		const s = rl();

		let ans = 0;
		for (let i = 1; i < s.length; i++) {
			ans += Math.abs(k.indexOf(s[i]) - k.indexOf(s[i-1]));
		}

		console.log(ans);
	}
}

/*
** 1607a Linear Keyboard
*/

// Common Template Starts //
//*
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++];
}
// Common Template Ends //

// LIBRARY START //

const isOdd = (x) => { return x & 1 }
const isEven = (x) => { return !(x & 1) }

const reverseText = (s) => { return s.split('').reverse().join('') }
const hasDuplicates = (str) => (/([a-z])\1/i).test(str)

const hasDuplicateChar = (str, char) => str.indexOf(char) !== str.lastIndexOf(char)

const isSorted = arr => arr.every((v, i, a) => !i || a[i - 1] <= v);

const findAllIndicesOfChar = (str, char) => {
    str = str.split('')
    let indices = [];
    for (let i = 0; i < str.length; i++) {
        if (str[i] === char) indices.push(i);
    }
    return indices
}

const splitAt = index => x => [x.slice(0, index), x.slice(index)]

const isUpper = str => !/[a-z]/.test(str) && /[A-Z]/.test(str)

const escapeRegExp = (string) => string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&')

const replaceAll = (str, find, replace) => str.replace(new RegExp(escapeRegExp(find), 'g'), replace)

const findUnique = (str) => {
    return [...str].reduce((acc, curr) => {
        return acc.includes(curr) ? acc : acc + curr;
    }, "")
}

// LIBRARY END

const tempPrintFunc = (keyboard, word) => {
    keyboard = keyboard.split('')
    word = word.split('')

    let val = 0
    let currChar = word[0]

    while (word.length > 0) {
        nextChar = word.shift()

        curr_pos = keyboard.indexOf(currChar)
        next_pos = keyboard.indexOf(nextChar)

        val += Math.abs(curr_pos - next_pos)

        currChar = nextChar
    }

    return val
}

//*
function main() {
    let cases = readline()

    while (cases--) {
        let keyboard = readline()
        let word = readline()
        console.log(tempPrintFunc(keyboard, word))
    }
}
//*/

// let keyboard = ''
// let word = ''

// keyboard = 'abcdefghijklmnopqrstuvwxyz'
// word = 'hello'
// console.log(tempPrintFunc(keyboard, word) == 13)

// keyboard = 'abcdefghijklmnopqrstuvwxyz'
// word = 'i'
// console.log(tempPrintFunc(keyboard, word) == 0)

// keyboard = 'abcdefghijklmnopqrstuvwxyz'
// word = 'codeforces'
// console.log(tempPrintFunc(keyboard, word) == 68)

// keyboard = 'qwertyuiopasdfghjklzxcvbnm'
// word = 'qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq'
// console.log(tempPrintFunc(keyboard, word) == 0)

// keyboard = 'qwertyuiopasdfghjklzxcvbnm'
// word = 'abacaba'
// console.log(tempPrintFunc(keyboard, word) == 74)

'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() {
    let t = Number(readline())
    for (let j = 1; j <= t; j++) {
        let s=readline();
        let n=s.length;
        let x=readline();
        let ans=0;
        let mp=new Map();
        for(let i=0;i<n;i++)
            mp[s[i]]=i;
        let m=x.length;
        for(let i=1;i<m;i++)
            ans+=Math.abs(mp[x[i]]-mp[x[i-1]]);
        console.log(ans);
    }
}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

function main(){
  let input = Number(readline());
  let output = [];
  for(let i=0; i<input; i++){
    let pattern = readline().replace('\r','');
    let word = readline().replace('\r', '');
    if(word.length===1) output.push('0');
    else output.push(minimalTime(pattern, word))
  }
  for(let j=0; j<output.length; j++){
    print(output[j])
  }
}

function minimalTime(pattern, word){
  let time = 0;
  for(let i=1; i<=(word.length-1); i++){
    time += Math.abs(((pattern.indexOf(word[i-1])+1) - (pattern.indexOf(word[i])+1)));
    }

  return time;
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    var a = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i].split('');
            a = new Map();
            for(j = 1; j <= n.length; j++){
                a.set(n[j - 1], j);
            }
        }else{
            var k = lines[i].split('');
            var ans = 0;
            var x = 0, y = 0;
            for(j = 1; j < k.length; j++){
                x = a.get(k[j]);
                y = a.get(k[j - 1]);
                ans += Math.floor(x - y);
            }
            console.log(ans);
        }
    }
});

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];
    var a = new Map();
    for(var j = 1; j <= n * 2; j++){
        if(j % 2 == 1){
            a = new Map();
            var keyboard = lines[j];
            for(var l = 1; l < 27; l++){
                a.set(keyboard[l], l);
            }
        }else{
            var word = lines[j];
            var answer = 0;
            var b = 0;
            var c = 0;
            for(var h = 1; h < word.length; h++){
                b = a.get(word[h]);
                c = a.get(word[h - 1]);
                answer += Math.abs(b - c);
            }
            if(isNaN(answer)){
                answer = 0;
            }
            console.log(answer);
        }
    }
});

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();
    });
    console.log(typeof inputString)
    run(...inputString);
});

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

const input = readline();

function run(...args) {
  console.log(args[1])
  const findDistance = (keyboard, word) => {
    const keyboardMap = {};
    for (let i = 0; i <= keyboard.length; i++) {
      if (!keyboardMap[keyboard[i]]) {
        keyboardMap[keyboard[i]] = i + 1;
      }
    }

    let sum = 0;
    for (let i = 1; i < word.length - 1; i++) {
      let firstValue = keyboardMap[word[i]];
      let secondValue = keyboardMap[word[i + 1]];

      if (firstValue > secondValue) {
        sum += firstValue - secondValue;
      } else {
        sum += secondValue - firstValue;
      }
    }
    return sum;
  };

  for (let i = 0; i < args.length - 1; i+=2) {
    const r = findDistance(args[i], args[i + 1]);
    console.log(r)

  }

}

function run(t, ...args) {
  const findDistance = (keyboard, word) => {
    const keyboardMap = {};
    for (let i = 0; i <= keyboard.length; i++) {
      if (!keyboardMap[keyboard[i]]) {
        keyboardMap[keyboard[i]] = i + 1;
      }
    }

    let sum = 0;
    for (let i = 0; i < word.length - 1; i++) {
      let firstValue = keyboardMap[word[i]];
      let secondValue = keyboardMap[word[i + 1]];

      if (firstValue > secondValue) {
        sum += firstValue - secondValue;
      } else {
        sum += secondValue - firstValue;
      }
    }
    return sum;
  };
  const res = [];
  for (let i = 0; i < args.length - 1; i+=2) {
    const r = findDistance(args[i], args[i + 1]);
    console.log(r)
    res.push(r);
  }
  return res;
}

run(5,
  'abcdefghijklmnopqrstuvwxyz',
  'hello',
  'abcdefghijklmnopqrstuvwxyz',
  'i',
  'abcdefghijklmnopqrstuvwxyz',
  'codeforces',
  'qwertyuiopasdfghjklzxcvbnm',
  'qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq',
  'qwertyuiopasdfghjklzxcvbnm',
  'abacaba');

function run (t, ...args) {
  const findDistance = (keyboard, word) => {
    const keyboardMap = {};
    for (let i = 0; i <= keyboard.length; i++) {
      if (!keyboardMap[keyboard[i]]) {
          keyboardMap[keyboard[i]] = i+1;
      }
    }

   let sum = 0;
    for (let i =0; i < word.length -1; i++) {
      let firstValue = keyboardMap[word[i]];
      let secondValue = keyboardMap[word[i+1]];

      if (firstValue > secondValue) {
        sum += firstValue -secondValue;
      } else {
        sum += secondValue -firstValue;
      }
    }
    return sum;
  }
 const res = [];
  for (let i = 0; i < args.length - 1; i++) {
     res.push(findDistance(args[i], args[i+1]));
  }
  return res;
}

function run (t, ...args) {
  const findDistance = (keyboard, word) => {
    const keyboardMap = {};
    for (let i = 0; i <= keyboard.length; i++) {
      if (!keyboardMap[keyboard[i]]) {
          keyboardMap[keyboard[i]] = i+1;
      }
    }

   let sum = 0;
    for (let i =0; i < word.length -1; i++) {
      let firstValue = keyboardMap[word[i]];
      let secondValue = keyboardMap[word[i+1]];

      if (firstValue > secondValue) {
        sum += firstValue -secondValue;
      } else {
        sum += secondValue -firstValue;
      }
    }
    return sum;
  }

  for (let i = 0; i < args.length - 1; i++) {
     console.log(findDistance(args[i], args[i+1]));
  }

}

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];
    var a = new Map();
    for(var j = 1; j <= n * 2; j++){
        if(j % 2 == 1){
            a = new Map();
            var keyboard = lines[j];
            for(var l = 1; l < 27; l++){
                a.set(keyboard[l - 1], l);
            }
        }else{
            var word = lines[j];
            var answer = 0;
            var b = 0;
            var c = 0;
            for(var h = 1; h < word.length; h++){
                b = a.get(word[h]);
                c = a.get(word[h - 1]);
                answer += Math.abs(b - c);
            }
            console.log(answer - 1);
        }
    }
});


function main()
{
    var s = readline();
    var ans = "";
    var flag = false,
        quote = false;
    for ( var i = 0; i < s.length; i++ )
    {
        if ( !flag )
        {
            if ( s[i] == "\"" )
            {
                flag = true;
                quote = true;
            }
            else if ( s[i] != " " )
            {
                ans += s[i];
                flag = true;
            }
        }
        else
        {
            if ( quote == true )
            {
                if ( s[i] == "\"" )
                {
                    print("<"+ans+">");
                    ans = "";
                    flag = false;
                    quote = false;
                }
                else
                {
                    ans += s[i];
                }
            }
            else
            {
                if ( s[i] == " " )
                {
                    print("<"+ans+">");
                    ans = "";
                    flag = false;
                    quote = false;
                }
                else
                {
                    ans += s[i];
                }
            }
        }
    }
    if ( ans != "" )
        print("<"+ans+">");
}

main();

;(function () {

	print(function (s, result) {

		s = s.trim().split('');

		var word = '', isQuote = false;

		for (var i = 0, _i = s.length; i < _i; i++) {
			if (s[i] === '"') {
				if (isQuote) {
					result.push(['<', word, '>'].join(''));
					word = '';
				}

				isQuote = !isQuote;
			} else if (isQuote === false && s[i] === ' ') {
				word = word.trim();
				if (word.length) {
					result.push(['<', word, '>'].join(''));
				}
				word = '';
			} else {
				word += s[i];
			}
		}

		if (word.length) {
			result.push(['<', word, '>'].join(''));
		}

		return result.join('\n');

	}(readline(), []));

}.call(this));

//var command = '   firstarg   second   ""   '
var command = readline()
  , quoteOpen = false
  , spaceWas = false;
//print('command: ' + command);
command = ' ' + command;
for (var i = 0, lex = ''; i < command.length; i++) {
    if (command[i] === '"') {
        if (quoteOpen) {
            print("<"+lex+">");
            quoteOpen = false;
            spaceWas = false;
            lex = '';
        } else {
            quoteOpen = true;
            spaceWas = false;
            lex = '';
        }
    } else if (command[i] === ' ') {
        if (!quoteOpen) {
            if (!spaceWas) {
                spaceWas = true;
            } else if (command[i-1] !== ' '){
                print("<"+lex+">");
                lex = '';
            }
        } else {
            lex += command[i];
        }
    } else {
        lex += command[i];
    }
}
if (lex) print("<"+lex+">");

function main()
{
    var s = readline();
    var ans = "";
    var flag = false,
        quote = false;
    for ( var i = 0; i < s.length; i++ )
    {
        if ( s[i] == "\"" )
        {
            if ( quote )
            {
                print("<"+ans+">");
                ans = "";
            }
            quote = !quote;
        }
        else if ( !quote && s[i] == " " )
        {
            if ( ans.length )
            {
                print("<"+ans+">");
                ans = "";
            }
        }
        else
        {
            ans += s[i];
        }
    }
    if ( ans != "" )
        print("<"+ans+">");
}

main();

function main(){
    var s = readline();
    var ans = "";
    var flag = false,
        quote = false;
    for ( var i = 0; i < s.length; i++ ){
        if ( s[i] == "\"" ){
            if ( quote ){
                print("<"+ans+">");
                ans = "";
            }
            quote = !quote;
        }
        else if ( !quote && s[i] == " " ){
            if ( ans.length ){
                print("<"+ans+">");
                ans = "";
            }
        }
        else{
            ans += s[i];
        }
    }
    if ( ans != "" )
        print("<"+ans+">");
}

main();

;(function () {

	print(function (s, result) {

		s = s.trim().split('');

		var word = '', isQuote = false;

		for (var i = 0, _i = s.length; i < _i; i++) {
			if (s[i] === '"') {
				if (isQuote) {
					isQuote = false;
					result.push(['<', word, '>'].join(''));
					word = '';
				} else {
					isQuote = true;
				}
			} else if (isQuote === false && s[i] === ' ') {
				word = word.trim();
				if (word.length) result.push(['<', word, '>'].join(''));
				word = '';
			} else {
				word += s[i];
			}
		}

		return result.join('\n');

	}(readline(), []));

}.call(this));

//var command = '   firstarg   second   ""   '
var command = readline()
  , quoteOpen = false
  , spaceWas = false;

for (var i = 0, lex = ''; i < command.length; i++) {
    if (command[i] === '"') {
        if (quoteOpen) {
            print("<"+lex+">");
            quoteOpen = false;
            spaceWas = false;
            lex = '';
        } else {
            quoteOpen = true;
            spaceWas = false;
            lex = '';
        }
    } else if (command[i] === ' ') {
        if (!quoteOpen) {
            if (!spaceWas) {
                spaceWas = true;
                lex = '';
            } else if (command[i-1] !== ' '){
                print("<"+lex+">");
                lex = '';
            }
        } else {
            lex += command[i];
        }
    } else {
        lex += command[i];
    }
}

//var command = '   firstarg   second   ""   '
var command = readline()
  , quoteOpen = false
  , spaceWas = false;
//print('command: ' + command);
for (var i = 0, lex = ''; i < command.length; i++) {
    if (command[i] === '"') {
        if (quoteOpen) {
            print("<"+lex+">");
            quoteOpen = false;
            spaceWas = false;
            lex = '';
        } else {
            quoteOpen = true;
            spaceWas = false;
            lex = '';
        }
    } else if (command[i] === ' ') {
        if (!quoteOpen) {
            if (!spaceWas) {
                spaceWas = true;
                lex = '';
            } else if (command[i-1] !== ' '){
                print("<"+lex+">");
                lex = '';
            }
        } else {
            lex += command[i];
        }
    } else {
        lex += command[i];
    }
}
if (lex) print("<"+lex+">");

//var command = '   firstarg   second   ""   '
var command = readline()
  , quoteOpen = false
  , spaceWas = false;
//print('command' + command);
for (var i = 0, lex = ''; i < command.length; i++) {
    if (command[i] === '"') {
        if (quoteOpen) {
            print("<"+lex+">");
            quoteOpen = false;
            spaceWas = false;
            lex = '';
        } else {
            quoteOpen = true;
            spaceWas = false;
            lex = '';
        }
    } else if (command[i] === ' ') {
        if (!quoteOpen) {
            if (!spaceWas) {
                spaceWas = true;
                lex = '';
            } else if (command[i-1] !== ' '){
                print("<"+lex+">");
                lex = '';
            }
        } else {
            lex += command[i];
        }
    } else {
        lex += command[i];
    }
}
if (lex) print("<"+lex+">");

//var command = '   firstarg   second   ""   '
var command = readline()
  , quoteOpen = false
  , spaceWas = false;
print('command: ' + command);
for (var i = 0, lex = ''; i < command.length; i++) {
    if (command[i] === '"') {
        if (quoteOpen) {
            print("<"+lex+">");
            quoteOpen = false;
            spaceWas = false;
            lex = '';
        } else {
            quoteOpen = true;
            spaceWas = false;
            lex = '';
        }
    } else if (command[i] === ' ') {
        if (!quoteOpen) {
            if (!spaceWas) {
                spaceWas = true;
            } else if (command[i-1] !== ' '){
                print("<"+lex+">");
                lex = '';
            }
        } else {
            lex += command[i];
        }
    } else {
        lex += command[i];
    }
}
if (lex) print("<"+lex+">");

//var command = '   firstarg   second   ""   '
var command = readline()
  , quoteOpen = false
  , spaceWas = false;
//print('command: ' + command);
for (var i = 0, lex = ''; i < command.length; i++) {
    if (command[i] === '"') {
        if (quoteOpen) {
            print("<"+lex+">");
            quoteOpen = false;
            spaceWas = false;
            lex = '';
        } else {
            quoteOpen = true;
            spaceWas = false;
            lex = '';
        }
    } else if (command[i] === ' ') {
        if (!quoteOpen) {
            if (!spaceWas) {
                spaceWas = true;
            } else if (command[i-1] !== ' '){
                print("<"+lex+">");
                lex = '';
            }
        } else {
            lex += command[i];
        }
    } else {
        lex += command[i];
    }
}
if (lex) print("<"+lex+">");

function main()
{
    var s = readline();
    var ans = "";
    var flag = false,
        quote = false;
    for ( var i = 0; i < s.length; i++ )
    {
        if ( !flag )
        {
            if ( s[i] == "\"" )
            {
                flag = true;
                quote = true;
            }
            else if ( s[i] != " " )
            {
                ans += s[i];
                flag = true;
            }
        }
        else
        {
            if ( quote == true )
            {
                if ( s[i] == "\"" )
                {
                    print("<"+ans+">");
                    ans = "";
                    flag = false;
                    quote = false;
                }
                else
                {
                    ans += s[i];
                }
            }
            else
            {
                if ( s[i] == " " )
                {
                    print("<"+ans+">");
                    ans = "";
                    flag = false;
                    quote = false;
                }
                else
                {
                    ans += s[i];
                }
            }
        }
    }
}

main();


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 testCases = readline();

  for (let i = 0; i < testCases; i++) {
    let size = readline();
    let arr = readline().split(" ").map(Number);

    let max = -1;
    let sum = 0;
    for (let j = 0; j < arr.length; j++) {
      if (arr[j] > max) max = arr[j];
      sum += arr[j];
    }
    let sumMinusMax = sum - max;
    // console.log(sum, max);
    if (sum === 0) {
      console.log(0);
    } else if (sumMinusMax >= max) {
      console.log(1);
    } else {
      console.log(max - sumMinusMax);
    }
  }
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    let max = 0,
      sum = 0;
    for (let i = 0; i < n; i++) {
      max = Math.max(max, arr[i]);
      sum += arr[i];
    }
    if (sum === 0) console.log(0);
    else {
      sum = sum - max;
      if (sum >= max - 1) console.log(1);
      else console.log(1 + (max - sum - 1));
    }
  }
};
solve();

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let mx = Math.max(...a);

		let sum = 0;
		for (let i = 0; i < n; i++) sum += a[i];
		sum -= mx;

		let ans;
		if (mx == 0) ans = 0;
		else if (sum >= mx) ans = 1;
		else ans = mx - sum;

		console.log(ans);
	}
}

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		a.sort((x, y) => x - y);

		let sum = 0;
		for (let i = 0; i < n - 1; i++) sum += a[i];

		let ans = 0;
		if (sum + a[n-1])
			ans = 1 + Math.max(a[n-1] - sum - 1, 0);

		console.log(ans);
	}
}

//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 if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
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();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var map = {};
		var max = 0;
		var K = 0;
		for(var i = 0; i < N; i++){
			K += list[i];
			max = Math.max(max, list[i]);
		}
		if(K == 0){
			myout(0);
			continue;
		}
		var output = 0;
		for(var i = 0; i < N; i++){
			output = Math.max(output, max - 1 - (K - list[i]));
		}
		myout(output + 1);
	}
}

function solve() {
   const n = Number(read());
   const arr = readArray(BigInt);
   let maxNum = 0n;
   let sumNum = 0n;
   for (const x of arr) {
      sumNum += x;
      if (x > maxNum) {
         maxNum = x;
      }
   }
   if (sumNum === 0n) {
      write(0);
      return;
   }
   sumNum -= maxNum;
   if (maxNum <= sumNum + 1n) {
      write(1);
      return;
   }
   write(maxNum - sumNum);
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function pDivCount(n) {
   let ans = 0;
   let i = 1;
   while(n > 1) {
      i++;
      while(n % i === 0) {
         ans++;
         n = Math.floor(n / i);
      }
   }
   return ans;
}

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

function lcm(a, b) {
   return Math.floor(a / gcd(a, b)) * b;
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e);
   }
}

function readArray(mapF) {
   var res = read().split(' ');
   if (mapF) {
      res = res.map(mapF);
   }
   return res;
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
   MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\r\n');
}
init();

function write(value) {
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   if (isNode) {
      return MEMORY;
   }
   var res = [];
   var x;
   while (x = read()) {
      res.push(x);
   }
   return res;
}

function readLineNums () {
  return readline().split(' ').map(x => parseInt(x));
}

// ***** PROBLEM SOLUTION *****

var n = readLineNums();

while (n--) {
  readLineNums();
  var passes = readLineNums();

  if ( !passes.some(pass => pass !== 0) ) {
    print(0);
    continue;
  }
  var max = passes.reduce((max, num) => (num > max) ? num : max, -1);
  var sum = passes.reduce((sum, num) => (num + sum), 0);

  var remaining = sum - max;

  if (remaining >= max) {
    print(1);
  } else {
    print(2 * max - sum);
  }
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    arr.sort((a, b) => b - a);
    if (arr[0] === 0) {
      console.log(0);
      continue;
    }
    let ans = 0;
    for (let i = 1; i < n; i++) {
      let dif = Math.abs(arr[i] - arr[i - 1]);
      if (dif <= 0) arr[i] = 1;
      else arr[i] = dif;
    }
    if (arr[n - 1] <= 1) console.log(1);
    else console.log(arr[n - 1]);
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    arr.sort((a, b) => b - a);
    if (arr[0] === 0) {
      console.log(0);
      continue;
    }
    let ans = 0;
    for (let i = 1; i < n; i++) {
      let dif = Math.abs(arr[i] - arr[i - 1]);
      if (dif <= 0) arr[i] = 0;
      else arr[i] = dif;
    }
    if (arr[n - 1] <= 1) console.log(1);
    else console.log(arr[n - 1]);
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    arr.sort((a, b) => b - a);
    if (arr[n - 1] === 0) {
      console.log(0);
      continue;
    }
    let ans = 0;
    for (let i = 1; i < n; i++) {
      let dif = Math.abs(arr[i] - arr[i - 1]);
      if (dif <= 0) arr[i] = 0;
      else arr[i] = dif;
    }
    if (arr[n - 1] <= 1) console.log(1);
    else console.log(arr[n - 1]);
  }
};
solve();

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		a.sort((x, y) => x - y);

		let sum = 0;
		for (let i = 0; i < n - 1; i++) sum += a[i];

		let ans = 0;
		if (sum)
			ans = 1 + Math.max(a[n-1] - sum - 1, 0);

		console.log(ans);
	}
}


var readline=require('readline');
var rl=readline.createInterface(process.stdin,process.stdout);
var n=-1;
var checker=0;
var mySet=new Set();
rl.on('line', lineInput => {
    if(n==-1){
      n=parseInt(lineInput);
    }
    else{
      mySet.add(lineInput);
      checker++;
      if(checker==n){
      console.log(mySet.size);
      rl.close();
      }
    }

});

/*  inputs.push(lineInput);
const n=parseInt(lineInput);
for(let i=0; i<n; i++){
  mySet.add(lineInput);
}
Console.log(mySet.size());*/

'use strict'

let N = +readline()
let lll

let ls = new Set
while (lll = readline()) {
  ls.add(lll)
}

print(ls.size)


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

'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
}

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
}