package main

import (
	"fmt"
	"math"
)

func solve(keyboard string, word string) {
	chr_to_pos := make(map[byte]int)
	for i := 0; i < len(keyboard); i++ {
		chr_to_pos[keyboard[i]] = i
	}
	r := 0
	for i := 1; i < len(word); i++ {
		prev := chr_to_pos[word[i-1]]
		cur := chr_to_pos[word[i]]
		r += int(math.Abs(float64(prev - cur)))
	}
	fmt.Println(r)
}

func main() {
	var tc int
	fmt.Scan(&tc)
	for i := 0; i < tc; i++ {
		var keyboard, word string
		fmt.Scan(&keyboard, &word)
		solve(keyboard, word)
	}
}

package main

import (
    "bufio"
    "fmt"
    "os"
)

var scan = fmt.Fscan
var println = fmt.Fprintln

var in *bufio.Reader
var out *bufio.Writer
func init(){
    in = bufio.NewReader(os.Stdin)
    out = bufio.NewWriter(os.Stdout)
}

func abs(a int) int{
	if(a<0){return -a}
	return a
}

func main() {
	var t int; scan(in,&t)
	for ;t>0;t-- {
		var a,b string; scan(in,&a,&b)
		m := len(b); v := make([]int,26); ans := 0

		for i,c := range(a) {v[c-'a']=i;}

		var aux int
		for i:=1;i<m;i++ {
			aux = abs((v[b[i]-'a']-v[b[i-1]-'a']))
			ans += aux
		}
		println(out,ans)
	}
	out.Flush()
}

package main

import (
    "bufio"
    "fmt"
    "os"
	"math"
)

func main() {
    in := bufio.NewReader(os.Stdin)
    out := bufio.NewWriter(os.Stdout)
	var t int
	fmt.Fscan(in,&t)
	for ;t>0;t-- {
		var a,b string
		fmt.Fscan(in,&a,&b)
		v := make([]int,26)
		for i,c := range(a) {v[c-'a']=i;}
		m := len(b)
		ans := 0
		var aux int
		for i:=1;i<m;i++ {
			aux = int(math.Abs(float64(v[b[i]-'a']-v[b[i-1]-'a'])))
			ans += aux
		}
		fmt.Fprintln(out,ans)
	}
	out.Flush()
}

package main

import (
    "bufio"
    "fmt"
    "os"
	"math"
)

func main() {
    in := bufio.NewReader(os.Stdin)
    out := bufio.NewWriter(os.Stdout)
	var t int
	fmt.Fscanf(in,"%d\n",&t)
	for ;t>0;t-- {
		var a,b string
		fmt.Fscanf(in,"%s\n%s\n",&a,&b)
		v := make([]int,26)
		for i,c := range(a) {v[c-'a']=i;}
		m := len(b)
		ans := 0
		var aux int
		for i:=1;i<m;i++ {
			aux = int(math.Abs(float64(v[b[i]-'a']-v[b[i-1]-'a'])))
			ans += aux
		}
		fmt.Fprintf(out,"%d\n",ans)
	}
	out.Flush()
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int
	fmt.Scanf("%d\n",&t)
	for ;t>0;t-- {
		var a,b string
		fmt.Scanf("%s\n%s\n",&a,&b)
		v := make([]int,26)
		for i,c := range(a) {v[c-'a']=i;}
		m := len(b)
		ans := 0
		var aux int
		for i:=1;i<m;i++ {
			aux = int(math.Abs(float64(v[b[i]-'a']-v[b[i-1]-'a'])))
			ans += aux
		}
		fmt.Printf("%d\n",ans)
	}
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int
	fmt.Scanf("%d\n",&t)
	for ;t>0;t-- {
		var a,b string
		fmt.Scanf("%s\n%s\n",&a,&b)
		v := make([]int,26)
		for i,c := range(a) {v[c-'a']=i;}
		m := len(b)
		ans := 0
		var aux int
		for i:=1;i<m;i++ {
			aux = int(math.Abs(float64(v[b[i]-'a']-v[b[i-1]-'a'])))
			ans += aux
		}
		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
	"math"
)

func Abs(a, b int) int {
	return int(math.Abs(float64(a) - float64(b)))
}

func main() {
	var cnt int
	_, err := fmt.Scanln(&cnt)
	if err != nil {
		fmt.Println(err)
		return
	}
	for i := 0; i < cnt; i++ {
		var keyboard string
		var word string
		sum := 0
		_, err = fmt.Scanln(&keyboard)
		if err != nil {
			fmt.Println(err)
			return
		}
		_, err = fmt.Scanln(&word)
		if err != nil {
			fmt.Println(err)
			return
		}
		keyMap := make(map[rune]int)
		for order, val := range keyboard {
			keyMap[val] = order + 1
		}
		for index := 0; index + 1 < len(word); index++ {
			sum += Abs(keyMap[rune(word[index])], keyMap[rune(word[index+1])])
		}
		fmt.Println(sum)
	}
}

package main

import (
	"fmt"
	"math"
)

func solve(keyboard string, word string) {
	chr_to_pos := make(map[byte]int)
	for i, b := range keyboard {
		chr_to_pos[byte(b)] = i
	}
	r := 0
	for i, b := range word {
		if i+1 == len(word) {
			break
		}
		r += int(math.Abs(float64(chr_to_pos[byte(b)] - chr_to_pos[word[i+1]])))
	}
	fmt.Println(r)
}

func main() {
	var tc int
	fmt.Scan(&tc)
	for i := 0; i < tc; i++ {
		var keyboard, word string
		fmt.Scan(&keyboard, &word)
		solve(keyboard, word)
	}
}

package main

import (
	"fmt"
)
import "math"
func main() {
	var test int
  fmt.Scanf("%d\n",&test)
  for i:=0;i<test;i++{
    var alphaorder string
    fmt.Scanf("%s\n",&alphaorder)
    var input string
    fmt.Scanf("%s\n",&input)
    var maphere map[string]float64=make(map[string]float64)
    for j:=0.0;j<float64(len(alphaorder));j++{
      maphere[string(alphaorder[int(j)])]=j+1.0
    }
    var result int=0
    for i:=0;i<len(input)-1;i++{
      result+=int(math.Abs(maphere[string(input[i])]-maphere[string(input[i+1])]))
    }
    fmt.Println(result)
  }
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	defer ot.Flush()
	t := rnI()
	for ; t != 0; t-- {
		s, a := rnS(), rnS()

		res := 0
		for i := 1; i < len(a); i++ {
			res += abs(strings.Index(s, string(a[i])) - strings.Index(s, string(a[i-1])))
		}
		fmt.Fprintln(ot, res)
	}

}

/* ======================================================================== */
//
//
//
//							 _____   _   _   ____
//							| ____| | \ | | |  _ \
//							|  _|   |  \| | | | | |
//							| |___  | |\  | | |_| |
//							|_____| |_| \_| |____/
//
//
//
/* ============================PART 1: I/O ================================== */

var (
	ot = bufio.NewWriterSize(os.Stdout, int(1e6))
	in = bufio.NewScanner(os.Stdin)
)

func init()        { in.Split(bufio.ScanWords); in.Buffer(make([]byte, 4096), int(1e9)) }
func rnS() string  { in.Scan(); return in.Text() }
func rnI() int     { i, _ := strconv.Atoi(rnS()); return i }
func rnF() float64 { f, _ := strconv.ParseFloat(rnS(), 64); return f }

func rsI(l, r int) []int {
	t := make([]int, r)
	for i := l; i < r; i++ {
		t[i] = rnI()
	}
	return t
}

/* ===========================PART 2: Math Func ============================  */
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}
func abs(x int) int {
	if x > 0 {
		return x
	}
	return -x
}
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}
func memset(a []int, v int) {
	if len(a) == 0 {
		return
	}
	a[0] = v
	for bp := 1; bp < len(a); bp *= 2 {
		copy(a[bp:], a[:bp])
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	defer ot.Flush()
	sign := make(map[byte]int)
	t := rnI()
	for ; t != 0; t-- {
		s, a := rnS(), rnS()
		for i := 0; i < len(s); i++ {
			sign[s[i]] = i + 1
		}

		res := 0
		for i := 1; i < len(a); i++ {
			res += abs(sign[a[i]] - sign[a[i-1]])
		}
		fmt.Fprintln(ot, res)
	}

}

/* ======================================================================== */
//
//
//
//							 _____   _   _   ____
//							| ____| | \ | | |  _ \
//							|  _|   |  \| | | | | |
//							| |___  | |\  | | |_| |
//							|_____| |_| \_| |____/
//
//
//
/* ============================PART 1: I/O ================================== */

var (
	ot = bufio.NewWriterSize(os.Stdout, int(1e6))
	in = bufio.NewScanner(os.Stdin)
)

func init()        { in.Split(bufio.ScanWords); in.Buffer(make([]byte, 4096), int(1e9)) }
func rnS() string  { in.Scan(); return in.Text() }
func rnI() int     { i, _ := strconv.Atoi(rnS()); return i }
func rnF() float64 { f, _ := strconv.ParseFloat(rnS(), 64); return f }

func rsI(l, r int) []int {
	t := make([]int, r)
	for i := l; i < r; i++ {
		t[i] = rnI()
	}
	return t
}

/* ===========================PART 2: Math Func ============================  */
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}
func abs(x int) int {
	if x > 0 {
		return x
	}
	return -x
}
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}
func memset(a []int, v int) {
	if len(a) == 0 {
		return
	}
	a[0] = v
	for bp := 1; bp < len(a); bp *= 2 {
		copy(a[bp:], a[:bp])
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	var (
		t int
		a string
		s string
	)
	fmt.Scanf("%d\n", &t)
	scanner := bufio.NewScanner(os.Stdin)
	for i := 0; i < t; i++ {
		r := 0
		scanner.Scan()
		a = scanner.Text()
		scanner.Scan()
		s = scanner.Text()
		sl := strings.Split(s, "")
		m := AlphToMap(a)
		for j := 1; j < len(sl); j++ {
			k1 := m[sl[j-1]]
			k2 := m[sl[j]]
			if k1 > k2 {
				r = r + k1 - k2
			} else {
				r = r + k2 - k1
			}
		}
		fmt.Println(r)
	}
}

func AlphToMap(s string) (res map[string]int) {
	dict := make(map[string]int)
	sl := strings.Split(s, "")
	for i := 0; i < len(sl); i++ {
		dict[sl[i]] = i
	}
	res = dict
	return
}

package main
import(
    "fmt"
    "strings"
)
func main() {
	var t int
	fmt.Scan(&t)
	for i:=0;i<t;i++{
		var alphabet,word string
		fmt.Scan(&alphabet,&word)
		strings.Split(alphabet,"")
		input_map:= make(map[string]int,len(alphabet))
		for j:=0;j<len(alphabet);j++{
			input_map[string(alphabet[j])] = j
		}
		counter:=0
		for j:=1;j<len(word);j++{
			counter+=abs(input_map[string(word[j])]-input_map[string(word[j-1])])
		}
		fmt.Println(counter)
	}
}

func abs(x int) int {
	var result int
	if x > 0 {
		result = x
	} else {
		if x < 0 {
			result = x*-1
		}
	}
	return result
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

func (sc *A) run() {
	n := sc.nextInt()
	for t := 0; t < n; t++ {
		key := sc.nextString()
		arr := make([]int, 128)
		for i := 0; i < len(key); i++ {
			arr[key[i]] = i + 1
		}
		str := sc.nextString()
		sum := 0
		for i := 1; i < len(str); i++ {
			sum += int(math.Abs(float64(arr[str[i]] - arr[str[i-1]])))
		}
		fmt.Println(sum)
	}
}

func main() {
	file, err := os.Open("input.txt")
	var F *bufio.Reader
	if err == nil {
		F = bufio.NewReader(file)
		os.Stdin = file
	} else {
		F = bufio.NewReader(os.Stdin)
	}
	defer func(file *os.File) {
		_ = file.Close()
	}(file)
	NewA(F).run()
}

func NewA(r *bufio.Reader) *A {
	return &A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

type A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (sc *A) nextLine() string {
	line, err := sc.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	sc.split = []string{}
	sc.index = 0
	return line
}

func (sc *A) load() {
	if len(sc.split) <= sc.index {
		sc.split = strings.Split(sc.nextLine(), sc.separator)
		sc.index = 0
	}
}

func (sc *A) nextInt() int {
	sc.load()
	val, _ := strconv.Atoi(strings.TrimSpace(sc.split[sc.index]))
	sc.index++
	return val
}

func (sc *A) nextInt64() int64 {
	sc.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(sc.split[sc.index]), 10, 64)
	sc.index++
	return val
}

func (sc *A) nextString() string {
	sc.load()
	val := strings.TrimSpace(sc.split[sc.index])
	sc.index++
	return val
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func mod(a int) int {
	if a > 0 {
		return a
	} else {
		return -1 * a
	}
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)

	test := parseInt(getString(reader))
	for ; test > 0; test-- {
		arrangement := getString(reader)
		arg := make(map[byte]int)
		for i := 0; i < 26; i++ {
			arg[arrangement[i]] = i
		}
		word := getString(reader)
		size := len(word)
		res := 0
		for i := 1; i < size; i++ {
			res += mod(arg[word[i]] - arg[word[i-1]])
		}
		writer.WriteString(fmt.Sprintln(res))
	}
	writer.Flush()
}

func parseInt(str string) int {
	var res int
	size := len(str)
	for i := 0; i < size; i++ {
		digit := int(str[i] - '0')
		for j := (i + 1); j < size; j++ {
			digit = digit<<3 + digit<<1
		}
		res += digit
	}
	return res
}

func getString(in *bufio.Reader) string {
	res, _ := in.ReadString('\n')
	res = strings.ReplaceAll(res, "\n", "")
	res = strings.ReplaceAll(res, "\r", "")
	res = strings.TrimSpace(res)
	return res
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func abs(n int) int {
	if n < 0 {
		return n * -1
	}
	return n
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)

	for t := 0; t < T; t++ {
		var keys, s string
		fmt.Fscan(in, &keys, &s)

		vals := make([]rune, 26)
		for i, v := range keys {
			vals[i] = v
		}

		dist := func(r rune) int {
			for i, ch := range vals {
				if ch == r {
					return i
				}
			}
			return -1
		}

		var total int
		pos := dist(rune(s[0]))
		for i := 1; i < len(s); i++ {
			p2 := dist(rune(s[i]))
			total += abs(p2 - pos)
			pos = p2
		}

		fmt.Fprintln(out, total)
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func Abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, s, alps := 0, "", ""
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &alps, &s)
		o, tot := make([]int, len(s)), 0
		for j := 0; j < len(s); j++ {
			o[j] = strings.Index(alps, string(s[j])) + 1
		}
		for j := 1; j < len(s); j++ {
			tot += Abs(o[j] - o[j-1])
		}
		fmt.Fprintln(w, tot)
	}
	w.Flush()
}

func main() {
	solve()
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	reader = bufio.NewReader(os.Stdin)
	t      int
	k, s   string
)

func solve(k, s string) int {
	res := 0
	keyboard := make(map[byte]int)
	for i, c := range k {
		keyboard[byte(c)] = i
	}
	for i := 1; i < len(s); i++ {
		diff := keyboard[s[i]] - keyboard[s[i-1]]
		if diff < 0 {
			diff = - diff
		}
		res += diff
	}
	return res
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &k, &s)
		fmt.Println(solve(k, s))
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	reader = bufio.NewReader(os.Stdin)
	t      int
	k, s   string
)

