Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.

In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$). In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$ — the permutation of size $$$n$$$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.

If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).

NotePlease note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.Due to randomness of input hacks in this problem are forbidden.

// Codeforces 986 B
package main

import (
	"bufio"
	"fmt"
	"strings"
	"strconv"
	"os"
)
var in *bufio.Reader

func readFive() (int,int,int,int,int) {
	var a [5]int
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("first read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for i:=0; i<len(ss); i++ {
		a[i], err = strconv.Atoi(ss[i])
		if err != nil {
			fmt.Println("n atoi failure", err)
			panic(err)
		}
	}
	return a[0],a[1],a[2],a[3],a[4]
}

func readLineNumbs(n int) []int {
	a := make([]int, n)
	delim := byte(' ')
	for i:=0; i<n; i++ {
		if i==(n-1) {
			delim = byte('\n')
		}
		s, err := in.ReadString(delim)
		s = strings.Trim(s, " \n\r")
		if err != nil {
			fmt.Println("read failure", err)
			panic(err)
		}
		aa,err := strconv.Atoi(s)
		if err != nil {
			fmt.Println("aa conv failed", err)
			panic(err)
		}
		a[i] = aa
	}
	return a
}

// binary sums structs and functions
const MAXH = 21
const MAXSZ = 1100000  // > 2 ^ 20
var bsTree [][]int64

func initBsTree() {
    bsTree = make([][]int64, MAXH)
    sz := MAXSZ
    for i:=0; i<MAXH; i++ {
        bsTree[i] = make([]int64, sz)
        sz = sz/2
    }
}

func addv(v int) {
    d := 0
    for d < MAXH {
		bsTree[d][v]++
		d++; v = v/2
    }
}

func getsum(v int) int64 {
	var sum int64 = 0
	d := 0
	for d < MAXH {
		if (v & 1) == 1 {
			sum += bsTree[d][v-1]
			// fmt.Printf("added, d,v,sum = %d %d %d\n", d,v,sum)
		}
		d++; v = v/2
	}
	return sum
}

var n,k int
var p []int
var isPetr bool

func readData() {
	in = bufio.NewReader(os.Stdin)
	n, _, _, _, _ = readFive()
	p = readLineNumbs(n)
}

func solve() {
	initBsTree()
	var nperms int64 = 0
	var nSmaller,nLarger int64
	for i:=0; i<n; i++ {
		nSmaller = getsum(p[i])
		nLarger = int64(i) - nSmaller
		nperms += nLarger
		addv(p[i])
	}
	if (n % 2) == 0 {
		// even n, 3*n even, 7*n + 1 - odd
		isPetr = (nperms % 2) == 0
	} else {
		// odd n, 3*n odd, 7*n + 1 - even
		isPetr = (nperms % 2) == 1
	}
}

func printRes() {
	if isPetr {
		fmt.Println("Petr")
	} else {
		fmt.Println("Um_nik")
	}
}

func main() {
	readData()
	solve()
	printRes()
}


You are given a keyboard that consists of $$$26$$$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.You have to type the word $$$s$$$ on this keyboard. It also consists only of lowercase Latin letters.To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions $$$8$$$, $$$5$$$, $$$12$$$ and $$$15$$$, respectively. Therefore, it will take $$$|5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13$$$ units of time to type the word "hello". Determine how long it will take to print the word $$$s$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of a description contains a keyboard — a string of length $$$26$$$, which consists only of lowercase Latin letters. Each of the letters from 'a' to 'z' appears exactly once on the keyboard. The second line of the description contains the word $$$s$$$. The word has a length from $$$1$$$ to $$$50$$$ letters inclusive and consists of lowercase Latin letters.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to the test case is the minimal time it takes to type the word $$$s$$$ on the given keyboard.

5
abcdefghijklmnopqrstuvwxyz
hello
abcdefghijklmnopqrstuvwxyz
i
abcdefghijklmnopqrstuvwxyz
codeforces
qwertyuiopasdfghjklzxcvbnm
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
qwertyuiopasdfghjklzxcvbnm
abacaba

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 := 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 (
	"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)
  }
}


There are $$$n$$$ robbers at coordinates $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, ..., $$$(a_n, b_n)$$$ and $$$m$$$ searchlight at coordinates $$$(c_1, d_1)$$$, $$$(c_2, d_2)$$$, ..., $$$(c_m, d_m)$$$. In one move you can move each robber to the right (increase $$$a_i$$$ of each robber by one) or move each robber up (increase $$$b_i$$$ of each robber by one). Note that you should either increase all $$$a_i$$$ or all $$$b_i$$$, you can't increase $$$a_i$$$ for some points and $$$b_i$$$ for some other points.Searchlight $$$j$$$ can see a robber $$$i$$$ if $$$a_i \leq c_j$$$ and $$$b_i \leq d_j$$$. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair $$$i,j$$$ such that searchlight $$$j$$$ can see a robber $$$i$$$).What is the minimum number of moves you need to perform to reach a safe configuration?