func solve(k, s string) int {
	var r int
	x := make(map[byte]int)
	for i, c := range k {
		x[byte(c)] = i
	}
	for i := 1; i < len(s); i++ {
		diff := x[s[i]] - x[s[i-1]]
		if diff < 0 {
			diff = -diff
		}
		r += diff
	}
	return r
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &k, &s)
		fmt.Println(solve(k, s))
	}
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

type CF1607A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1607A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1607A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1607A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1607A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1607A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1607A
Date: 17/11/21
User: pepradere
URL: https://codeforces.com/problemset/problem/1607/A
Problem: CF1607A
**/
func (in *CF1607A) Run() {
	t := in.NextInt()
	for ; t > 0; t-- {
		str := in.NextString()
		mapa := make(map[uint8]int)
		for i := 0; i < len(str); i++ {
			mapa[str[i]] = i
		}
		line := in.NextString()
		ans := 0
		for i := 1; i < len(line); i++ {
			ans += int(math.Abs(float64(mapa[line[i]] - mapa[line[i-1]])))
		}
		fmt.Println(ans)
	}
}

func NewCF1607A(r *bufio.Reader) *CF1607A {
	return &CF1607A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1607A(bufio.NewReader(os.Stdin)).Run()
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Scan()
	t, _ := strconv.Atoi(sc.Text())
	for i := 0; i < t; i++ {
		sc.Scan()
		keyboard := sc.Text()
		sc.Scan()
		st := sc.Text()
		ans := 0
		lastPos := strings.Index(keyboard, st[0:1])
		for j := 1; j < len(st); j++ {
			curPos := strings.Index(keyboard, st[j:(j+1)])
			ans += int(math.Abs(float64(curPos - lastPos)))
			lastPos = curPos
		}
		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
	"math"
	"strings"
)

func main() {
	var t int
	fmt.Scanln(&t)
	//fmt.Println("t =", t)
	for i := 0; i < t; i++ {
		//fmt.Println("---------------------")
		var ss string
		fmt.Scanln(&ss)

		//fmt.Println("ss =", ss)

		var s string
		var sum float64 = 0
		fmt.Scanln(&s)
		//fmt.Println(s)
		for j := 1; j < len(s); j++ {
			sum += math.Abs(float64(strings.Index(ss, string(s[j])) - strings.Index(ss, string(s[j-1]))))
		}
		fmt.Println(sum)
		//fmt.Println("---------------------")
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"math"
)

func main() {
	var n int
	var s, k string
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d\n", &n)

	for i := 0; i < n; i++ {
    	fmt.Fscanln(in, &s)
    	chr2num := make(map[rune]int)

    	for i, val := range s {
    	    chr2num[val] = i + 1
    	}

    	fmt.Fscanln(in, &k)
    	count, pre := 0, chr2num[rune(k[0])]

    	for _, val := range k {
        	cur := chr2num[val]
        	count += int(math.Abs(float64(cur - pre)))
    	    pre = cur
    	}
    	fmt.Println(count)
	}
}

package main

import (
	"fmt"
)

const A = 26

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func Solve() {
	var keyboard, word string
	fmt.Scan(&keyboard, &word)
	pos := make([]int, A)
	for idx, c := range keyboard {
		pos[c-'a'] = idx
	}
	ret := 0
	for i := 1; i < len(word); i++ {
		ret += abs(pos[word[i]-'a'] - pos[word[i-1]-'a'])
	}
	fmt.Println(ret)
}

func main() {
	var TC int
	fmt.Scanln(&TC)
	for i := 0; i < TC; i++ {
		Solve()
	}
}

package main

import (
	"fmt"
)

func Abs(x int) int{
	if x<0{
		return x*-1
	}
	return x
}

func main() {
	var t int
	fmt.Scanln(&t)
	for t > 0 {
		var alpha, word string
		var idx int = 0
		fmt.Scan(&alpha, &word)
		arr := make([]int, len(word))
		for i := 0; i < len(word); i++ {
			for c:=0;c<26;c++{
				if word[i] == alpha[c]{
					arr[idx] = c+1
					idx++
				}
			}
		}
		var ans int = 0
		for i := 1; i < idx; i++ {
			ans += Abs(arr[i] - arr[i-1])
		}
		fmt.Println(ans)
		t--
	}
}

package main

import "fmt"

func main() {

	var cases uint
	fmt.Scanln(&cases)

	var tmpStrg, word string
	for cases > 0 {

		cases--

		fmt.Scanln(&tmpStrg)

		keyboardMap := make(map[rune]int)
		for index, char := range tmpStrg {
			keyboardMap[char] = index
		}

		fmt.Scanln(&word)

		time := 0
		for i := 1; i < len(word); i++ {
			time += abs(keyboardMap[rune(word[i])] - keyboardMap[rune(word[i-1])])
		}
		fmt.Println(time)
	}
}

func abs(value int) int {
	if value < 0 {
		value *= -1
	}
	return value
}

package main

import "fmt"

const (
	ALPHABET_SIZE = 26
	T_MIN         = 1
	T_MAX         = 1000
	WORD_MIN      = 1
	WORD_MAX      = 50
)

func calculateDistance(a int, b int) int {
	diff := a - b
	if diff < 0 {
		return -diff
	}
	return diff
}

func parseDictionary(alphabet *string) (dictionary []int) {
	dictionary = make([]int, ALPHABET_SIZE)
	for index, letter := range *alphabet {
		//fmt.Printf("parse: %v, %c\n", index, letter)
		dictionary[letter-'a'] = index
	}
	return
}

func test(alphabet *string, word *string) (result int) {
	dictionary := parseDictionary(alphabet)
	previousLetter := (*word)[0]
	for _, letter := range *word {
		//fmt.Printf("test: %v %c\n", letter, letter)
		result += calculateDistance(
			dictionary[previousLetter-'a'],
			dictionary[letter-'a'],
		)
		previousLetter = byte(letter)
	}
	return
}

func main() {
	var t int
	fmt.Scanf("%v\n", &t)
	//fmt.Printf("%v\n", t)
	for i := 0; i < t; i++ {
		var alphabet, word string
		fmt.Scanf("%s\n%s\n", &alphabet, &word)
		//fmt.Printf("%s\n%s\n", alphabet, word)
		fmt.Printf("%v\n", test(&alphabet, &word))
	}
}

package main

import (
	"fmt"
	"math"
)

func getInt(p *int) {
	for {
		_, err := fmt.Scanf("%d", p)
		if err == nil {
			break
		}
	}
}

func getString(p *string) {
	for {
		_, err := fmt.Scanf("%s", p)
		if err == nil {
			break
		}
	}
}

func proc() {
	m := make(map[rune]int)
	var s string
	getString(&s)
	for i, r := range s {
		m[r] = i
	}
	getString(&s)
	last := -1
	ans := 0
	for _, r := range s {
		now := m[r]
		if last == -1 {
			last = now
		}
		ans += int(math.Abs(float64(now - last)))
		last = now
	}
	fmt.Println(ans)
}

func main() {
	var t int
	getInt(&t)
	for i := 0; i < t; i++ {
		proc()
	}
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		s := readLine(reader)
		b := readLine(reader)

		var sum int = 0
		var a = make([]int, 26)
		for i, r := range s {
			a[r - 'a'] = i
		}

		for i := 1; i < len(b); i++ {
			c := a[b[i] - 'a'] - a[b[i-1] - 'a']
			if c >= 0 {
				sum += c
			} else {
				sum += -1*c
			}
		}

		fmt.Fprintln(writer, sum)

		t--
	}

	writer.Flush()
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

func readLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}

	return strings.TrimRight(string(str), "\r\n")
}

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

package main

import "fmt"

func main() {
	var t, res int
	fmt.Scanln(&t)
	for ; t > 0; t-- {
		var keyboard, s string
		res = 0
		fmt.Scanln(&keyboard)
		fmt.Scanln(&s)
		m := make(map[byte]int, 26)
		for k := range keyboard {
			m[keyboard[k]] = k
		}
		prev := 0
		for i := range s {
			if i > 0 {
				res += abs(m[s[i]], prev)
			}
			prev = m[s[i]]
		}
		fmt.Println(res)
	}
}

func abs(a, b int) int {
	if a-b < 0 {
		return -(a - b)
	}
	return a - b
}

package main

import (
	"fmt"
	"bufio"
	"os"
)

var (
	input = bufio.NewReader(os.Stdin)
	output = bufio.NewWriter(os.Stdout)
)

func assert(test bool) {
    if !test {panic("assert!")}
}

func main() {
    defer output.Flush()
    //solve()
    //return
	var t int64
	fmt.Fscanln(input, &t)
    for t > 0 {
        t--
        solve()
    }
}

func solve() {
    var bet, s string
    fmt.Fscanln(input, &bet)
    fmt.Fscanln(input, &s)
    m := make(map[byte]int)
    for i := 0; i < len(bet); i++ {
        m[bet[i]] = i
    }
    ans := 0
    for i := 1; i < len(s); i++ {
        ans += abs(m[s[i]] - m[s[i - 1]])
    }
    fmt.Fprintln(output, ans)
}

func gcd(a, b int64) int64 {
    if b == 0 { return a}
    return gcd(b, a % b)
}

func lcm(a, b int64) int64 {
    return a * b / gcd(a, b)
}

func abs(x int) int {
    if x >= 0 { return x}
    return -x
}

func max(a, b int) int {
    if a > b { return a}
    return b
}
func min(a, b int) int {
    if a < b { return a}
    return b
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int
	fmt.Scanf("%d",&t)
	for ;t>0;t-- {
		var a,b string
		fmt.Scanf("%s\n%s\n",&a,&b)
		v := make([]int,26)
		for i,c := range(a) {v[c-'a']=i;}
		m := len(b)
		ans := 0
		var aux int
		for i:=1;i<m;i++ {
			aux = int(math.Abs(float64(v[b[i]-'a']-v[b[i-1]-'a'])))
			ans += aux
		}
		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int
	fmt.Scanf("%d",&t)
	for ;t>0;t-- {
		var a,b string
		fmt.Scanf("%s\n%s",&a,&b)
		v := make([]int,26)
		for i,c := range(a) {v[c-'a']=i;}
		m := len(b)
		ans := 0
		var aux int
		for i:=1;i<m;i++ {
			aux = int(math.Abs(float64(v[b[i]-'a']-v[b[i-1]-'a'])))
			ans += aux
		}
		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
	"math"
)

func Abs(a, b int) int {
	return int(math.Abs(float64(a) - float64(b)))
}

func main() {
	var cnt int
	_, err := fmt.Scanf("%d", &cnt)
	if err != nil {
		fmt.Println(err)
		return
	}
	for i := 0; i < cnt; i++ {
		var keyboard string
		var word string
		sum := 0
		_, err = fmt.Scanf("%s", &keyboard)
		if err != nil {
			fmt.Println(err)
			return
		}
		_, err = fmt.Scanf("%s", &word)
		if err != nil {
			fmt.Println(err)
			return
		}
		keyMap := make(map[rune]int)
		for order, val := range keyboard {
			keyMap[val] = order + 1
		}
		for index := 0; index + 1 < len(word); index++ {
			sum += Abs(keyMap[rune(word[index])], keyMap[rune(word[index+1])])
		}
		fmt.Println(sum)
	}
}

package main

import (
	"fmt"
)
import "math"
func main() {
	var test int
  fmt.Scanf("%d",&test)
  for i:=0;i<test;i++{
    var alphaorder string
    fmt.Scanf("%s",&alphaorder)
    var maphere map[string]float64=make(map[string]float64)
    for j:=0.0;j<float64(len(alphaorder));j++{
      maphere[string(alphaorder[int(j)])]=j+1.0
    }
    var input string
    fmt.Scanf("%s",&input)
    var result int=0
    for i:=0;i<len(input)-1;i++{
      result+=int(math.Abs(maphere[string(input[i])]-maphere[string(input[i+1])]))
    }
    fmt.Println(result)
  }
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	n, m := ReadInt(), ReadInt()
	a := make([]int, n)
	b := make([]int, n)
	c := make([]int, m)
	d := make([]int, m)
	for i := 0; i < n; i++ {
		a[i], b[i] = ReadInt(), ReadInt()
	}
	for i := 0; i < m; i++ {
		c[i], d[i] = ReadInt(), ReadInt()
	}
	fmt.Println(solve(n, m, a, b, c, d))
}

func solve(n, m int, a, b, c, d []int) int {
	v := make([]int, 1e6+2)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i] <= c[j] {
				v[c[j]-a[i]] = Max(v[c[j]-a[i]], d[j]-b[i]+1)
			}
		}
	}
	y := 0
	ret := int(1e6 + 1)
	for x := int(1e6 + 1); x >= 0; x-- {
		y = Max(y, v[x])
		ret = Min(ret, x+y)
	}
	return ret
}

func Min(xs ...int) int {
	min := xs[0]
	for _, x := range xs[1:] {
		if min > x {
			min = x
		}
	}
	return min
}

func Max(xs ...int) int {
	max := xs[0]
	for _, x := range xs[1:] {
		if max < x {
			max = x
		}
	}
	return max
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

type point struct {
	x, y int
}

const nodeCnt = int(1e6) + 1

var T[4 * nodeCnt] int
var lz[4 * nodeCnt] int

func lazyUpdate(node int)  {
	if lz[node] > 0 {
		T[node * 2] = max(T[node], lz[node])
		T[node * 2 + 1] = max(T[node * 2 + 1], lz[node])
		lz[node * 2] = max(lz[node * 2], lz[node])
		lz[node * 2 + 1] = max(lz[node * 2 + 1], lz[node])
		lz[node] = 0
	}
}

func updateRange(node int, l int, r int, u int, v int, val int)  {
	if l > v || r < u {
		return
	}

	if l >= u && r <= v {
		T[node] = max(T[node], val)
		lz[node] = max(lz[node], val)
		return
	}

	lazyUpdate(node)
	var mid = (l + r) / 2
	updateRange(node * 2, l, mid, u, v, val)
	updateRange(node * 2 + 1, mid + 1, r, u, v, val)
	T[node] = max(T[node * 2], T[node * 2 + 1])
}

func getMax(node int, l int, r int, pos int) int {
	if l > pos || r < pos {
		return 0
	}

	if l == r {
		if l == pos {
			return T[node]
		}
		return 0
	}

	lazyUpdate(node)
	var mid = (l + r) / 2
	return max(getMax(node * 2, l, mid, pos),
		getMax(node * 2 + 1, mid + 1, r, pos))
}

func max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a int, b int) int {
	if a < b {
		return a
	}
	return b
}

func main()  {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var n, m int
	fmt.Fscanf(reader, "%d%d\n", &n, &m)
	var robs = make([]point, 0)
	var lights = make([]point, 0)
	for i := 0; i < n; i++ {
		var x, y int
		fmt.Fscanf(reader, "%d%d\n", &x, &y)
		robs = append(robs, point{x, y})
	}
	for i := 0; i < m; i++ {
		var x, y int
		fmt.Fscanf(reader, "%d%d\n", &x, &y)
		lights = append(lights, point{x, y})
	}

	var dxMax = make([]int, nodeCnt + 1)
	for _, rob := range robs {
		for _, light := range lights {
			var dx = light.x - rob.x
			if dx >= 0 {
				var dy = max(0, light.y - rob.y + 1)
				if dy > 0 {
					dxMax[dx + 1] = max(dxMax[dx + 1], dy)
				}
			}
		}
	}

	for i := 1; i <= nodeCnt; i++ {
		if dxMax[i] > 0 {
			updateRange(1, 1, nodeCnt, 1, i, dxMax[i])
		}
	}

	var ret = 2 * nodeCnt
	for dx := nodeCnt + 1; dx >= 1; dx-- {
		ret = min(ret, getMax(1, 1, nodeCnt, dx) + dx - 1)
	}
	fmt.Fprintf(writer, "%d", ret)
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	n, m := ReadInt(), ReadInt()
	a := make([]int, n)
	b := make([]int, n)
	c := make([]int, m)
	d := make([]int, m)
	for i := 0; i < n; i++ {
		a[i], b[i] = ReadInt(), ReadInt()
	}
	for i := 0; i < m; i++ {
		c[i], d[i] = ReadInt(), ReadInt()
	}
	fmt.Println(solve(n, m, a, b, c, d))
}