The first line of input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 2000$$$): the number of robbers and the number of searchlight. Each of the next $$$n$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$ ($$$0 \leq a_i, b_i \leq 10^6$$$), coordinates of robbers. Each of the next $$$m$$$ lines contains two integers $$$c_i$$$, $$$d_i$$$ ($$$0 \leq c_i, d_i \leq 10^6$$$), coordinates of searchlights.

Print one integer: the minimum number of moves you need to perform to reach a safe configuration.

NoteIn the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates $$$(3, 0)$$$.The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates $$$(2, 3)$$$ and $$$3 > 2$$$.In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates $$$(3, 8)$$$, $$$(8, 3)$$$.It's easy the see that the configuration of the robbers is safe.It can be proved that you can't reach a safe configuration using no more than $$$3$$$ moves.

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


The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.In the Pindows operating system a strings are the lexemes of the command line — the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command " run.exe one, two . ", we give four lexemes to the Pindows command line: "run.exe", "one,", "two", ".". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited — that is, for each occurrence of character """ we should be able to say clearly that the quotes are opening or closing. For example, as we run the command ""run.exe o" "" " ne, " two . " " ", we give six lexemes to the Pindows command line: "run.exe o", "" (an empty string), " ne, ", "two", ".", " " (a single space).It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.You have a string that consists of uppercase and lowercase English letters, digits, characters ".,?!"" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character """ to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters.

The single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the ".,?!"" signs, or a space. It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme.

In the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the "<" (less) character to the left of your lexemes and the ">" (more) character to the right. Print the lexemes in the order in which they occur in the command. Please, follow the given output format strictly. For more clarifications on the output format see the test samples.

"RUn.exe O" "" "   2ne, " two! . " "
firstarg   second   ""

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 _, 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 (
    "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 _, 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()
}


Daniel is watching a football team playing a game during their training session. They want to improve their passing skills during that session.The game involves $$$n$$$ players, making multiple passes towards each other. Unfortunately, since the balls were moving too fast, after the session Daniel is unable to know how many balls were involved during the game. The only thing he knows is the number of passes delivered by each player during all the session.Find the minimum possible amount of balls that were involved in the game.

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of players. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$), where $$$a_i$$$ is the number of passes delivered by the $$$i$$$-th player. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the first test case, with the only ball, the game can go like this:$$$2 \rightarrow 1 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 2$$$.In the second test case, there is no possible way to play the game with only one ball. One possible way to play with two balls:$$$2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 1$$$.$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1$$$In the third example, there were no passes, so $$$0$$$ balls are possible.

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"
	"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 (
	"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"
	"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
}


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

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

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

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

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)
	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"
	"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))

	}

}


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

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

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

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
}


Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago.You are given a connected undirected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. There are $$$k$$$ special vertices: $$$x_1, x_2, \ldots, x_k$$$.Let's define the cost of the path as the maximum weight of the edges in it. And the distance between two vertexes as the minimum cost of the paths connecting them.For each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them.The original constraints are really small so he thought the problem was boring. Now, he raises the constraints and hopes you can solve it for him.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \leq k \leq n \leq 10^5$$$, $$$n-1 \leq m \leq 10^5$$$) — the number of vertices, the number of edges and the number of special vertices. The second line contains $$$k$$$ distinct integers $$$x_1, x_2, \ldots, x_k$$$ ($$$1 \leq x_i \leq n$$$). Each of the following $$$m$$$ lines contains three integers $$$u$$$, $$$v$$$ and $$$w$$$ ($$$1 \leq u,v \leq n, 1 \leq w \leq 10^9$$$), denoting there is an edge between $$$u$$$ and $$$v$$$ of weight $$$w$$$. The given graph is undirected, so an edge $$$(u, v)$$$ can be used in the both directions. The graph may have multiple edges and self-loops. It is guaranteed, that the graph is connected.

The first and only line should contain $$$k$$$ integers. The $$$i$$$-th integer is the distance between $$$x_i$$$ and the farthest special vertex from it.

NoteIn the first example, the distance between vertex $$$1$$$ and $$$2$$$ equals to $$$2$$$ because one can walk through the edge of weight $$$2$$$ connecting them. So the distance to the farthest node for both $$$1$$$ and $$$2$$$ equals to $$$2$$$.In the second example, one can find that distance between $$$1$$$ and $$$2$$$, distance between $$$1$$$ and $$$3$$$ are both $$$3$$$ and the distance between $$$2$$$ and $$$3$$$ is $$$2$$$.The graph may have multiple edges between and self-loops, as in the first example.

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

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