func solve(n, m int, a, b, c, d []int) int {
	v := make([]int, 1e6+1)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i] <= c[j] {
				v[c[j]-a[i]] = Max(v[c[j]-a[i]], d[j]-b[i]+1)
			}
		}
	}
	y := 0
	ret := int(1e6)
	for x := int(1e6); x >= 0; x-- {
		y = Max(y, v[x])
		ret = Min(ret, x+y)
	}
	return ret
}

func Min(xs ...int) int {
	min := xs[0]
	for _, x := range xs[1:] {
		if min > x {
			min = x
		}
	}
	return min
}

func Max(xs ...int) int {
	max := xs[0]
	for _, x := range xs[1:] {
		if max < x {
			max = x
		}
	}
	return max
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

type pair struct {
	x, y int
}

type triple struct {
	x, y int
	id int
}

func max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a int, b int) int {
	if a < b {
		return a
	}
	return b
}

const N = int(2e6)
const INF = int(1e9)
var Tree[]int

func countMove(robot pair, from pair, to pair) pair {
	if from.x == to.x {
		if robot.x > from.x || robot.y > to.y {
			return pair{-1, -1}
		}
		return pair{from.x - robot.x, max(0, from.y - robot.y)}
	}

	if robot.y > from.y || robot.x > from.x {
		return pair{-1, -1}
	}
	return pair{max(0, to.x - robot.x), from.y - robot.y}
}

func update(node int, l int, r int, pos int, value int)  {
	if l > pos || r < pos {
		return
	}
	if l == r {
		if l != pos {
			return
		}
		Tree[node] = value
		return
	}
	var mid = (l + r) / 2
	update(node * 2, l, mid, pos, value)
	update(node * 2 + 1, mid + 1, r, pos, value)
	Tree[node] = max(Tree[node * 2], Tree[node * 2+ 1])
}

func initTree(node int, l int, r int)  {
	if l == r {
		Tree[node] = INF
		return
	}
	var mid = (l + r) / 2
	initTree(node * 2, l, mid)
	initTree(node * 2 + 1, mid + 1, r)
	Tree[node] = max(Tree[node * 2], Tree[node * 2 + 1])
}

func main()  {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	var lights = make([]pair, 0)
	var unique = make(map[pair]bool)

	var robots = make([]pair, 0)

	for i := 0; i < n; i++ {
		var x, y int
		fmt.Fscanf(reader, "%d %d\n", &x, &y)
		robots = append(robots, pair{x, y})
	}

	for i := 0; i < m; i++ {
		var x, y int
		fmt.Fscanf(reader, "%d %d\n", &x, &y)
		_, ok := unique[pair{x, y}]
		if !ok {
			lights = append(lights, pair{x, y})
			unique[pair{x, y}] = true
		}
	}

	var candidates = make([]pair, 0)
	for i := 0; i < len(lights); i++ {
		var found = false
		for j := 0; j < len(lights); j++ {
			if i != j && lights[i].x <= lights[j].x && lights[i].y <= lights[j].y {
				found = true
				break
			}
		}
		if !found {
			candidates = append(candidates, lights[i])
		}
	}

	sort.Slice(candidates, func(i, j int) bool {
		return candidates[i].x > candidates[j].x || (candidates[i].x == candidates[j].x && candidates[i].y < candidates[j].y)
	})

	var M = len(candidates)

	var points = make([]pair, 0)
	if candidates[0].y > 0 {
		points = append(points, pair{candidates[0].x, 0})
	}
	points = append(points, candidates[0])

	for i := 1; i < M; i++ {
		points = append(points, pair{candidates[i].x, candidates[i - 1].y})
		points = append(points, candidates[i])
	}

	if candidates[M - 1].x > 0 {
		points = append(points, pair{0, candidates[M - 1].y})
	}

	M = len(points)
	points[0].x++
	for i := 1; i < M - 1; i++ {
		points[i].x++
		points[i].y++
	}
	points[M - 1].y++

	if len(points) == 1 {
		var tmps = make([]pair, 0)
		tmps = append(tmps, pair{points[0].x, 0})
		tmps = append(tmps, points[0])
		tmps = append(tmps, pair{0, points[0].y})
		points = tmps
		M = len(points)
	}

	var wouldMove = 0
	var moves = make([]triple, 0)
	for id, robot := range robots {
		var isMoved = false
		for i := 1; i < M; i++ {
			var move = countMove(robot, points[i - 1], points[i])
			if move.x == -1 {
				continue
			}
			moves = append(moves, triple{move.x, move.y, id})
			isMoved = true
		}
		if isMoved {
			wouldMove++
		}
	}

	if wouldMove == 0 {
		fmt.Fprintf(writer, "0")
		return
	}

	sort.Slice(moves, func(i, j int) bool {
		return moves[i].y < moves[j].y
	})

	var ret = INF

	var nodeCnt = len(robots)
	Tree = make([]int, 4 * (nodeCnt + 1))
	initTree(1, 1, nodeCnt)

	for _, move := range moves {
		update(1, 1, nodeCnt, move.id + 1, move.x)
		ret = min(ret, move.y + Tree[1])
	}
	fmt.Fprintf(writer, "%d\n", ret)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

type pair struct {
	x, y int
}

type triple struct {
	x, y int
	id int
}

func max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a int, b int) int {
	if a < b {
		return a
	}
	return b
}

const N = int(2e6)
const INF = int(1e9)
var Tree[]int

func countMove(robot pair, from pair, to pair) pair {
	if from.x == to.x {
		if robot.x > from.x || robot.y > to.y {
			return pair{-1, -1}
		}
		return pair{from.x - robot.x, max(0, from.y - robot.y)}
	}

	if robot.y > from.y || robot.x > from.x {
		return pair{-1, -1}
	}
	return pair{max(0, to.x - robot.x), from.y - robot.y}
}

func getMax(node int, l int, r int, u int, v int) int {
	if r < u || l > v {
		return -INF
	}
	if l >= u && r <= v {
		return Tree[node]
	}
	var mid = (l + r) / 2
	var lmax = getMax(node * 2, l, mid, u, v)
	var rmax = getMax(node * 2 + 1, mid + 1, r, u, v)
	return max(lmax, rmax)
}

func update(node int, l int, r int, pos int, value int)  {
	if l > pos || r < pos {
		return
	}
	if l == r {
		if l != pos {
			return
		}
		Tree[node] = value
		return
	}
	var mid = (l + r) / 2
	update(node * 2, l, mid, pos, value)
	update(node * 2 + 1, mid + 1, r, pos, value)
	Tree[node] = max(Tree[node * 2], Tree[node * 2+ 1])
}

func initTree(node int, l int, r int)  {
	if l == r {
		Tree[node] = INF
		return
	}
	var mid = (l + r) / 2
	initTree(node * 2, l, mid)
	initTree(node * 2 + 1, mid + 1, r)
	Tree[node] = max(Tree[node * 2], Tree[node * 2 + 1])
}

func main()  {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	var lights = make([]pair, 0)
	var unique = make(map[pair]bool)

	var robots = make([]pair, 0)

	for i := 0; i < n; i++ {
		var x, y int
		fmt.Fscanf(reader, "%d %d\n", &x, &y)
		robots = append(robots, pair{x, y})
	}

	for i := 0; i < m; i++ {
		var x, y int
		fmt.Fscanf(reader, "%d %d\n", &x, &y)
		_, ok := unique[pair{x, y}]
		if !ok {
			lights = append(lights, pair{x, y})
			unique[pair{x, y}] = true
		}
	}

	var candidates = make([]pair, 0)
	for i := 0; i < len(lights); i++ {
		var found = false
		for j := 0; j < len(lights); j++ {
			if i != j && lights[i].x <= lights[j].x && lights[i].y <= lights[j].y {
				found = true
				break
			}
		}
		if !found {
			candidates = append(candidates, lights[i])
		}
	}

	sort.Slice(candidates, func(i, j int) bool {
		return candidates[i].x > candidates[j].x || (candidates[i].x == candidates[j].x && candidates[i].y < candidates[j].y)
	})

	var M = len(candidates)

	var points = make([]pair, 0)
	if candidates[0].y > 0 {
		points = append(points, pair{candidates[0].x, 0})
	}
	points = append(points, candidates[0])

	for i := 1; i < M; i++ {
		points = append(points, pair{candidates[i].x, candidates[i - 1].y})
		points = append(points, candidates[i])
	}

	if candidates[M - 1].x > 0 {
		points = append(points, pair{0, candidates[M - 1].y})
	}

	M = len(points)
	points[0].x++
	for i := 1; i < M - 1; i++ {
		points[i].x++
		points[i].y++
	}
	points[M - 1].y++

	if len(points) == 1 {
		var tmps = make([]pair, 0)
		tmps = append(tmps, pair{points[0].x, 0})
		tmps = append(tmps, points[0])
		tmps = append(tmps, pair{0, points[0].y})
		points = tmps
		M = len(points)
	}

	var wouldMove = 0
	var moves = make([]triple, 0)
	for id, robot := range robots {
		var isMoved = false
		for i := 1; i < M; i++ {
			var move = countMove(robot, points[i - 1], points[i])
			if move.x == -1 {
				continue
			}
			moves = append(moves, triple{move.x, move.y, id})
			isMoved = true
		}
		if isMoved {
			wouldMove++
		}
	}

	if wouldMove == 0 {
		fmt.Fprintf(writer, "0")
		return
	}

	sort.Slice(moves, func(i, j int) bool {
		return moves[i].y < moves[j].y
	})

	var ret = INF

	var nodeCnt = len(robots)
	Tree = make([]int, 4 * nodeCnt + 1)
	initTree(1, 1, nodeCnt)

	for _, move := range moves {
		update(1, 1, nodeCnt, move.id + 1, move.x)
		ret = min(ret, move.y + getMax(1, 1, nodeCnt, 1, nodeCnt))
	}
	fmt.Fprintf(writer, "%d\n", ret)
}


package main

import (
    "io/ioutil"
    "bufio"
    "os"
)

func main() {
    writer := bufio.NewWriter(os.Stdout)
    s, _ := ioutil.ReadAll(os.Stdin)
    open, start := false, false
    for _, b := range s {
        if ((b < 'a') || (b > 'z')) && ((b < 'A') || (b > 'Z')) && ((b < '0') || (b > '9')) && (b != ' ') && (b != '.') && (b != ',') && (b != '!') && (b != '?') && (b != '"') { break }
        v := rune(b)
        if open {
            if v == '"' {
                writer.WriteString(">\n")
                open = false
            } else {
                writer.WriteRune(v)
            }
        } else {
            if v == '"' {
                writer.WriteString("<")
                open = true
            } else if v != ' ' {
                if !start {
                    writer.WriteString("<")
                    start = true
                }
                writer.WriteRune(v)
            } else {
                if start {
                    writer.WriteString(">\n")
                    start = false
                }
            }
        }
    }
    if start { writer.WriteString(">\n") }
    writer.Flush()
}

package main

import (
    "io/ioutil"
    "bufio"
    "os"
)

func main() {
    writer := bufio.NewWriter(os.Stdout)
    s, _ := ioutil.ReadAll(os.Stdin)
    open, start := false, false
    for _, v := range s {
        if ((v < 'a') || (v > 'z')) && ((v < 'A') || (v > 'Z')) && ((v < '0') || (v > '9')) && (v != ' ') && (v != '.') && (v != ',') && (v != '!') && (v != '?') && (v != '"') { break }
        if open {
            if v == '"' {
                writer.WriteString(">\n")
                open = false
            } else {
                writer.WriteByte(v)
            }
        } else {
            if v == '"' {
                writer.WriteString("<")
                open = true
            } else if v != ' ' {
                if !start {
                    writer.WriteString("<")
                    start = true
                }
                writer.WriteByte(v)
            } else {
                if start {
                    writer.WriteString(">\n")
                    start = false
                }
            }
        }
    }
    if start { writer.WriteString(">\n") }
    writer.Flush()
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func solve() {
	s := []byte(readString())

	// Consume initial spaces

	for len(s) > 0 {
		if s[0] == ' ' {
			s = s[1:]
		} else {
			s = s[parseWord(s):]
		}
	}
}

func parseWord(s []byte) int {
	n := 0
	inquote := false
	word := make([]byte, 0, len(s))
	for _, c := range s {
		if inquote {
			if c == '"' {
				inquote = false
			} else {
				word = append(word, c)
			}
		} else {
			if c == ' ' {
				break
			}
			if c == '"' {
				inquote = true
			} else {
				word = append(word, c)
			}
		}
		n++
	}
	fmt.Print("<", string(word), ">\n")
	return n
}

var scanner *bufio.Scanner

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanLines)
	solve()
}

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

func readInt64() int64 {
	v, _ := strconv.ParseInt(readString(), 10, 64)
	return v
}

package main

import (
    "io/ioutil"
    "bufio"
    "os"
)

func main() {
    writer := bufio.NewWriter(os.Stdout)
    s, _ := ioutil.ReadAll(os.Stdin)
    open, start := false, false
    for _, b := range s {
        if b == '\n' { break }
        v := rune(b)
        if open {
            if v == '"' {
                writer.WriteString(">\n")
                open = false
            } else {
                writer.WriteRune(v)
            }
        } else {
            if v == '"' {
                writer.WriteString("<")
                open = true
            } else if v != ' ' {
                if !start {
                    writer.WriteString("<")
                    start = true
                }
                writer.WriteRune(v)
            } else {
                if start {
                    writer.WriteString(">\n")
                    start = false
                }
            }
        }
    }
    if start { writer.WriteString(">\n") }
    writer.Flush()
}

package main

import (
    "bufio"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    writer := bufio.NewWriter(os.Stdout)
    scanner.Scan()
    open, start := false, false
    for _, v := range scanner.Text() {
        if open {
            if v == '"' {
                writer.WriteString(">\n")
                open = false
            } else {
                writer.WriteRune(v)
            }
        } else {
            if v == '"' {
                writer.WriteString("<")
                open = true
            } else if v != ' ' {
                if !start {
                    writer.WriteString("<")
                    start = true
                }
                writer.WriteRune(v)
            } else {
                if start {
                    writer.WriteString(">\n")
                    start = false
                }
            }
        }
    }
    writer.Flush()
}

package main

import (
    "bufio"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    writer := bufio.NewWriter(os.Stdout)
    s, _, _ := reader.ReadLine()
    open, start := false, false
    for _, b := range s {
        v := rune(b)
        if open {
            if v == '"' {
                writer.WriteString(">\n")
                open = false
            } else {
                writer.WriteRune(v)
            }
        } else {
            if v == '"' {
                writer.WriteString("<")
                open = true
            } else if v != ' ' {
                if !start {
                    writer.WriteString("<")
                    start = true
                }
                writer.WriteRune(v)
            } else {
                if start {
                    writer.WriteString(">\n")
                    start = false
                }
            }
        }
    }
    if start { writer.WriteString(">\n") }
    writer.Flush()
}

package main

import (
    "bufio"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    writer := bufio.NewWriter(os.Stdout)
    scanner.Scan()
    open, start := false, false
    for _, v := range scanner.Text() {
        if open {
            if v == '"' {
                writer.WriteString(">\n")
                open = false
            } else {
                writer.WriteRune(v)
            }
        } else {
            if v == '"' {
                writer.WriteString("<")
                open = true
            } else if v != ' ' {
                if !start {
                    writer.WriteString("<")
                    start = true
                }
                writer.WriteRune(v)
            } else {
                if start {
                    writer.WriteString(">\n")
                    start = false
                }
            }
        }
    }
    if start { writer.WriteString(">\n") }
    writer.Flush()
}


package main

import (
	"fmt"
	"bufio"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var t int
	for fmt.Fscan(reader, &t); t > 0; t-- {
		var n int
		fmt.Fscan(reader, &n)
		a := make([]int, n)
		mx := 0
		sum := int64(0)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
			if a[i] > mx {
				mx = a[i]
			}
			sum += int64(a[i])
		}
		if mx == 0 {
			fmt.Fprint(writer, "0\n")
			continue
		}
		sum -= int64(mx)
		if int64(mx) > sum {
			fmt.Fprintf(writer, "%d\n", int64(mx)-sum)
			continue
		}
		fmt.Fprint(writer, "1\n")
	}
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func main() {
	cf1649b(os.Stdin, os.Stdout)
}

func cf1649b(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(in, &n)
		mx := 0
		sum := int64(0)
		for j := 0; j < n; j++ {
			var num int
			fmt.Fscan(in, &num)
			mx = max(mx, num)
			sum += int64(num)
		}
		// solve
		if mx == 0 {
			fmt.Fprintln(out, 0)
		} else if int64(mx) * 2 <= sum {
			fmt.Fprintln(out, 1)
		} else {
			fmt.Fprintln(out, 2*int64(mx) - sum)
		}
	}
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func solveCF1649BCase(in io.Reader, out io.Writer) {
	var n int
	fmt.Fscan(in, &n)

	var max, sum int64 = 0, 0
	for i := 0; i < n; i++ {
		var p int64
		fmt.Fscan(in, &p)
		if p > max {
			max = p
		}
		sum = sum + p
	}

	if sum == 0 {
		fmt.Fprintln(out, 0)
		return
	}
	if (sum - max) >= max {
		fmt.Fprintln(out, 1)
		return
	}
	fmt.Fprintln(out, max-(sum-max))
}

func CF1649B(rawIn io.Reader, rawOut io.Writer) {
	in := bufio.NewReader(rawIn)
	out := bufio.NewWriter(rawOut)
	defer out.Flush()

	var cases int
	fmt.Fscan(in, &cases)
	for cc := 0; cc < cases; cc++ {
		solveCF1649BCase(in, out)
	}
}

func main() { CF1649B(os.Stdin, os.Stdout) }

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
)

/*
4
2
0 0
2
1 1
3
1 1 1
4
1 1 1 1
---
0
1
1
1
========
4
2
5 1
2
5 2
3
1 3 4
3
1 3 7
---
4
3
1
3
========
8
4
2 2 2 2
4
3 2 2 2
4
4 2 2 2
4
1 2 3 4
4
1 1 1 4
6
1 1 1 1 2 3
6
1 1 1 1 2 4
5
1 1 4 4 10
---
1
1
1
1
1
1
1
1
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n int
	scanf("%d\n", &n)

	a := make([]int, n)

	sum := int64(0)
	onlyZeros := true

	for i := range a {
		scanf("%d", &a[i])

		sum += int64(a[i])

		if a[i] != 0 {
			onlyZeros = false
		}
	}
	scanf("\n")

	if onlyZeros {
		fmt.Fprintln(writer, 0)
		return
	}

	sort.Ints(a)

	minBallCnt := int64(1)

	diff := int64(a[n-1]) - (sum - int64(a[n-1])) - 1
	maxCnt, _ := max(0, diff)
	minBallCnt += maxCnt

	fmt.Fprintln(writer, minBallCnt)
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int) int {
	quot := num / div
	if num%div != 0 {
		quot++
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int64) int64 {
	minimum := nums[0]
	for _, num := range nums {
		if num < minimum {
			minimum = num
		}
	}
	return minimum
}

//goland:noinspection GoUnusedFunction
func max(nums ...int64) (max, idx int64) {
	for i, num := range nums {
		if num > nums[idx] {
			idx = int64(i)
		}
	}

	return nums[idx], idx
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := 5; i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func solveCF1649BCase(in io.Reader, out io.Writer) {
	var n int
	fmt.Fscan(in, &n)

	var max, sum int = 0, 0
	for i := 0; i < n; i++ {
		var p int
		fmt.Fscan(in, &p)
		if p > max {
			max = p
		}
		sum = sum + p
	}

	if sum == 0 {
		fmt.Fprintln(out, 0)
		return
	}
	if max == 1000000000 {
		fmt.Fprintf(out, "%d %d %d\n", sum, max, sum-max)
	}
	if (sum - max) >= max {
		fmt.Fprintln(out, 1)
		return
	}
	fmt.Fprintln(out, max-(sum-max))
}

func CF1649B(rawIn io.Reader, rawOut io.Writer) {
	in := bufio.NewReader(rawIn)
	out := bufio.NewWriter(rawOut)
	defer out.Flush()

	var cases int
	fmt.Fscan(in, &cases)
	for cc := 0; cc < cases; cc++ {
		solveCF1649BCase(in, out)
	}
}

func main() { CF1649B(os.Stdin, os.Stdout) }

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func solveCF1649BCase(in io.Reader, out io.Writer) {
	var n int
	fmt.Fscan(in, &n)

	var max, sum int = 0, 0
	for i := 0; i < n; i++ {
		var p int
		fmt.Fscan(in, &p)
		if p > max {
			max = p
		}
		sum = sum + p
	}

	if sum == 0 {
		fmt.Fprintln(out, 0)
		return
	}
	if (sum - max) >= max {
		fmt.Fprintln(out, 1)
		return
	}
	fmt.Fprintln(out, max-(sum-max))
}

func CF1649B(rawIn io.Reader, rawOut io.Writer) {
	in := bufio.NewReader(rawIn)
	out := bufio.NewWriter(rawOut)
	defer out.Flush()

	var cases int
	fmt.Fscan(in, &cases)
	for cc := 0; cc < cases; cc++ {
		solveCF1649BCase(in, out)
	}
}

func main() { CF1649B(os.Stdin, os.Stdout) }

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func solveCF1649BCase(in io.Reader, out io.Writer) {
	var n int
	fmt.Fscan(in, &n)

	var max, sum int = 0, 0
	for i := 0; i < n; i++ {
		var p int
		fmt.Fscan(in, &p)
		if p > max {
			max = p
		}
		sum = sum + p
	}

	if sum == 0 {
		fmt.Fprintln(out, 0)
	} else if (sum - max) >= max {
		fmt.Fprintln(out, 1)
	} else {
		fmt.Fprintln(out, max-(sum-max))
	}
}

func CF1649B(rawIn io.Reader, rawOut io.Writer) {
	in := bufio.NewReader(rawIn)
	out := bufio.NewWriter(rawOut)
	defer out.Flush()

	var cases int
	fmt.Fscan(in, &cases)
	for cc := 0; cc < cases; cc++ {
		solveCF1649BCase(in, out)
	}
}

func main() { CF1649B(os.Stdin, os.Stdout) }

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func solveCF1649BCase(in io.Reader, out io.Writer) {
	var n int
	fmt.Fscan(in, &n)

	var max, sum int = 0, 0
	for i := 0; i < n; i++ {
		var p int
		fmt.Fscan(in, &p)
		if p > max {
			max = p
		}
		sum = sum + p
	}

	if sum == 0 {
		fmt.Fprintln(out, 0)
	} else if sum-max >= max {
		fmt.Fprintln(out, 1)
	} else {
		fmt.Fprintln(out, max-(sum-max))
	}
}

func CF1649B(rawIn io.Reader, rawOut io.Writer) {
	in := bufio.NewReader(rawIn)
	out := bufio.NewWriter(rawOut)
	defer out.Flush()

	var cases int
	fmt.Fscan(in, &cases)
	for cc := 0; cc < cases; cc++ {
		solveCF1649BCase(in, out)
	}
}

func main() { CF1649B(os.Stdin, os.Stdout) }

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func main() {
	cf1649b(os.Stdin, os.Stdout)
}

func cf1649b(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(in, &n)
		mx := 0
		sum := 0
		for j := 0; j < n; j++ {
			var num int
			fmt.Fscan(in, &num)
			mx = max(mx, num)
			sum += num
		}
		// solve
		if mx == 0 {
			fmt.Fprintln(out, 0)
		} else if mx * 2 <= sum {
			fmt.Fprintln(out, 1)
		} else {
			fmt.Fprintln(out, 2*mx - sum)
		}
	}
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

const (
	mod int = 1e9 + 7
)

func main() {
	in := bufio.NewScanner(os.Stdin)
	in.Split(bufio.ScanWords)
	in.Buffer(nil, 1e9)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	nextInt := func() int {
		in.Scan()
		vv, _ := strconv.Atoi(in.Text())
		return vv
	}

	// nextStr := func() string {
	// 	in.Scan()
	// 	return in.Text()
	// }

	t := nextInt()
	sol := func() int {
		n := nextInt()
		a := make([]int, n+1)
		b := make([]int, n+1)
		c := make([]int, n+1)
		t := make([]bool, n+1)
		for i := 1; i <= n; i++ {
			z := nextInt()
			a[i] = z
		}
		for i := 1; i <= n; i++ {
			z := nextInt()
			b[a[i]] = z
		}
		for i := 1; i <= n; i++ {
			z := nextInt()
			c[a[i]] = z
		}
		ans := 1
		for i := 1; i <= n; i++ {
			if t[i] {
				continue
			}
			z := i
			f := true
			cc := 0
			// var val []int
			for {
				if c[z] != 0 {
					f = false
				}
				// val = append(val, z)
				t[z] = true
				cc++
				z = b[z]
				if z == i {
					break
				}
			}
			// fmt.Println(val, f, cc)
			if f && cc > 1 {
				ans = (ans + ans) % mod
			}
		}
		return ans
	}
	for ; t > 0; t-- {
		fmt.Fprintln(out, sol())
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func modshift(p, m int) int {
	res := 1
	for i := 0; i < p; i++ {
		res = res << 1
		res = res % m
	}
	return res
}

func dfs(n int, p []int, v []bool) {
	t := n
	v[t] = true
	for p[t] != n {
		t = p[t]
		v[t] = true
	}
}

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	mod := int(1e9 + 7)
	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {
		var n, cnt int
		fmt.Fscan(r, &n)

		a := make([]int, n)
		b := make([]int, n)
		d := make([]int, n)
		p := make([]int, n+1)
		vis := make([]bool, n+1)

		for i := range a { fmt.Fscan(r, &a[i]) }
		for i := range b { fmt.Fscan(r, &b[i]) }
		for i := range d { fmt.Fscan(r, &d[i]) }

		for i := range d {
			p[b[i]] = a[i]
			if b[i] == a[i] { d[i] = a[i] }
		}

		for _, v := range d {
			if v != 0 && !vis[v] { dfs(v, p, vis) }
		}

		for i, v := range d {
			if v == 0 && !vis[b[i]] {
				cnt++
				dfs(b[i], p, vis)
			}
		}

		fmt.Fprintln(w, modshift(cnt, mod))
	}

}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

const (
	mod int = 1e9 + 7
)

func main() {
	in := bufio.NewScanner(os.Stdin)
	in.Split(bufio.ScanWords)
	in.Buffer(nil, 1e9)

	nextInt := func() int {
		in.Scan()
		vv, _ := strconv.Atoi(in.Text())
		return vv
	}

	// nextStr := func() string {
	// 	in.Scan()
	// 	return in.Text()
	// }

	t := nextInt()
	sol := func() int {
		n := nextInt()
		a := make([]int, n+1)
		b := make([]int, n+1)
		c := make([]int, n+1)
		t := make([]bool, n+1)
		for i := 1; i <= n; i++ {
			z := nextInt()
			a[i] = z
		}
		for i := 1; i <= n; i++ {
			z := nextInt()
			b[a[i]] = z
		}
		for i := 1; i <= n; i++ {
			z := nextInt()
			c[a[i]] = z
		}
		ans := 1
		for i := 1; i <= n; i++ {
			if t[i] {
				continue
			}
			z := i
			f := true
			cc := 0
			// var val []int
			for {
				if c[z] != 0 {
					f = false
				}
				// val = append(val, z)
				t[z] = true
				cc++
				z = b[z]
				if z == i {
					break
				}
			}
			// fmt.Println(val, f, cc)
			if f && cc > 1 {
				ans = (ans + ans) % mod
			}
		}
		return ans
	}
	for ; t > 0; t-- {
		fmt.Println(sol())
	}
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

type Int int64

const (
	INF = 3e5 + 10
	L0  = Int(0)
	L1  = Int(1)
)

func find(x int, f []int) int {
	if f[x] != x {
		f[x] = find(f[x], f)
	}
	return f[x]
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var t int
	Fscan(in, &t)

	for tt := 0; tt < t; tt++ {
		var n int
		Fscan(in, &n)

		a := make([]int, n+1)
		b := make([]int, n+1)
		c := make([]int, n+1)

		f := make([]int, n+1)
		cnt := make([]int, n+1)

		for i := 1; i <= n; i++ {
			Fscan(in, &a[i])
			f[i] = i
			cnt[i] = 1
		}

		for i := 1; i <= n; i++ {
			Fscan(in, &b[i])
			fx := find(a[i], f)
			fy := find(b[i], f)
			if fx != fy {
				f[fx] = fy
				cnt[fy] += cnt[fx]
				cnt[fx] = 0
			}
		}

		for i := 1; i <= n; i++ {
			Fscan(in, &c[i])
			if c[i] != 0 {
				fc := find(a[i], f)
				cnt[fc] = 0
			}
		}

		ans := L1
		for i := 1; i <= n; i++ {
			if f[i] == i && cnt[i] > 1 {
				ans = (ans << 1) % 1000000007
			}
		}

		Fprintln(out, ans)

	}

}

func MakeGrid(h, w int) [][]Int {
	index := make([][]Int, h)
	data := make([]Int, h*w)
	for i := 0; i < h; i++ {
		index[i] = data[i*w : (i+1)*w]
	}
	return index
}

func Abs(x Int) Int {
	if x > 0 {
		return x
	}
	return -x
}

func Min(nums ...Int) Int {
	return nums[MinIdx(nums...)]
}

func MinIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num < nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

func Max(nums ...Int) Int {
	return nums[MaxIdx(nums...)]
}

func MaxIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

var (
	mod  Int
	fmod func(Int) Int = doNothing
)

// SetMod sets the mod. It must be called first.
func SetMod(newMod Int) {
	mod = newMod
	fmod = dynamicMod
}

func dynamicMod(m Int) Int {
	m %= mod
	if m < 0 {
		return m + mod
	}
	return m
}

func doNothing(m Int) Int {
	return m
}

// Mod returns m % mod.
func (m Int) Mod() Int {
	return fmod(m)
}

// Inv returns modular multiplicative inverse
func (m Int) Inv() Int {
	return m.Pow(Int(0).Sub(2))
}

// Pow returns m^n
func (m Int) Pow(n Int) Int {
	p := Int(1)
	for n > 0 {
		if n&1 == 1 {
			p.MulAs(m)
		}
		m.MulAs(m)
		n >>= 1
	}
	return p
}

// Add returns m+x
func (m Int) Add(x Int) Int {
	return (m + x).Mod()
}

// Sub returns m-x
func (m Int) Sub(x Int) Int {
	return (m - x).Mod()
}

// Mul returns m*x
func (m Int) Mul(x Int) Int {
	return (m * x).Mod()
}

// Div returns m/x
func (m Int) Div(x Int) Int {
	return m.Mul(x.Inv())
}

// AddAs assigns *m + x to *m and returns m
func (m *Int) AddAs(x Int) *Int {
	*m = m.Add(x)
	return m
}

// SubAs assigns *m - x to *m and returns m
func (m *Int) SubAs(x Int) *Int {
	*m = m.Sub(x)
	return m
}

// MulAs assigns *m * x to *m and returns m
func (m *Int) MulAs(x Int) *Int {
	*m = m.Mul(x)
	return m
}

// DivAs assigns *m / x to *m and returns m
func (m *Int) DivAs(x Int) *Int {
	*m = m.Div(x)
	return m
}

func (m *Int) MaxAs(x ...Int) *Int {
	*m = Max(append(x, *m)...)
	return m
}

func (m *Int) MinAs(x ...Int) *Int {
	*m = Min(append(x, *m)...)
	return m
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

type Int int64

const (
	INF = 3e5 + 10
	L0  = Int(0)
	L1  = Int(1)
)

func find(x int, f []int) int {
	if x != f[x] {
		f[x] = find(f[x], f)
	}
	return f[x]
}

func union(x, y int, f, cnt []int) {
	fx := find(x, f)
	fy := find(y, f)

	if fx != fy {
		f[fx] = fy
		cnt[fy] += cnt[fx]
		cnt[fx] = 0
	}
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var t int
	Fscan(in, &t)

	for tt := 0; tt < t; tt++ {
		var n int
		Fscan(in, &n)
		f := make([]int, n+1)
		a := make([]int, n+1)
		b := make([]int, n+1)
		c := make([]int, n+1)
		cnt := make([]int, n+1)
		vis := make([]bool, n+1)

		for i := 1; i <= n; i++ {
			Fscan(in, &a[i])
			f[i] = i
			cnt[i] = 1
		}

		for i := 1; i <= n; i++ {
			Fscan(in, &b[i])
		}

		for i := 1; i <= n; i++ {
			union(a[i], b[i], f, cnt)
		}

		for i := 1; i <= n; i++ {
			Fscan(in, &c[i])
			if c[i] != 0 {
				vis[find(a[i], f)] = true
			}
		}

		ans := L1
		for i := 1; i <= n; i++ {
			fx := find(i, f)
			if cnt[fx] > 1 && !vis[fx] {
				vis[fx] = true
				ans = (ans << 1) % 1000000007
			}
		}
		Fprintln(out, ans)

	}

}

func MakeGrid(h, w int) [][]Int {
	index := make([][]Int, h)
	data := make([]Int, h*w)
	for i := 0; i < h; i++ {
		index[i] = data[i*w : (i+1)*w]
	}
	return index
}

func Abs(x Int) Int {
	if x > 0 {
		return x
	}
	return -x
}

func Min(nums ...Int) Int {
	return nums[MinIdx(nums...)]
}

func MinIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num < nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

func Max(nums ...Int) Int {
	return nums[MaxIdx(nums...)]
}

func MaxIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

var (
	mod  Int
	fmod func(Int) Int = doNothing
)

// SetMod sets the mod. It must be called first.
func SetMod(newMod Int) {
	mod = newMod
	fmod = dynamicMod
}

func dynamicMod(m Int) Int {
	m %= mod
	if m < 0 {
		return m + mod
	}
	return m
}

func doNothing(m Int) Int {
	return m
}

// Mod returns m % mod.
func (m Int) Mod() Int {
	return fmod(m)
}

// Inv returns modular multiplicative inverse
func (m Int) Inv() Int {
	return m.Pow(Int(0).Sub(2))
}

// Pow returns m^n
func (m Int) Pow(n Int) Int {
	p := Int(1)
	for n > 0 {
		if n&1 == 1 {
			p.MulAs(m)
		}
		m.MulAs(m)
		n >>= 1
	}
	return p
}

// Add returns m+x
func (m Int) Add(x Int) Int {
	return (m + x).Mod()
}

// Sub returns m-x
func (m Int) Sub(x Int) Int {
	return (m - x).Mod()
}

// Mul returns m*x
func (m Int) Mul(x Int) Int {
	return (m * x).Mod()
}

// Div returns m/x
func (m Int) Div(x Int) Int {
	return m.Mul(x.Inv())
}

// AddAs assigns *m + x to *m and returns m
func (m *Int) AddAs(x Int) *Int {
	*m = m.Add(x)
	return m
}

// SubAs assigns *m - x to *m and returns m
func (m *Int) SubAs(x Int) *Int {
	*m = m.Sub(x)
	return m
}

// MulAs assigns *m * x to *m and returns m
func (m *Int) MulAs(x Int) *Int {
	*m = m.Mul(x)
	return m
}

// DivAs assigns *m / x to *m and returns m
func (m *Int) DivAs(x Int) *Int {
	*m = m.Div(x)
	return m
}

func (m *Int) MaxAs(x ...Int) *Int {
	*m = Max(append(x, *m)...)
	return m
}

func (m *Int) MinAs(x ...Int) *Int {
	*m = Min(append(x, *m)...)
	return m
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func iai(m int,v int) []int { a := make([]int,m); for i:=0;i<m;i++ { a[i] = v }; return a }
const MOD = 1000000007
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N := gi(); A := gis(N); for i:=0;i<N;i++ { A[i]-- }; B := gis(N); for i:=0;i<N;i++ { B[i]-- }; D := gis(N); for i:=0;i<N;i++ { D[i]-- }
		Arev := make([]int,N); for i:=0;i<N;i++ { Arev[A[i]] = i }
		C := iai(N,-1); ans := 1
		cycleChase := func (idx int) {
			targ := A[idx]; C[idx] = targ;
			for B[idx] != targ { idx = Arev[B[idx]]; C[idx] = A[idx] }
		}
		for i:=0;i<N;i++ {
			if C[i] == -1 && A[i] == B[i] { C[i] = A[i]; continue }
			if C[i] == -1 && D[i] != -1 { cycleChase(i) }
		}
		for i:=0;i<N;i++ {
			if C[i] != -1 { continue }
			ans *= 2; ans %= MOD
			cycleChase(i)
		}
		fmt.Fprintln(wrtr,ans)
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func slove() {
	var n int
	fmt.Fscan(r, &n)
	nums1 := make([]int, n)
	idx1 := make([]int, n+1)
	for i:=0;i<n;i++ {
		fmt.Fscan(r, &nums1[i])
		idx1[nums1[i]] = i
	}
	nums2 := make([]int, n)
	idx2 := make([]int, n+1)
	for i:=0;i<n;i++ {
		fmt.Fscan(r, &nums2[i])
		idx2[nums2[i]] = i
	}
	nums3 := make([]int, n)
	for i:=0;i<n;i++ {
		fmt.Fscan(r, &nums3[i])
	}
	for i := range nums3 {
		if nums1[i] == nums2[i] {
			nums3[i] = nums1[i]
		}
		if nums3[i] != 0 {
			j := i
			for {
				if nums1[j] == nums2[j] {
					break
				}
				if nums1[j] == nums3[j] {
					k := idx1[nums2[j]]
					if nums3[k] == nums1[k] {
						break
					}
					nums3[k] = nums1[k]
					j = k
				} else {
					k := idx2[nums1[j]]
					if nums3[k] == nums2[k] {
						break
					}
					nums3[k] = nums2[k]
					j = k
				}
			}
		}
	}
	uf := newUnionFind(n+1)
	for i := range nums3 {
		if nums3[i] == 0 {
			uf.merge(nums1[i], nums2[i])
		}
	}
	c := map[int]int{}
	for i:=1;i<=n;i++ {
		fa := uf.find(i)
		c[fa]++
	}
	ans := 1
	for _, v := range c {
		if v != 1 {
			ans *= 2
			ans %= 1e9 + 7
		}
	}
	fmt.Fprintln(w, ans)
}

func main() {
	defer w.Flush()
	var n int
	fmt.Fscan(r, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

type unionFind struct {
	fa	[]int
	groups	int
}

func newUnionFind(n int) unionFind {
	fa := make([]int, n)
	for i := range fa {
		fa[i] = i
	}
	return unionFind{fa, n}
}

func (u unionFind) find(x int) int {
	if u.fa[x] != x {
		u.fa[x] = u.find(u.fa[x])
	}
	return u.fa[x]
}

func (u *unionFind) merge(from, to int) (isMerged bool) {
	x, y := u.find(from), u.find(to)
	if x == y {
		return false
	}
	u.fa[x] = y
	u.groups--
	return true
}

func (u unionFind) same(x, y int) bool {
	return u.find(x) == u.find(y)
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	MOD := 1000000007
	var reader *bufio.Reader = bufio.NewReader(os.Stdin)
	var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var T int
	fmt.Scan(&T)
	var n int
	for t := 0; t < T; t++ {
		fmt.Fscan(reader, &n)
		as := make([]int, n)
		bs := make([]int, n)
		ds := make([]int, n)

		a_reverse := make([]int, n)
		b_reverse := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &as[i])
			as[i]--
			a_reverse[as[i]] = i
		}
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &bs[i])
			bs[i]--
			b_reverse[bs[i]] = i
		}
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &ds[i])
		}
		ans := 1
		// cycles := 0
		colored := make([]bool, n)
		for i := 0; i < n; i++ {
			if colored[i] {
				// fmt.Println(i)
				continue
			}
			// for j := 0; j < n; j++ {
			// 	fmt.Print(colored[j], " ")
			// }
			// fmt.Print("\n")
			a := as[i]
			untouched := true
			index := b_reverse[a]

			for index != i {
				colored[index] = true
				if ds[index] != 0 {
					untouched = false
				}
				a = as[index]
				index = b_reverse[a]
			}
			colored[index] = true
			if ds[index] != 0 {
				untouched = false
			}
			// fmt.Println(untouched)
			if untouched && as[i] != bs[i] {
				ans *= 2
				ans %= MOD
			}
		}
		fmt.Fprintln(writer, ans)
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var in, out = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func main() {
	defer out.Flush()

	var tc int
	for fmt.Fscan(in, &tc); tc > 0; tc-- {
		var n int
		fmt.Fscan(in, &n)
		a, b, d := make([]int, n), make([]int, n), make([]int, n)
		aidx, bidx := make([]int, n), make([]int, n)
		for i := range a {
			fmt.Fscan(in, &a[i])
			a[i]--
			aidx[a[i]] = i
		}
		for i := range b {
			fmt.Fscan(in, &b[i])
			b[i]--
			bidx[b[i]] = i
		}
		for i := range d {
			fmt.Fscan(in, &d[i])
			d[i]--
		}

		seen := make([]bool, n)
		for i := range d {
			if d[i] == -1 {
				continue
			}
			p := i
			for !seen[p] {
				seen[p] = true
				other := a[p] ^ b[p] ^ d[p]
				if other == a[p] {
					p = aidx[b[p]]
					d[p] = b[p]
				} else {
					p = bidx[a[p]]
					d[p] = a[p]
				}
			}
		}

		r := int64(1)
		for i := range d {
			if seen[i] || a[i] == b[i] {
				continue
			}
			r = (r * 2) % (1e9 + 7)
			d[i] = a[i]
			p := i
			for !seen[p] {
				seen[p] = true
				other := a[p] ^ b[p] ^ d[p]
				if other == a[p] {
					p = aidx[b[p]]
					d[p] = b[p]
				} else {
					p = bidx[a[p]]
					d[p] = a[p]
				}
			}
		}

		fmt.Fprintln(out, r)
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func modexp(b, p, m int) int {
	if b == 0 { return 0 }
	if p == 0 { return 1 }
	if p == 1 { return b }
	res := modexp(b, p>>1, m)
	res = (res * res) % m
	if p % 2 == 1 { res = (b * res) % m }
	return res
}

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	mod := int(1e9 + 7)
	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, cnt int
		fmt.Fscan(r, &n)

		a := make([]int, n)
		b := make([]int, n)
		d := make([]int, n)
		p := make([]int, n+1)
		vis := make([]bool, n+1)

		for i := range a { fmt.Fscan(r, &a[i]) }
		for i := range b { fmt.Fscan(r, &b[i]) }
		for i := range d { fmt.Fscan(r, &d[i]) }

		for i := range d {
			if a[i] != b[i] {
				p[b[i]] = a[i]
			} else {
				vis[a[i]] = true
			}
		}

		for i, v := range d {
			if !vis[b[i]] {
				t := p[b[i]]
				for t != b[i] {
					vis[t] = true
					t = p[t]
				}
				if v == 0 {
					cnt++
				}
			}
		}

		fmt.Fprintln(w, modexp(2, cnt, mod))

	}

}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var scanner *bufio.Scanner

type Stack []int

func (this *Stack) Push(x int) {
	*this = append(*this, x)
}

func (this *Stack) Empty() bool {
	return len(*this) == 0
}

func (this *Stack) Pop() int {
	var res = (*this)[len(*this)-1]
	*this = (*this)[:len(*this)-1]
	return res
}

func (this *Stack) Top() int {
	if this.Empty() {
		return 0
	}
	return (*this)[len(*this)-1]
}

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 4096 * 4096
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)

	var n, k int
	n = readInt()
	k = readInt()

	var s = Stack{}

	var save = make([]int, k+1)
	var vis = make([]int, n+1)
	for i := 1; i <= k; i++ {
		save[i] = readInt()
		vis[save[i]] = 1
	}

	var p = Stack{}
	for i := 1; i <= n; i++ {
		// fmt.Println(vis[i])
		if vis[i] == 0 {
			p.Push(i)
		} else {
			if !p.Empty() {
				for !p.Empty() {
					save = append(save, p.Pop())
				}
			}
		}
	}
	for !p.Empty() {
		save = append(save, p.Pop())
	}
	// fmt.Println(save)

	var miss = 1
	var ok = true
	for i := 1; i <= n; i++ {
		x := save[i]
		if s.Empty() {
			s.Push(x)
			continue
		}
		for !s.Empty() && x > s.Top() {
			var out = s.Pop()
			if out == miss {
				miss++
			} else {
				ok = false
				break
			}
		}

		if !ok {
			break
		}
		s.Push(x)
	}

	if !ok {
		fmt.Println(-1)
		return
	}

	for i := 1; i <= n; i++ {
		fmt.Printf("%d", save[i])
		if i == n {
			fmt.Println("")
		} else {
			fmt.Print(" ")
		}
	}
}

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

func readInt64() int64 {
	v, _ := strconv.ParseInt(readString(), 10, 64)
	return v
}

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var scanner *bufio.Scanner

type Stack []int

func (this *Stack) Push(x int) {
	*this = append(*this, x)
}

func (this *Stack) Empty() bool {
	return len(*this) == 0
}

func (this *Stack) Pop() int {
	var res = (*this)[len(*this)-1]
	*this = (*this)[:len(*this)-1]
	return res
}

func (this *Stack) Top() int {
	if this.Empty() {
		return 0
	}
	return (*this)[len(*this)-1]
}

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)

	var n, k int
	n = readInt()
	k = readInt()

	var s = Stack{}

	var save = make([]int, k+1)
	var vis = make([]int, n+1)
	for i := 1; i <= k; i++ {
		save[i] = readInt()
		vis[save[i]] = 1
	}

	var p = Stack{}
	for i := 1; i <= n; i++ {
		// fmt.Println(vis[i])
		if vis[i] == 0 {
			p.Push(i)
		} else {
			if !p.Empty() {
				for !p.Empty() {
					save = append(save, p.Pop())
				}
			}
		}
	}
	for !p.Empty() {
		save = append(save, p.Pop())
	}
	// fmt.Println(save)

	var miss = 1
	var ok = true
	for i := 1; i <= n; i++ {
		x := save[i]
		if s.Empty() {
			s.Push(x)
			continue
		}
		for !s.Empty() && x > s.Top() {
			var out = s.Pop()
			if out == miss {
				miss++
			} else {
				ok = false
				break
			}
		}

		if !ok {
			break
		}
		s.Push(x)
	}

	if !ok {
		fmt.Println(-1)
		return
	}

	for i := 1; i <= n; i++ {
		fmt.Printf("%d", save[i])
		if i == n {
			fmt.Println("")
		} else {
			fmt.Print(" ")
		}
	}
}

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

func readInt64() int64 {
	v, _ := strconv.ParseInt(readString(), 10, 64)
	return v
}

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"sort"
	"strconv"
	"strings"
)

// github.com/EndlessCheng/codeforces-go
func CF1081D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	var n, m, k, v int
	Fscan(in, &n, &m, &k)
	sp := make([]bool, n)
	for i := 0; i < k; i++ {
		Fscan(in, &v)
		sp[v-1] = true
	}
	es := make([][3]int, m)
	for i := range es {
		Fscan(in, &es[i][0], &es[i][1], &es[i][2])
	}
	sort.Slice(es, func(i, j int) bool { return es[i][2] < es[j][2] })

	fa := make([]int, n)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	cnt := 1
	merge := func(x, y int) {
		x, y = find(x), find(y)
		if x == y {
			return
		}
		if sp[x] && sp[y] {
			cnt++
			fa[y] = x
		} else if sp[x] {
			fa[y] = x
		} else {
			fa[x] = y
		}
	}
	for i := 0; ; {
		w := es[i][2]
		for ; i < m && es[i][2] == w; i++ {
			merge(es[i][0]-1, es[i][1]-1)
		}
		if cnt == k {
			Fprint(_w, strings.Repeat(strconv.Itoa(w)+" ", k))
			break
		}
	}
}

func main() { CF1081D(os.Stdin, os.Stdout) }

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

type djs struct {
	node   int
	parent *djs
	height int
	hasX   bool
}

// Repr gets representative of this disjoint set.
func (s *djs) repr() *djs {
	if s.parent == nil {
		return s
	}
	return s.parent.repr()
}

func max(i, j int) int {
	if i > j {
		return i
	}
	return j
}

// Join adds t under s.
func (s *djs) join(t *djs) {
	if s.parent != nil {
		panic("join.s.parent is not nil!")
	}
	if t.parent != nil {
		panic("join.s.parent is not nil!")
	}

	if s.height > t.height {
		t.parent = s
		s.height = max(s.height, t.height+1)
		if t.hasX {
			s.hasX = true
		}
	} else {
		s.parent = t
		t.height = max(t.height, s.height+1)
		if s.hasX {
			t.hasX = true
		}
	}
}

func (s *djs) String() string {
	return fmt.Sprintf("{djs:%d}", s.node)
}

type edge struct {
	from, to, weight int
	visited          bool
}

func (e *edge) String() string {
	return fmt.Sprintf("edge<%v>", *e)
}

var (
	n, m, k int
	x       []int

	xes         = make(map[int]struct{})
	edges       = make(map[int]map[int]int)
	edgesBySize []*edge

	setOf = make(map[int]*djs)
)

func dprintf(i string, a ...interface{}) {
	if false {
		fmt.Printf(i+"\n", a...)
	}
}

func findRepr() int {
	dprintf("setof=%v, edges=%s", setOf, edgesBySize)
	farthest := 0
	for _, edge := range edgesBySize {
		fs := setOf[edge.from].repr()
		ts := setOf[edge.to].repr()
		if fs == ts {
			// This edge does not connect two disjoint sets together, skip this edge.
			continue
		}
		if fs.hasX && ts.hasX {
			if edge.weight > farthest {
				farthest = edge.weight
			}
		}

		dprintf("joining %v and %v", fs, ts)
		fs.join(ts)
	}
	return farthest
}

func main() {
	r := bufio.NewReader(os.Stdin)
	scanf := func(x string, i ...interface{}) { fmt.Fscanf(r, x, i...) }

	// Read n, m, k.
	scanf("%d %d %d\n", &n, &m, &k)

	// Read array x.
	x = make([]int, k)
	for i, _ := range x {
		if i == len(x)-1 {
			scanf("%d\n", &x[i])
		} else {
			scanf("%d", &x[i])
		}
		dprintf("read x %d", x[i])
		xes[x[i]] = struct{}{}
	}

	// Populate edgesBySize array.
	edgesBySize = make([]*edge, m)
	var u, v, w int
	for i := 0; i < m; i++ {
		scanf("%d %d %d\n", &u, &v, &w)
		dprintf("read uvw %d%d%d", u, v, w)
		// We need only one edge here.
		e := &edge{u, v, w, false}
		dprintf("reading edge %s", e)
		edgesBySize[i] = e
	}
	sort.Slice(edgesBySize, func(i, j int) bool {
		return edgesBySize[i].weight < edgesBySize[j].weight
	})

	// Populate union-finds.
	for i := 1; i <= n; i++ {
		setOf[i] = &djs{height: 1, node: i}
		if _, ok := xes[i]; ok {
			setOf[i].hasX = true
		}
	}

	// Run the kruskal or whatever is this crap called.
	len := findRepr()
	for i := 0; i < k; i++ {
		fmt.Printf("%d ", len)
	}

	dprintf("n=%d, m=%d, k=%d, x=%d, g=%v", n, m, k, x, nil)
}