On the way to school, Karen became fixated on the puzzle game on her phone!  The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!

The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500).

If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done:   row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row".  col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column".  If there are multiple optimal solutions, output any one of them.

NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level:  In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level:  Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3.

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

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

	n := readInt()
	m := readInt()
	a := make([][]int, n)
	for i := range a {
		a[i] = make([]int, m)
		for j := range a[i] {
			a[i][j] = readInt()
		}
	}
	var rows, cols []int
	handleRows := func() {
		for i := range a {
			mi := 500
			for j := range a[i] {
				if x := a[i][j]; mi > x {
					mi = x
				}
			}
			for j := 0; j < mi; j++ {
				rows = append(rows, i+1)
			}
			for j := range a[i] {
				a[i][j] -= mi
			}
		}
	}
	handleCols := func() {
		for j := range a[0] {
			mi := 500
			for i := range a {
				if x := a[i][j]; mi > x {
					mi = x
				}
			}
			for i := 0; i < mi; i++ {
				cols = append(cols, j+1)
			}
			for i := range a {
				a[i][j] -= mi
			}
		}
	}
	if n < m {
		handleRows()
		handleCols()
	} else {
		handleCols()
		handleRows()
	}
	for i := range a {
		for j := range a[i] {
			if a[i][j] != 0 {
				fmt.Println(-1)
				return
			}
		}
	}
	fmt.Fprintln(out, len(rows)+len(cols))
	for _, i := range rows {
		fmt.Fprintln(out, "row", i)
	}
	for _, i := range cols {
		fmt.Fprintln(out, "col", i)
	}
}

package main

import (
	"fmt"
)

func main() {
	arr, invertDim := scan()

	rowSubstract := make([]int, len(arr))
	for i, row := range arr {
		min := min(row)
		rowSubstract[i] = min
		substract(row, rowSubstract[i])
	}

	colSubstract := arr[0]
	for _, row := range arr {
		for j, cell := range row {
			if cell != colSubstract[j] {
				fmt.Println("-1")
				return
			}
		}
	}

	fmt.Println(sum(rowSubstract) + sum(colSubstract))
	if invertDim {
		print("row", colSubstract)
		print("col", rowSubstract)
	} else {
		print("row", rowSubstract)
		print("col", colSubstract)
	}
}

func scan() (arr [][]int, invertDim bool) {
	var n, m int
	fmt.Scan(&n, &m)
	if n > m {
		invertDim = true
		n, m = m, n
	}
	arr = make([][]int, n)
	for i := range arr {
		arr[i] = make([]int, m)
	}
	if invertDim {
		for j := range arr[0] {
			for i := range arr {
				fmt.Scan(&arr[i][j])
			}
		}
	} else {
		for i := range arr {
			for j := range arr[i] {
				fmt.Scan(&arr[i][j])
			}
		}
	}
	return
}

func min(arr []int) (min int) {
	min = arr[0]
	for _, v := range arr {
		if min > v {
			min = v
		}
	}
	return
}

func substract(arr []int, diff int) {
	for i := range arr {
		arr[i] -= diff
	}
}

func sum(arr []int) (sum int) {
	for _, v := range arr {
		sum += v
	}
	return
}

func print(label string, vals []int) {
	for i, n := range vals {
		for j := 0; j < n; j++ {
			fmt.Println(label, i+1)
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	col := make([]int, n)
	row := make([]int, m)
	for j := range row {
		fmt.Scan(&row[j])
	}
	col[0] = extractMin(row)
	for i := 1; i < n; i++ {
		var v int
		fmt.Scan(&v)
		col[i] = v - row[0]
		if col[i] < 0 {
			fmt.Println("-1")
			return
		}
		for j := 1; j < m; j++ {
			fmt.Scan(&v)
			if col[i] != v-row[j] {
				fmt.Println("-1")
				return
			}
		}
	}
	base := extractMin(col)
	sum := sum(row) + sum(col)
	if n > m {
		fmt.Println(sum + base*m)
		for i := range row {
			for j := 0; j < base; j++ {
				fmt.Println("col", i+1)
			}
		}
	} else {
		fmt.Println(sum + base*n)
		for j := range col {
			for i := 0; i < base; i++ {
				fmt.Println("row", j+1)
			}
		}
	}
	for i, v := range row {
		for k := 0; k < v; k++ {
			fmt.Println("col", i+1)
		}
	}
	for j, v := range col {
		for k := 0; k < v; k++ {
			fmt.Println("row", j+1)
		}
	}
}

func extractMin(arr []int) int {
	min := arr[0]
	for _, v := range arr {
		if min > v {
			min = v
		}
	}
	for i := range arr {
		arr[i] -= min
	}
	return min
}

func sum(arr []int) int {
	res := 0
	for _, v := range arr {
		res += v
	}
	return res
}

// Codeforces My Practice
// author: Leonardone @ NEETSDKASU
package main

import "fmt"

type tup struct {
	rc bool
	p  int
}

func rows(f [][]int, ans []tup) []tup {
	for i := range f {
		min := 9999
		for j := range f[i] {
			if f[i][j] < min {
				min = f[i][j]
			}
		}
		for k := 0; k < min; k++ {
			ans = append(ans, tup{true, i + 1})
		}
		for j := range f[i] {
			f[i][j] -= min
		}
	}
	return ans
}

func cols(f [][]int, ans []tup) []tup {
	for j := range f[0] {
		min := 9999
		for i := range f {
			if f[i][j] < min {
				min = f[i][j]
			}
		}
		for k := 0; k < min; k++ {
			ans = append(ans, tup{false, j + 1})
		}
		for i := range f {
			f[i][j] -= min
		}
	}
	return ans
}

func main() {
	ans := make([]tup, 0, 10000)
	var n, m int
	fmt.Scan(&n, &m)
	f := make([][]int, n)
	for i := range f {
		f[i] = make([]int, m)
		for j := range f[i] {
			fmt.Scan(&f[i][j])
		}
	}
	if n < m {
		ans = rows(f, ans)
		ans = cols(f, ans)
	} else {
		ans = cols(f, ans)
		ans = rows(f, ans)
	}
	for _, ff := range f {
		for _, v := range ff {
			if v > 0 {
				fmt.Println(-1)
				return
			}
		}
	}
	fmt.Println(len(ans))
	for _, t := range ans {
		if t.rc {
			fmt.Println("row", t.p)
		} else {
			fmt.Println("col", t.p)
		}
	}
}

package main

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

func main() {
	sc := NewScanner()
	n, m := sc.NextInt(), sc.NextInt()
	grid := make([][]int, n)
	grid2 := make([][]int, n)

	for i := 0; i < n; i++ {
		grid[i] = sc.NextIntArray()
		grid2[i] = make([]int, m)
		for j := 0; j < m; j++ {
			grid2[i][j] = grid[i][j]
		}
	}
	ansFlag := true
	ans := make([]string, 0)
	for i := 0; i < n; i++ {
		mn := grid[i][0]
		for j := 0; j < m; j++ {
			if mn > grid[i][j] {
				mn = grid[i][j]
			}
		}

		for k := 0; k < mn; k++ {
			ans = append(ans, fmt.Sprintf("row %d", i+1))
		}
		for j := 0; j < m; j++ {
			grid[i][j] -= mn
		}
	}

	for j := 0; j < m; j++ {
		mn := grid[0][j]
		for i := 0; i < n; i++ {
			if mn > grid[i][j] {
				mn = grid[i][j]
			}
		}

		for k := 0; k < mn; k++ {
			ans = append(ans, fmt.Sprintf("col %d", j+1))
		}
		for i := 0; i < n; i++ {
			grid[i][j] -= mn
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if 0 < grid[i][j] {
				ansFlag = false
				goto A
			}
		}
	}
A:
	ans2 := make([]string, 0)
	ans2Flag := true

	for j := 0; j < m; j++ {
		mn := grid2[0][j]
		for i := 0; i < n; i++ {
			if mn > grid2[i][j] {
				mn = grid2[i][j]
			}
		}

		for k := 0; k < mn; k++ {
			ans2 = append(ans2, fmt.Sprintf("col %d", j+1))
		}
		for i := 0; i < n; i++ {
			grid2[i][j] -= mn
		}
	}

	for i := 0; i < n; i++ {
		mn := grid2[i][0]
		for j := 0; j < m; j++ {
			if mn > grid2[i][j] {
				mn = grid2[i][j]
			}
		}

		for k := 0; k < mn; k++ {
			ans2 = append(ans2, fmt.Sprintf("row %d", i+1))
		}
		for j := 0; j < m; j++ {
			grid2[i][j] -= mn
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if 0 < grid[i][j] {
				ans2Flag = false
				goto B
			}
		}
	}
B:
	var A []string
	if ansFlag {
		A = ans
	}
	if ans2Flag {
		if A == nil || len(A) > len(ans2) {
			A = ans2
		}
	}

	if A == nil {
		fmt.Println(-1)
		return
	}
	fmt.Println(len(A))
	for _, v := range A {
		fmt.Println(v)
	}

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	arr := scan()

	rowSubstract := make([]int, len(arr))
	for i, row := range arr {
		min := min(row)
		rowSubstract[i] = min
		substract(row, rowSubstract[i])
	}

	colSubstract := arr[0]
	for _, row := range arr {
		for j, cell := range row {
			if cell != colSubstract[j] {
				fmt.Println("-1")
				return
			}
		}
	}

	fmt.Println(sum(rowSubstract) + sum(colSubstract))
	print("row", rowSubstract)
	print("col", colSubstract)
}

func scan() [][]int {
	var n, m int
	fmt.Scan(&n, &m)
	arr := make([][]int, n)
	for i := range arr {
		arr[i] = make([]int, m)
		for j := range arr[i] {
			fmt.Scan(&arr[i][j])
		}
	}
	return arr
}

func min(arr []int) (min int) {
	min = arr[0]
	for _, v := range arr {
		if min > v {
			min = v
		}
	}
	return
}

func substract(arr []int, diff int) {
	for i := range arr {
		arr[i] -= diff
	}
}

func sum(arr []int) (sum int) {
	for _, v := range arr {
		sum += v
	}
	return
}

func print(label string, vals []int) {
	for i, n := range vals {
		for j := 0; j < n; j++ {
			fmt.Println(label, i)
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	col := make([]int, n)
	row := make([]int, m)
	for j := range row {
		fmt.Scan(&row[j])
	}
	col[0] = extractMin(row)
	for i := 1; i < n; i++ {
		var v int
		fmt.Scan(&v)
		col[i] = v - row[0]
		if col[i] < 0 {
			fmt.Println("-1")
			return
		}
		for j := 1; j < m; j++ {
			fmt.Scan(&v)
			if col[i] != v-row[j] {
				fmt.Println("-1")
				return
			}
		}
	}
	base := extractMin(col)
	sum := sum(row) + sum(col)
	if n > m {
		fmt.Println(sum + base*m)
		for i := range row {
			for j := 0; j < base; j++ {
				fmt.Println("row", i+1)
			}
		}
	} else {
		fmt.Println(sum + base*n)
		for j := range col {
			for i := 0; i < base; i++ {
				fmt.Println("col", j+1)
			}
		}
	}
	for i, v := range row {
		for k := 0; k < v; k++ {
			fmt.Println("col", i+1)
		}
	}
	for j, v := range col {
		for k := 0; k < v; k++ {
			fmt.Println("row", j+1)
		}
	}
}

func extractMin(arr []int) int {
	min := arr[0]
	for _, v := range arr {
		if min > v {
			min = v
		}
	}
	for i := range arr {
		arr[i] -= min
	}
	return min
}

func sum(arr []int) int {
	res := 0
	for _, v := range arr {
		res += v
	}
	return res
}

package main

import (
	"fmt"
)

func main() {
	arr := scan()

	rowSubstract := make([]int, len(arr))
	for i, row := range arr {
		min := min(row)
		rowSubstract[i] = min
		substract(row, rowSubstract[i])
	}

	colSubstract := arr[0]
	for _, row := range arr {
		for j, cell := range row {
			if cell != colSubstract[j] {
				fmt.Println("-1")
				return
			}
		}
	}

	fmt.Println(sum(rowSubstract) + sum(colSubstract))
	print("row", rowSubstract)
	print("col", colSubstract)
}

func scan() [][]int {
	var n, m int
	fmt.Scan(&n, &m)
	arr := make([][]int, n)
	for i := range arr {
		arr[i] = make([]int, m)
		for j := range arr[i] {
			fmt.Scan(&arr[i][j])
		}
	}
	return arr
}

func min(arr []int) (min int) {
	min = arr[0]
	for _, v := range arr {
		if min > v {
			min = v
		}
	}
	return
}

func substract(arr []int, diff int) {
	for i := range arr {
		arr[i] -= diff
	}
}

func sum(arr []int) (sum int) {
	for _, v := range arr {
		sum += v
	}
	return
}

func print(label string, vals []int) {
	for i, n := range vals {
		for j := 0; j < n; j++ {
			fmt.Println(label, i+1)
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	col := make([]int, n)
	row := make([]int, m)
	for j := range row {
		fmt.Scan(&row[j])
	}
	col[0] = extractMin(row)
	for i := 1; i < n; i++ {
		var v int
		fmt.Scan(&v)
		col[i] = v - row[0]
		if col[i] < 0 {
			fmt.Println("-1")
			return
		}
		for j := 1; j < m; j++ {
			fmt.Scan(&v)
			if col[i] != v-row[j] {
				fmt.Println("-1")
				return
			}
		}
	}
	base := extractMin(col)
	if n < m {
		for i := range row {
			for j := 0; j < base; j++ {
				fmt.Println("row", i+1)
			}
		}
	} else {
		for j := range col {
			for i := 0; i < base; i++ {
				fmt.Println("col", j+1)
			}
		}
	}
	for i, v := range row {
		for k := 0; k < v; k++ {
			fmt.Println("col", i+1)
		}
	}
	for j, v := range col {
		for k := 0; k < v; k++ {
			fmt.Println("row", j+1)
		}
	}
}

func extractMin(arr []int) int {
	min := arr[0]
	for _, v := range arr {
		if min > v {
			min = v
		}
	}
	for i := range arr {
		arr[i] -= min
	}
	return min
}

package main

import (
	"fmt"
)

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	col := make([]int, n)
	row := make([]int, m)
	for j := range row {
		fmt.Scan(&row[j])
	}
	col[0] = extractMin(row)
	for i := 1; i < n; i++ {
		var v int
		fmt.Scan(&v)
		col[i] = v - row[0]
		if col[i] < 0 {
			fmt.Println("-1")
			return
		}
		for j := 1; j < m; j++ {
			fmt.Scan(&v)
			if col[i] != v-row[j] {
				fmt.Println("-1")
				return
			}
		}
	}
	base := extractMin(col)
	sum := sum(row) + sum(col)
	if n < m {
		fmt.Println(sum + base*len(row))
		for i := range row {
			for j := 0; j < base; j++ {
				fmt.Println("row", i+1)
			}
		}
	} else {
		fmt.Println(sum + base*len(col))
		for j := range col {
			for i := 0; i < base; i++ {
				fmt.Println("col", j+1)
			}
		}
	}
	for i, v := range row {
		for k := 0; k < v; k++ {
			fmt.Println("col", i+1)
		}
	}
	for j, v := range col {
		for k := 0; k < v; k++ {
			fmt.Println("row", j+1)
		}
	}
}

func extractMin(arr []int) int {
	min := arr[0]
	for _, v := range arr {
		if min > v {
			min = v
		}
	}
	for i := range arr {
		arr[i] -= min
	}
	return min
}

func sum(arr []int) int {
	res := 0
	for _, v := range arr {
		res += v
	}
	return res
}

package main

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

func main() {
	sc := NewScanner()
	n, m := sc.NextInt(), sc.NextInt()
	grid := make([][]int, n)
	grid2 := make([][]int, n)

	for i := 0; i < n; i++ {
		grid[i] = sc.NextIntArray()
		grid2[i] = make([]int, m)
		for j := 0; j < m; j++ {
			grid2[i][j] = grid[i][j]
		}
	}

	ans := make([]string, 0)
	for i := 0; i < n; i++ {
		mn := grid[i][0]
		for j := 0; j < m; j++ {
			if mn > grid[i][j] {
				mn = grid[i][j]
			}
		}

		for k := 0; k < mn; k++ {
			ans = append(ans, fmt.Sprintf("row %d", i+1))
		}
		for j := 0; j < m; j++ {
			grid[i][j] -= mn
		}
	}

	for j := 0; j < m; j++ {
		mn := grid[0][j]
		for i := 0; i < n; i++ {
			if mn > grid[i][j] {
				mn = grid[i][j]
			}
		}

		for k := 0; k < mn; k++ {
			ans = append(ans, fmt.Sprintf("col %d", j+1))
		}
		for i := 0; i < n; i++ {
			grid[i][j] -= mn
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if 0 < grid[i][j] {
				fmt.Println(-1)
				return
			}
		}
	}

	ans2 := make([]string, 0)

	for j := 0; j < m; j++ {
		mn := grid2[0][j]
		for i := 0; i < n; i++ {
			if mn > grid2[i][j] {
				mn = grid2[i][j]
			}
		}

		for k := 0; k < mn; k++ {
			ans2 = append(ans2, fmt.Sprintf("col %d", j+1))
		}
		for i := 0; i < n; i++ {
			grid2[i][j] -= mn
		}
	}

	for i := 0; i < n; i++ {
		mn := grid2[i][0]
		for j := 0; j < m; j++ {
			if mn > grid2[i][j] {
				mn = grid2[i][j]
			}
		}

		for k := 0; k < mn; k++ {
			ans2 = append(ans2, fmt.Sprintf("row %d", i+1))
		}
		for j := 0; j < m; j++ {
			grid2[i][j] -= mn
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if 0 < grid[i][j] {
				fmt.Println(-1)
				return
			}
		}
	}

	if len(ans) < len(ans2) {
		fmt.Println(len(ans))
		for _, v := range ans {
			fmt.Println(v)
		}
	} else {
		if len(ans) > len(ans2) {
			fmt.Println(len(ans2))
			for _, v := range ans2 {
				fmt.Println(v)
			}
		}

	}

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}


User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≤ k ≤ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak < bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≤ i, j ≤ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.

The first line contains an integer n (1 ≤ n ≤ 300) — the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn — the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≤ i < j ≤ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≤ i ≤ n, Ai, i = 0 holds.

In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.

NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4).   A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

var a [][]bool
var p []int
var used []bool
var n int
//Wrong

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n = nextInt()
	a = make([][]bool, n)
	p = make([]int, n)
	used = make([]bool, n)

	for i := 0; i < n; i++ {
		p[i] = nextInt()
	}

	for i := range a {
		a[i] = make([]bool, n)
		s := next()
		for j := range s {
			// print(j, s[j], " ")
			if s[j] == '1' {
				a[i][j] = true
			}
		}
		// println()
	}

	// for i := range a {
	// 	println(a[i])
	// }
	// println()
	for i := range a {
		if !used[i] {
			dfs(i)
		}
	}
	// println('1')
	// for i := range a {
	// 	println(a[i])
	// }
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			if p[i] > p[j] && a[i][j] {
				p[i], p[j] = p[j], p[i]
			}
		}
	}

	for i := range p {
		print(p[i], " ")
	}

	println()
}

func dfs(x int) {
	used[x] = true

	for i := 0; i < n; i++ {
		if a[x][i] {
			for j := 0; j < n; j++ {
				if a[x][j] {
					// println(x, i, j)
					a[i][j] = true
				}
			}

			if !used[i] {
				dfs(i)
			}
		}
	}
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	//fmt.Println(matrix)
	for i, line := range matrix {
		for j, val := range line {
			if val == '1' {
				s.union(i, j)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

func (s *Solver) Solve() []int {
	numbersInUnions := make([][]int, len(s.permutation))
	for i := range numbersInUnions {
		numbersInUnions[i] = make([]int, 0)
	}
	//
	//fmt.Println(s.permutation)
	//fmt.Println(s.unions)

	for i, val := range s.permutation {
		index := s.find(i)
		//fmt.Println(i, val, index)
		numbersInUnions[index] = append(numbersInUnions[index], val)
	}

	for _, arr := range numbersInUnions {
		sort.Ints(arr)
	}

	ans := make([]int, len(s.permutation))
	lastUsedIndex := make([]int, len(s.permutation))
	for i := range s.permutation {
		index := s.find(i)
		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
		lastUsedIndex[index] += 1
	}

	return ans
}

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

	permutation := make([]int, n)
	for i := range permutation {
		format := "%d "
		if i + 1 == len(permutation) {
			format = "%d\n"
		}
		fmt.Fscanf(inBuf,format, &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	answer := solver.Solve()

	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	for _, val := range answer {
		fmt.Fprintf(outBuf, "%d ", val)
	}
	fmt.Fprintf(outBuf, "\n")
}

package main

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

var (
	scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
	writer  *bufio.Writer  = bufio.NewWriter(os.Stdout)
	n       int
	p       []int
	A       [][]bool
)

func in() {
	n = readInt()
	p = make([]int, n)
	for i := 0; i < n; i++ {
		p[i] = readInt()
	}
	A = make([][]bool, n)
	for i := 0; i < n; i++ {
		A[i] = make([]bool, n)
		var line string = readString()
		for j, ch := range line {
			A[i][j] = ch == '1'
		}
	}
}

func out() {
	printInt(p[0])
	for i := 1; i < n; i++ {
		printSpace()
		printInt(p[i])
	}
	printLine()
	defer writer.Flush()
}

func run() {
	for k := 0; k < n; k++ {
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				if A[i][k] && A[j][k] && !A[i][j] {
					A[i][j] = true
				}
			}
		}
	}

	for i := 0; i < n-1; i++ {
		var min_j int = 0
		min := p[i]
		for j := i + 1; j < n; j++ {
			if A[i][j] && p[j] < min {
				min = p[j]
				min_j = j
			}
		}
		if min_j > 0 {
			p[i], p[min_j] = p[min_j], p[i]
		}
	}
}

func main() {
	scanner.Split(bufio.ScanWords)
	in()
	run()
	out()
}

// Read.

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

func readLine() string {
	scanner.Split(bufio.ScanLines)
	defer scanner.Split(bufio.ScanWords)
	return readString()
}

func readInt() int {
	ans, _ := strconv.ParseInt(readString(), 10, 0)
	return int(ans)
}

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

func readFloat64() float64 {
	ans, _ := strconv.ParseFloat(readString(), 64)
	return ans
}

// Write.

func printString(value string) {
	writer.WriteString(value)
}

func printLine() {
	printString("\n")
}

func printSpace() {
	printString(" ")
}

func printInt(value int) {
	printString(strconv.FormatInt(int64(value), 10))
}

func printInt64(value int64) {
	printString(strconv.FormatInt(value, 10))
}

func printFloat64(value float64) {
	printString(strconv.FormatFloat(value, 'f', 20, 64))
}

package main

import (
	"fmt"
)

var (
	n int
	p []int
	A [][]bool
)

func in() {
	fmt.Scan(&n)
	p = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&p[i])
	}
	A = make([][]bool, n)
	for i := 0; i < n; i++ {
		A[i] = make([]bool, n)
		var line string
		fmt.Scan(&line)
		for j, ch := range line {
			A[i][j] = ch == '1'
		}
	}
}

func out() {
	fmt.Print(p[0])
	for i := 1; i < n; i++ {
		fmt.Print(" ", p[i])
	}
	fmt.Println()
}

func run() {
	for k := 0; k < n; k++ {
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				if A[i][k] && A[j][k] && !A[i][j] {
					A[i][j] = true
				}
			}
		}
	}

	for i := 0; i < n-1; i++ {
		var min_j int = 0
		min := p[i]
		for j := i + 1; j < n; j++ {
			if A[i][j] && p[j] < min {
				min = p[j]
				min_j = j
			}
		}
		if min_j > 0 {
			p[i], p[min_j] = p[min_j], p[i]
		}
	}
}

func main() {
	in()
	run()
	out()
}

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/500/B

package main

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

func Solve(n int, p []int, a []string) []int {
	visited := make(map[int]bool)
	components := [][]int{}
	for i := 1; i <= n; i++ {
		if !visited[i] {
			queue := []int{i}
			visited[i] = true
			component := []int{}
			for len(queue) > 0 {
				curr := queue[0]
				queue = queue[1:]
				component = append(component, curr)
				for j := 1; j <= n; j++ {
					if curr != j && a[curr-1][j-1] == '1' && !visited[j] {
						visited[j] = true
						queue = append(queue, j)
					}
				}
			}
			components = append(components, component)
		}
	}
	for _, c := range components {
		sort.Ints(c)
		pc := make([]int, len(c))
		for i, elem := range c {
			pc[i] = p[elem-1]
		}
		sort.Ints(pc)
		for i, elem := range c {
			p[elem-1] = pc[i]
		}
	}
	return p
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	p := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &p[i])
	}
	fmt.Fscanf(reader, "\n")
	a := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%s\n", &a[i])
	}

	for _, elem := range Solve(n, p, a) {
		fmt.Fprintf(writer, "%d ", elem)
	}
	fmt.Fprintf(writer, "\n")
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	p := make([]int, n)
	a := make([]string, n)

	for i := 0; i < n; i++ {
		p[i] = nextInt()
	}

	for i := 0; i < n; i++ {
		a[i] = next()
	}

	for i := 0; i < n; i++ {
		if swapRow(i, p, a) {
			for j := 0; j < len(p); j++ {
				swapRow(j, p, a)
			}
		}
	}
	println(p)
}

func swapRow(i int, p []int, a []string) bool {
	index := i

	for j := i + 1; j < len(p); j++ {
		if a[i][j] == '1' && p[index] > p[j] {
			index = j
		}
	}

	if i != index {
		p[i], p[index] = p[index], p[i]
		// println(p, i, index)
		return true
	}

	// println(p, i, index)
	return false
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	p := make([]int, n)
	a := make([]string, n)

	for i := 0; i < n; i++ {
		p[i] = nextInt()
	}

	for i := 0; i < n; i++ {
		a[i] = next()
	}

	for i := 0; i < n; i++ {
		if swapRow(i, p, a) {
			for j := 0; j < len(p); j++ {
				swapRow(j, p, a)
			}
		}
	}
	println(p)
}

func swapRow(i int, p []int, a []string) bool {
	index := i

	for j := i + 1; j < len(p); j++ {
		if a[i][j] == '1' && p[index] > p[j] {
			index = j
		}
	}

	if i != index {
		p[i], p[index] = p[index], p[i]
		println(p, i, index)
		return true
	}

	println(p, i, index)
	return false
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	p := make([]int, n)
	a := make([]string, n)

	for i := 0; i < n; i++ {
		p[i] = nextInt()
	}

	for i := 0; i < n; i++ {
		a[i] = next()
	}

	checkAll(p, a)

	for i := 0; i < len(p); i++ {
		print(p[i], " ")
	}
}

func checkAll(p []int, a []string) {
	for i := 0; i < len(p); i++ {
		swapCol(i, p, a)
	}
}

func swapCol(index int, p []int, a []string) {

	for j := 0; j < index; j++ {
		if a[index][j] == '1' && p[index] < p[j] {
			p[index], p[j] = p[j], p[index]
			println(p, index, j)
			checkAll(p, a)
			break
		}
	}

	i := index

	for j := index + 1; j < len(p); j++ {
		if a[index][j] == '1' && p[i] > p[j] {
			i = j
		}
	}

	if index != i {
		p[index], p[i] = p[i], p[index]
		println(p, index, i)
		checkAll(p, a)
	}

	// println(p, index, i)
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	p := make([]int, n)
	a := make([]string, n)

	for i := 0; i < n; i++ {
		p[i] = nextInt()
	}

	for i := 0; i < n; i++ {
		a[i] = next()
	}

	checkAll(p, a)

	for i := 0; i < len(p); i++ {
		print(p[i], " ")
	}
}

func checkAll(p []int, a []string) {
	for i := 0; i < len(p); i++ {
		swapCol(i, p, a)
	}
}

func swapCol(index int, p []int, a []string) {

	for j := 0; j < index; j++ {
		if a[index][j] == '1' && p[index] < p[j] {
			p[index], p[j] = p[j], p[index]
			// println(p, index, j)
			checkAll(p, a)
			break
		}
	}

	i := index

	for j := index + 1; j < len(p); j++ {
		if a[index][j] == '1' && p[i] > p[j] {
			i = j
		}
	}

	if index != i {
		p[index], p[i] = p[i], p[index]
		// println(p, index, i)
		checkAll(p, a)
	}

	// println(p, index, i)
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	for i, line := range matrix {
		for j, val := range line {
			if i > j && val == '1' && s.find(i) != s.find(j) {
				s.union(i, j)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

func (s *Solver) Solve() []int {
	numbersInUnions := make([][]int, len(s.permutation))
	for i := range numbersInUnions {
		numbersInUnions[i] = make([]int, 0)
	}

	fmt.Println(s.permutation)
	fmt.Println(s.unions)

	for i, val := range s.permutation {
		index := s.find(i)
		fmt.Println(i, val, index)
		numbersInUnions[index] = append(numbersInUnions[index], val)
	}

	for _, arr := range numbersInUnions {
		sort.Ints(arr)
	}

	ans := make([]int, len(s.permutation))
	lastUsedIndex := make([]int, len(s.permutation))
	for i := range s.permutation {
		index := s.find(i)
		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
		lastUsedIndex[index] += 1
	}

	return ans
}

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

	permutation := make([]int, n)
	for i := range permutation {
		fmt.Fscanf(inBuf,"%d ", &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	answer := solver.Solve()

	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	for _, val := range answer {
		fmt.Fprintf(outBuf, "%d ", val)
	}
	fmt.Fprintf(outBuf, "\n")
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	for i, line := range matrix {
		for j, val := range line {
			if val == '1' {
				s.union(i, j)
				fmt.Println(i, j, s.unions)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

//func (s *Solver) Solve() []int {
//	numbersInUnions := make([][]int, len(s.permutation))
//	for i := range numbersInUnions {
//		numbersInUnions[i] = make([]int, 0)
//	}
//
//	fmt.Println(s.permutation)
//	fmt.Println(s.unions)
//
//	for i, val := range s.permutation {
//		index := s.find(i)
//		fmt.Println(i, val, index)
//		numbersInUnions[index] = append(numbersInUnions[index], val)
//	}
//
//	for _, arr := range numbersInUnions {
//		sort.Ints(arr)
//	}
//
//	ans := make([]int, len(s.permutation))
//	lastUsedIndex := make([]int, len(s.permutation))
//	for i := range s.permutation {
//		index := s.find(i)
//		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
//		lastUsedIndex[index] += 1
//	}
//
//	return ans
//}

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

	permutation := make([]int, n)
	for i := range permutation {
		fmt.Fscanf(inBuf,"%d ", &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	//answer := solver.Solve()
	//
	//outBuf := bufio.NewWriter(os.Stdout)
	//defer func() { outBuf.Flush() }()
	//
	//for _, val := range answer {
	//	fmt.Fprintf(outBuf, "%d ", val)
	//}
	//fmt.Fprintf(outBuf, "\n")
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	fmt.Println(matrix)
	for i, line := range matrix {
		for j, val := range line {
			if val == '1' {
				s.union(i, j)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

func (s *Solver) Solve() []int {
	numbersInUnions := make([][]int, len(s.permutation))
	for i := range numbersInUnions {
		numbersInUnions[i] = make([]int, 0)
	}

	fmt.Println(s.permutation)
	fmt.Println(s.unions)

	for i, val := range s.permutation {
		index := s.find(i)
		fmt.Println(i, val, index)
		numbersInUnions[index] = append(numbersInUnions[index], val)
	}

	for _, arr := range numbersInUnions {
		sort.Ints(arr)
	}

	ans := make([]int, len(s.permutation))
	lastUsedIndex := make([]int, len(s.permutation))
	for i := range s.permutation {
		index := s.find(i)
		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
		lastUsedIndex[index] += 1
	}

	return ans
}

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

	permutation := make([]int, n)
	for i := range permutation {
		format := "%d "
		if i + 1 == len(permutation) {
			format = "%d\n"
		}
		fmt.Fscanf(inBuf,format, &permutation[i])

	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	answer := solver.Solve()

	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	for _, val := range answer {
		fmt.Fprintf(outBuf, "%d ", val)
	}
	fmt.Fprintf(outBuf, "\n")
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	fmt.Println(s.unions)
	for i, line := range matrix {
		for j, val := range line {
			if val == '1' {
				s.union(i, j)
				fmt.Println(s.unions)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

//func (s *Solver) Solve() []int {
//	numbersInUnions := make([][]int, len(s.permutation))
//	for i := range numbersInUnions {
//		numbersInUnions[i] = make([]int, 0)
//	}
//
//	fmt.Println(s.permutation)
//	fmt.Println(s.unions)
//
//	for i, val := range s.permutation {
//		index := s.find(i)
//		fmt.Println(i, val, index)
//		numbersInUnions[index] = append(numbersInUnions[index], val)
//	}
//
//	for _, arr := range numbersInUnions {
//		sort.Ints(arr)
//	}
//
//	ans := make([]int, len(s.permutation))
//	lastUsedIndex := make([]int, len(s.permutation))
//	for i := range s.permutation {
//		index := s.find(i)
//		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
//		lastUsedIndex[index] += 1
//	}
//
//	return ans
//}

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

	permutation := make([]int, n)
	for i := range permutation {
		fmt.Fscanf(inBuf,"%d ", &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	//answer := solver.Solve()
	//
	//outBuf := bufio.NewWriter(os.Stdout)
	//defer func() { outBuf.Flush() }()
	//
	//for _, val := range answer {
	//	fmt.Fprintf(outBuf, "%d ", val)
	//}
	//fmt.Fprintf(outBuf, "\n")
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	for i, line := range matrix {
		for j, val := range line {
			if i > j && val == '1' && s.find(i) != s.find(j) {
				s.union(i, j)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

func (s *Solver) Solve() []int {
	numbersInUnions := make([][]int, len(s.permutation))
	for i := range numbersInUnions {
		numbersInUnions[i] = make([]int, 0)
	}

	fmt.Println(s.permutation)

	for i, val := range s.permutation {
		index := s.find(i)
		fmt.Println(i, val, index)
		numbersInUnions[index] = append(numbersInUnions[index], val)
	}

	for _, arr := range numbersInUnions {
		sort.Ints(arr)
	}

	ans := make([]int, len(s.permutation))
	lastUsedIndex := make([]int, len(s.permutation))
	for i := range s.permutation {
		index := s.find(i)
		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
		lastUsedIndex[index] += 1
	}

	return ans
}

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

	permutation := make([]int, n)
	for i := range permutation {
		fmt.Fscanf(inBuf,"%d ", &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	answer := solver.Solve()

	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	for _, val := range answer {
		fmt.Fprintf(outBuf, "%d ", val)
	}
	fmt.Fprintf(outBuf, "\n")
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	for i, line := range matrix {
		for j, val := range line {
			if i > j && val == '1' && s.find(i) != s.find(j) {
				s.union(i, j)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

func (s *Solver) Solve() []int {
	numbersInUnions := make([][]int, len(s.permutation))
	for i := range numbersInUnions {
		numbersInUnions[i] = make([]int, 0)
	}

	for i, val := range s.permutation {
		index := s.find(i)
		numbersInUnions[index] = append(numbersInUnions[index], val)
	}

	for _, arr := range numbersInUnions {
		sort.Ints(arr)
	}

	ans := make([]int, len(s.permutation))
	lastUsedIndex := make([]int, len(s.permutation))
	for i := range s.permutation {
		index := s.find(i)
		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
		lastUsedIndex[index] += 1
	}

	return ans
}

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

	permutation := make([]int, n)
	for i := range permutation {
		fmt.Fscanf(inBuf,"%d ", &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	answer := solver.Solve()

	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	fmt.Println(answer)

	for _, val := range answer {
		fmt.Fprintf(outBuf, "%d ", val)
	}
	fmt.Fprintf(outBuf, "\n")
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	for i, line := range matrix {
		for j, val := range line {
			if i > j && val == '1' && s.find(i) != s.find(j) {
				s.union(i, j)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

func (s *Solver) Solve() []int {
	numbersInUnions := make([][]int, len(s.permutation))
	for i := range numbersInUnions {
		numbersInUnions[i] = make([]int, 0)
	}

	for i, val := range s.permutation {
		index := s.find(i)
		numbersInUnions[index] = append(numbersInUnions[index], val)
	}

	for _, arr := range numbersInUnions {
		sort.Ints(arr)
	}

	ans := make([]int, len(s.permutation))
	lastUsedIndex := make([]int, len(s.permutation))
	for i := range s.permutation {
		index := s.find(i)
		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
		lastUsedIndex[index] += 1
	}

	return ans
}

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

	permutation := make([]int, n)
	for i := range permutation {
		fmt.Fscanf(inBuf,"%d ", &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	answer := solver.Solve()

	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	for _, val := range answer {
		fmt.Fprintf(outBuf, "%d ", val)
	}
	fmt.Fprintf(outBuf, "\n")
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	for i, line := range matrix {
		for j, val := range line {
			if i > j && val == '1' && s.find(i) != s.find(j) {
				s.union(i, j)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

func (s *Solver) Solve() []int {
	numbersInUnions := make([][]int, len(s.permutation))
	for i := range numbersInUnions {
		numbersInUnions[i] = make([]int, 0)
	}

	for i, val := range s.permutation {
		index := s.find(i)
		numbersInUnions[index] = append(numbersInUnions[index], val)
	}

	for _, arr := range numbersInUnions {
		sort.Ints(arr)
		fmt.Println(arr)
	}

	ans := make([]int, len(s.permutation))
	lastUsedIndex := make([]int, len(s.permutation))
	for i := range s.permutation {
		index := s.find(i)
		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
		lastUsedIndex[index] += 1
	}

	return ans
}

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

	permutation := make([]int, n)
	for i := range permutation {
		fmt.Fscanf(inBuf,"%d ", &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	answer := solver.Solve()

	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	for _, val := range answer {
		fmt.Fprintf(outBuf, "%d ", val)
	}
	fmt.Fprintf(outBuf, "\n")
}

package main

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

type Solver struct {
	permutation []int
	matrix []string
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.matrix = matrix
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	for i, line := range s.matrix {
		for j, val := range line {
			if i > j && val == '1' && s.find(i) != s.find(j) {
				s.union(i, j)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

func (s *Solver) Solve() []int {
	numbersInUnions := make([][]int, len(s.permutation))
	for i := range numbersInUnions {
		numbersInUnions[i] = make([]int, 0)
	}

	for i, val := range s.permutation {
		index := s.find(i)
		numbersInUnions[index] = append(numbersInUnions[index], val)
	}

	for _, arr := range numbersInUnions {
		sort.Ints(arr)
	}

	ans := make([]int, len(s.permutation))
	lastUsedIndex := make([]int, len(s.permutation))
	for i := range s.permutation {
		index := s.find(i)
		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
		lastUsedIndex[index] += 1
	}

	return ans
}

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

	permutation := make([]int, n)
	for i := range permutation {
		fmt.Fscanf(inBuf,"%d ", &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	answer := solver.Solve()

	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	for _, val := range answer {
		fmt.Fprintf(outBuf, "%d ", val)
	}
	fmt.Fprintf(outBuf, "\n")
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	fmt.Println(s.unions)
	for i, line := range matrix {
		for j, val := range line {
			if val == '1' && s.find(i) != s.find(j) {
				s.union(i, j)
				fmt.Println(s.unions)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

//func (s *Solver) Solve() []int {
//	numbersInUnions := make([][]int, len(s.permutation))
//	for i := range numbersInUnions {
//		numbersInUnions[i] = make([]int, 0)
//	}
//
//	fmt.Println(s.permutation)
//	fmt.Println(s.unions)
//
//	for i, val := range s.permutation {
//		index := s.find(i)
//		fmt.Println(i, val, index)
//		numbersInUnions[index] = append(numbersInUnions[index], val)
//	}
//
//	for _, arr := range numbersInUnions {
//		sort.Ints(arr)
//	}
//
//	ans := make([]int, len(s.permutation))
//	lastUsedIndex := make([]int, len(s.permutation))
//	for i := range s.permutation {
//		index := s.find(i)
//		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
//		lastUsedIndex[index] += 1
//	}
//
//	return ans
//}

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

	permutation := make([]int, n)
	for i := range permutation {
		fmt.Fscanf(inBuf,"%d ", &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	//answer := solver.Solve()
	//
	//outBuf := bufio.NewWriter(os.Stdout)
	//defer func() { outBuf.Flush() }()
	//
	//for _, val := range answer {
	//	fmt.Fprintf(outBuf, "%d ", val)
	//}
	//fmt.Fprintf(outBuf, "\n")
}

package main

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

type Solver struct {
	permutation []int
	unions []int
}

func (s *Solver) Init(permutation []int, matrix[]string) {
	s.permutation = permutation
	s.unions = make([]int, len(s.permutation))
	for i := range s.unions {
		s.unions[i] = i
	}
	fmt.Println(matrix)
	for i, line := range matrix {
		for j, val := range line {
			if val == '1' {
				s.union(i, j)
				fmt.Println(i, j, s.unions)
			}
		}
	}
}

func (s *Solver) union(a, b int) {
	s.unions[s.find(a)] = s.find(b)
}

func (s *Solver) find(a int) int {
	ans := s.unions[a]
	for ans != s.unions[ans] {
		ans = s.unions[ans]
	}
	return ans
}

//func (s *Solver) Solve() []int {
//	numbersInUnions := make([][]int, len(s.permutation))
//	for i := range numbersInUnions {
//		numbersInUnions[i] = make([]int, 0)
//	}
//
//	fmt.Println(s.permutation)
//	fmt.Println(s.unions)
//
//	for i, val := range s.permutation {
//		index := s.find(i)
//		fmt.Println(i, val, index)
//		numbersInUnions[index] = append(numbersInUnions[index], val)
//	}
//
//	for _, arr := range numbersInUnions {
//		sort.Ints(arr)
//	}
//
//	ans := make([]int, len(s.permutation))
//	lastUsedIndex := make([]int, len(s.permutation))
//	for i := range s.permutation {
//		index := s.find(i)
//		ans[i] = numbersInUnions[index][lastUsedIndex[index]]
//		lastUsedIndex[index] += 1
//	}
//
//	return ans
//}

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

	permutation := make([]int, n)
	for i := range permutation {
		fmt.Fscanf(inBuf,"%d ", &permutation[i])
	}

	matrix := make([]string, n)
	for i := range matrix {
		fmt.Fscanf(inBuf, "%s\n", &matrix[i])
	}

	solver := Solver{}
	solver.Init(permutation, matrix)
	//answer := solver.Solve()
	//
	//outBuf := bufio.NewWriter(os.Stdout)
	//defer func() { outBuf.Flush() }()
	//
	//for _, val := range answer {
	//	fmt.Fprintf(outBuf, "%d ", val)
	//}
	//fmt.Fprintf(outBuf, "\n")
}

package main

import (
	"fmt"
)

var (
	n int
	p []int
	A [][]bool
)

func in() {
	fmt.Scanln(&n)
	p = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &p[i])
	}
	A = make([][]bool, n)
	for i := 0; i < n; i++ {
		A[i] = make([]bool, n)
		var line string
		fmt.Scanln(&line)
		for j, ch := range line {
			A[i][j] = ch == '1'
		}
	}
}

func out() {
	fmt.Print(p[0])
	for i := 1; i < n; i++ {
		fmt.Print(" ", p[i])
	}
	fmt.Println()
}

func run() {
	for k := 0; k < n; k++ {
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				if A[i][k] && A[j][k] && !A[i][j] {
					A[i][j] = true
				}
			}
		}
	}

	for i := 0; i < n-1; i++ {
		var min_j int = 0
		min := p[i]
		for j := i + 1; j < n; j++ {
			if A[i][j] && p[j] < min {
				min = p[j]
				min_j = j
			}
		}
		if min_j > 0 {
			p[i], p[min_j] = p[min_j], p[i]
		}
	}
}

func main() {
	in()
	run()
	out()
}

package main

import (
	"fmt"
)

var (
	n int
	p []int
	A [][]bool
)

func in() {
	fmt.Scan(&n)
	p = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&p[i])
	}
	A = make([][]bool, n)
	for i := 0; i < n; i++ {
		A[i] = make([]bool, n)
		var line string
		fmt.Scan(&line)
		for j, ch := range line {
			A[i][j] = ch == '1'
		}
	}
	fmt.Println(n, p, A)
}

func out() {
	fmt.Print(p[0])
	for i := 1; i < n; i++ {
		fmt.Print(" ", p[i])
	}
	fmt.Println()
}

func run() {
	for k := 0; k < n; k++ {
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				if A[i][k] && A[j][k] && !A[i][j] {
					A[i][j] = true
				}
			}
		}
	}

	for i := 0; i < n-1; i++ {
		var min_j int = 0
		min := p[i]
		for j := i + 1; j < n; j++ {
			if A[i][j] && p[j] < min {
				min = p[j]
				min_j = j
			}
		}
		if min_j > 0 {
			p[i], p[min_j] = p[min_j], p[i]
		}
	}
}

func main() {
	in()
	run()
	out()
}

package main

import (
	"fmt"
)

var (
	n int
	p []int
	A [][]bool
)

func in() {
	fmt.Scanln(&n)
	p = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &p[i])
	}
	A = make([][]bool, n)
	for i := 0; i < n; i++ {
		A[i] = make([]bool, n)
		var line string
		fmt.Scanln(&line)
		for j, ch := range line {
			A[i][j] = ch == '1'
		}
	}
	fmt.Println(n, p, A)
}

func out() {
	fmt.Print(p[0])
	for i := 1; i < n; i++ {
		fmt.Print(" ", p[i])
	}
	fmt.Println()
}

func run() {
	for k := 0; k < n; k++ {
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				if A[i][k] && A[j][k] && !A[i][j] {
					A[i][j] = true
				}
			}
		}
	}

	for i := 0; i < n-1; i++ {
		var min_j int = 0
		min := p[i]
		for j := i + 1; j < n; j++ {
			if A[i][j] && p[j] < min {
				min = p[j]
				min_j = j
			}
		}
		if min_j > 0 {
			p[i], p[min_j] = p[min_j], p[i]
		}
	}
}

func main() {
	in()
	run()
	out()
}


Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin letters. String w has the length of |w|, its characters are numbered from 1 to |w|.First Petya should find all the occurrences of forbidden substrings in the w string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings "aBC" and "ABc" are considered equal.After that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position i should be replaced by any other one if for position i in string w there exist pair of indices l, r (1 ≤ l ≤ i ≤ r ≤ |w|) such that substring w[l ... r] is contained in the collection s1, s2, ..., sn, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring.Letter letter (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the letter occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically.Note that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them.

The first line contains the only integer n (1 ≤ n ≤ 100) — the number of forbidden substrings in the collection. Next n lines contain these substrings. The next line contains string w. All those n + 1 lines are non-empty strings consisting of uppercase and lowercase Latin letters whose length does not exceed 100. The last line contains a lowercase letter letter.

Output the only line — Petya's resulting string with the maximum number of letters letter. If there are several answers then output the one that comes first lexicographically. The lexicographical comparison is performed by the standard < operator in modern programming languages. The line a is lexicographically smaller than the line b, if a is a prefix of b, or there exists such an i (1 ≤ i ≤ |a|), that ai < bi, and for any j (1 ≤ j < i) aj = bj. |a| stands for the length of string a.

4
hello
party
abefglghjdhfgj
IVan
petrsmatchwin
a

package main

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

// github.com/EndlessCheng/codeforces-go
func CF95A(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	mp := map[string]bool{}
	var n int
	var s string
	for Fscan(in, &n); n > 0; n-- {
		Fscan(in, &s)
		mp[strings.ToLower(s)] = true
	}
	var l []byte
	Fscan(in, &s, &l)
	t := strings.ToLower(s)
	ans := []byte(s)
	c := l[0]

	for i := range t {
		for j := i + 1; j <= len(t); j++ {
			if mp[t[i:j]] {
				for k := i; k < j; k++ {
					tar := byte('a')
					if t[k] != c {
						tar = c
					} else if t[k] == 'a' {
						tar = 'b'
					}
					ans[k] = tar
					if s[k] < 'a' {
						ans[k] -= 32
					}
				}
			}
		}
	}
	Fprint(out, string(ans))
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF95A(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n int
	Fscan(in, &n)
	a := make([][]byte, n)
	for i := range a {
		Fscan(in, &a[i])
		a[i] = bytes.ToLower(a[i])
	}
	var s, l []byte
	Fscan(in, &s, &l)
	t := bytes.ToLower(s)
	c := l[0]

	for _, sub := range a {
		if i := bytes.Index(t, sub); i >= 0 {
			for j := i; j-i < len(sub); j++ {
				tar := byte('a')
				if t[j] != c {
					tar = c
				} else if t[j] == 'a' {
					tar = 'b'
				}
				if s[j] < 'a' {
					s[j] = tar - 32
				} else {
					s[j] = tar
				}
			}
		}
	}
	Fprint(out, string(s))
}

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


There is a tree consisting of n vertices. The vertices are numbered from 1 to n.Let's define the length of an interval [l, r] as the value r - l + 1. The score of a subtree of this tree is the maximum length of such an interval [l, r] that, the vertices with numbers l, l + 1, ..., r belong to the subtree.Considering all subtrees of the tree whose size is at most k, return the maximum score of the subtree. Note, that in this problem tree is not rooted, so a subtree — is an arbitrary connected subgraph of the tree.

There are two integers in the first line, n and k (1 ≤ k ≤ n ≤ 105). Each of the next n - 1 lines contains integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). That means ai and bi are connected by a tree edge. It is guaranteed that the input represents a tree.

Output should contain a single integer — the maximum possible score.

NoteFor the first case, there is some subtree whose size is at most 6, including 3 consecutive numbers of vertices. For example, the subtree that consists of {1, 3, 4, 5, 7, 8} or of {1, 4, 6, 7, 8, 10} includes 3 consecutive numbers of vertices. But there is no subtree whose size is at most 6, which includes 4 or more consecutive numbers of vertices.

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"unsafe"
)

type Node struct {
	l, r, p  *Node
	size, t  int
	Key, Val int
}

type Treap struct {
	root *Node
}

func New() *Treap {
	return &Treap{
		root: nil,
	}
}

func size(x *Node) int {
	if x != nil {
		return x.size
	}
	return 0
}

func (t *Treap) Size() int {
	return size(t.root)
}

func rotate(x *Node) {
	y := x.p
	g := y.p
	x.p = g
	if g != nil {
		if g.l == y {
			g.l = x
		} else {
			g.r = x
		}
	}
	y.p = x
	if x == y.l {
		y.l = x.r
		if x.r != nil {
			x.r.p = y
		}
		x.r = y
	} else {
		y.r = x.l
		if x.l != nil {
			x.l.p = y
		}
		x.l = y
	}
	y.size = size(y.l) + size(y.r) + 1
	x.size = size(x.l) + size(x.r) + 1
}

func adjust(x *Node) *Node {
	for x.p != nil && x.t < x.p.t {
		rotate(x)
	}
	return up(x)
}

func insert(p, x *Node) *Node {
	if p == nil {
		return x
	}
	if x.Key < p.Key {
		p.l = insert(p.l, x)
		p.l.p = p
	} else {
		p.r = insert(p.r, x)
		p.r.p = p
	}
	p.size++
	return p
}

func up(x *Node) *Node {
	if x == nil {
		return nil
	}
	for x.p != nil {
		x = x.p
	}
	return x
}

func (t *Treap) Insert(key, val int) *Node {
	x := &Node{
		Key:  key,
		Val:  val,
		size: 1,
		t:    rand.Int(),
	}
	t.insertNode(x)
	return x
}

func (t *Treap) insertNode(x *Node) {
	insert(t.root, x)
	t.root = adjust(x)
}

func (t *Treap) Find(key int) *Node {
	p := t.root
	for p != nil {
		if p.Key == key {
			return p
		}
		if key < p.Key {
			p = p.l
		} else {
			p = p.r
		}
	}
	return nil
}

func (t *Treap) Erase(key int) bool {
	return t.EraseNode(t.Find(key))
}

func (t *Treap) EraseNode(x *Node) bool {
	if x == nil {
		return false
	}
	for x.l != nil || x.r != nil {
		if x.l != nil && (x.r == nil || x.l.t < x.r.t) {
			rotate(x.l)
		} else {
			rotate(x.r)
		}
	}
	y := x.p
	x.p = nil
	if y != nil {
		if y.l == x {
			y.l = nil
		} else {
			y.r = nil
		}
		for z := y; z != nil; z = z.p {
			z.size--
		}
	}
	t.root = up(y)
	return true
}

func (t *Treap) Count(key int) int {
	x := t.root
	c := 0
	for x != nil {
		if x.Key >= key {
			x = x.l
		} else {
			c += size(x.l) + 1
			x = x.r
		}
	}
	return c
}

func (t *Treap) Print() {
	var dfs func(x *Node)
	dfs = func(x *Node) {
		if x == nil {
			return
		}
		dfs(x.l)
		fmt.Printf("%v=%v, ", x.Key, x.Val)
		dfs(x.r)
	}
	dfs(t.root)
	fmt.Println()
}

func (t *Treap) ForEach(f func(x *Node)) {
	var dfs func(x *Node)
	dfs = func(x *Node) {
		if x == nil {
			return
		}
		dfs(x.l)
		dfs(x.r)
		x.l, x.r, x.size = nil, nil, 1
		f(x)
	}
	dfs(t.root)
}

func (t *Treap) Head() *Node {
	x := t.root
	if x == nil {
		return nil
	}
	for x.l != nil {
		x = x.l
	}
	return x
}

func (t *Treap) Tail() *Node {
	x := t.root
	if x == nil {
		return nil
	}
	for x.r != nil {
		x = x.r
	}
	return x
}

func (x *Node) Next() *Node {
	if x.r != nil {
		x = x.r
		for x.l != nil {
			x = x.l
		}
		return x
	} else {
		for x.p != nil && x.p.r == x {
			x = x.p
		}
		return x.p
	}
}

func (x *Node) Prev() *Node {
	if x.l != nil {
		x = x.l
		for x.r != nil {
			x = x.r
		}
		return x
	} else {
		for x.p != nil && x.p.l == x {
			x = x.p
		}
		return x.p
	}
}

type Tree struct {
	n int
	lg int
	rn int
	ns []Tnode
}

type Tnode struct {
	dep int
	pnt []*Tnode
	rnk int
	adj []*Tnode
}

func NewTree(n int) *Tree {
	lg := 1
	for d := 1; d < n; d <<= 1 {
		lg++
	}
	t := &Tree{
		n: n,
		lg: lg,
		ns: make([]Tnode, n),
	}
	for i := range t.ns {
		x := &t.ns[i]
		x.dep = -1
		x.pnt = make([]*Tnode, lg)
	}
	t.rn = 0
	return t
}

func (t *Tree) Link(u, v int) {
	x := &t.ns[u]
	y := &t.ns[v]
	x.adj = append(x.adj, y)
	y.adj = append(y.adj, x)
}

func (t *Tree) Build() {
	t.build(&t.ns[0], &t.ns[0], 0)
	for d := 1; d < t.lg; d++ {
		for i := range t.ns {
			x := &t.ns[i]
			x.pnt[d] = x.pnt[d-1].pnt[d-1]
		}
	}
}

func (t *Tree) build(u, p *Tnode, d int) {
	u.pnt[0] = p
	u.dep = d
	u.rnk = t.rn
	t.rn++
	for _, v := range u.adj {
		if v.dep == -1 {
			t.build(v, u, d+1)
		}
	}
}

func (t *Tree) Lca(u, v int) int {
	x := &t.ns[u]
	y := &t.ns[v]
	z := t.lca(x, y)
	return int((uintptr(unsafe.Pointer(z)) - uintptr(unsafe.Pointer(x))) / unsafe.Alignof(t.ns[0]))
}

func (t *Tree) lca(x, y *Tnode) *Tnode {
	if x.dep < y.dep {
		x, y = y, x
	}
	d := x.dep - y.dep
	for i := 0; i < t.lg; i++ {
		if d&(1<<uint(i)) > 0 {
			x = x.pnt[i]
		}
	}
	for i := t.lg - 1; i >= 0; i-- {
		x1 := x.pnt[i]
		y1 := y.pnt[i]
		if x1 != y1 {
			x, y = x1, y1
		}
	}
	if x != y {
		x = x.pnt[0]
	}
	return x
}

func (t *Tree) Dist(u, v int) int {
	x := &t.ns[u]
	y := &t.ns[v]
	z := t.lca(x, y)
	return x.dep + y.dep - 2*z.dep
}

func (t *Tree) Rank(u int) int {
	x := &t.ns[u]
	return x.rnk
}

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

	var n, k int
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	k = 2*k - 2
	tree := NewTree(n)
	for i := 1; i < n; i++ {
		var u, v int
		fmt.Fscanf(reader, "%d %d\n", &u, &v)
		tree.Link(u-1, v-1)
	}
	tree.Build()

	ans := 1
	update := func(c int) {
		if ans < c {
			ans = c
		}
	}

	t := New()
	next := func(x *Node) *Node {
		if y := x.Next(); y != nil {
			return y
		}
		return t.Head()
	}
	prev := func(x *Node) *Node {
		if y := x.Prev(); y != nil {
			return y
		}
		return t.Tail()
	}

	ss := 0
	for i, j := 0, 0; j < n; {
		for ; j < n && ss <= k; j++ {
			update(j - i)
//			fmt.Println(i, j, ss)
//			fmt.Println("insert", j)
			x := t.Insert(tree.Rank(j), j)
			l := prev(x)
			r := next(x)
			ss -= tree.Dist(l.Val, r.Val)
			ss += tree.Dist(l.Val, x.Val)
			ss += tree.Dist(x.Val, r.Val)
//			fmt.Println("after", i, j+1, ss)
		}
		if ss <= k {
			update(j - i)
		}
		for ; i < j && ss > k; i++ {
//			fmt.Println("remove", i)
			x := t.Find(tree.Rank(i))
			l := prev(x)
			r := next(x)
			ss += tree.Dist(l.Val, r.Val)
			ss -= tree.Dist(l.Val, x.Val)
			ss -= tree.Dist(x.Val, r.Val)
			t.EraseNode(x)
		}
	}
	fmt.Println(ans)
}

package main

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

type Node struct {
	l, r, p  *Node
	size, t  int
	Key, Val int
}

type Treap struct {
	root *Node
}

func New() *Treap {
	return &Treap{
		root: nil,
	}
}

func size(x *Node) int {
	if x != nil {
		return x.size
	}
	return 0
}

func (t *Treap) Size() int {
	return size(t.root)
}

func rotate(x *Node) {
	y := x.p
	g := y.p
	x.p = g
	if g != nil {
		if g.l == y {
			g.l = x
		} else {
			g.r = x
		}
	}
	y.p = x
	if x == y.l {
		y.l = x.r
		if x.r != nil {
			x.r.p = y
		}
		x.r = y
	} else {
		y.r = x.l
		if x.l != nil {
			x.l.p = y
		}
		x.l = y
	}
	y.size = size(y.l) + size(y.r) + 1
	x.size = size(x.l) + size(x.r) + 1
}

func adjust(x *Node) *Node {
	for x.p != nil && x.t < x.p.t {
		rotate(x)
	}
	return up(x)
}

func insert(p, x *Node) *Node {
	if p == nil {
		return x
	}
	if x.Key < p.Key {
		p.l = insert(p.l, x)
		p.l.p = p
	} else {
		p.r = insert(p.r, x)
		p.r.p = p
	}
	p.size++
	return p
}

func up(x *Node) *Node {
	if x == nil {
		return nil
	}
	for x.p != nil {
		x = x.p
	}
	return x
}

func (t *Treap) Insert(key, val int) *Node {
	x := &Node{
		Key:  key,
		Val:  val,
		size: 1,
		t:    rand.Int(),
	}
	t.insertNode(x)
	return x
}

func (t *Treap) insertNode(x *Node) {
	insert(t.root, x)
	t.root = adjust(x)
}

func (t *Treap) Find(key int) *Node {
	p := t.root
	for p != nil {
		if p.Key == key {
			return p
		}
		if key < p.Key {
			p = p.l
		} else {
			p = p.r
		}
	}
	return nil
}

func (t *Treap) Erase(key int) bool {
	return t.EraseNode(t.Find(key))
}

func (t *Treap) EraseNode(x *Node) bool {
	if x == nil {
		return false
	}
	for x.l != nil || x.r != nil {
		if x.l != nil && (x.r == nil || x.l.t < x.r.t) {
			rotate(x.l)
		} else {
			rotate(x.r)
		}
	}
	y := x.p
	x.p = nil
	if y != nil {
		if y.l == x {
			y.l = nil
		} else {
			y.r = nil
		}
		for z := y; z != nil; z = z.p {
			z.size--
		}
	}
	t.root = up(y)
	return true
}

func (t *Treap) Count(key int) int {
	x := t.root
	c := 0
	for x != nil {
		if x.Key >= key {
			x = x.l
		} else {
			c += size(x.l) + 1
			x = x.r
		}
	}
	return c
}

func (t *Treap) Print() {
	var dfs func(x *Node)
	dfs = func(x *Node) {
		if x == nil {
			return
		}
		dfs(x.l)
		fmt.Printf("%v=%v, ", x.Key, x.Val)
		dfs(x.r)
	}
	dfs(t.root)
	fmt.Println()
}

func (t *Treap) ForEach(f func(x *Node)) {
	var dfs func(x *Node)
	dfs = func(x *Node) {
		if x == nil {
			return
		}
		dfs(x.l)
		dfs(x.r)
		x.l, x.r, x.size = nil, nil, 1
		f(x)
	}
	dfs(t.root)
}

func (t *Treap) Head() *Node {
	x := t.root
	if x == nil {
		return nil
	}
	for x.l != nil {
		x = x.l
	}
	return x
}

func (t *Treap) Tail() *Node {
	x := t.root
	if x == nil {
		return nil
	}
	for x.r != nil {
		x = x.r
	}
	return x
}

func (x *Node) Next() *Node {
	if x.r != nil {
		x = x.r
		for x.l != nil {
			x = x.l
		}
		return x
	} else {
		for x.p != nil && x.p.r == x {
			x = x.p
		}
		return x.p
	}
}

func (x *Node) Prev() *Node {
	if x.l != nil {
		x = x.l
		for x.r != nil {
			x = x.r
		}
		return x
	} else {
		for x.p != nil && x.p.l == x {
			x = x.p
		}
		return x.p
	}
}

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

	var n, k int
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	k = 2*k - 2
	vout := make([][]int, n)
	for i := 1; i < n; i++ {
		var u, v int
		fmt.Fscanf(reader, "%d %d\n", &u, &v)
		u--
		v--
		vout[u] = append(vout[u], v)
		vout[v] = append(vout[v], u)
	}

	lg := 1
	for d := 1; d < n; d <<= 1 {
		lg++
	}
	pnt := make([][]int, n)
	dep := make([]int, n)
	rnk := make([]int, n)
	for i := 0; i < n; i++ {
		dep[i] = -1
		pnt[i] = make([]int, lg)
	}
	rn := 0
	var dfs func(u, p, d int)
	dfs = func(u, p, d int) {
		pnt[u][0] = p
		dep[u] = d
		rnk[u] = rn
		rn++
		for _, v := range vout[u] {
			if dep[v] == -1 {
				dfs(v, u, d+1)
			}
		}
	}
	dfs(0, 0, 0)

	for d := 1; d < lg; d++ {
		for i := 0; i < n; i++ {
			pnt[i][d] = pnt[pnt[i][d-1]][d-1]
		}
	}
//	fmt.Println(dep)
//	fmt.Println(pnt)
//	fmt.Println(rnk)

	lca := func(x, y int) int {
		if dep[x] < dep[y] {
			x, y = y, x
		}
		d := dep[x] - dep[y]
		for i := 0; i < lg; i++ {
			if d&(1<<uint(i)) > 0 {
				x = pnt[x][i]
			}
		}
		for i := lg - 1; i >= 0; i-- {
			x1 := pnt[x][i]
			y1 := pnt[y][i]
			if x1 != y1 {
				x, y = x1, y1
			}
		}
		if x != y {
			x = pnt[x][0]
		}
		return x
	}
	dist := func(x, y int) int {
		z := lca(x, y)
//		fmt.Printf("dist %d, %d; lca = %d, d = %d.\n", x, y, z, dep[x]+dep[y]-2*dep[z])
		return dep[x] + dep[y] - 2*dep[z]
	}

	ans := 1
	update := func(c int) {
		if ans < c {
			ans = c
		}
	}

	t := New()
	next := func(x *Node) *Node {
		if y := x.Next(); y != nil {
			return y
		}
		return t.Head()
	}
	prev := func(x *Node) *Node {
		if y := x.Prev(); y != nil {
			return y
		}
		return t.Tail()
	}

	ss := 0
	for i, j := 0, 0; j < n; {
		for ; j < n && ss <= k; j++ {
			update(j - i)
//			fmt.Println(i, j, ss)
//			fmt.Println("insert", j)
			x := t.Insert(rnk[j], j)
			l := prev(x)
			r := next(x)
			ss -= dist(l.Val, r.Val)
			ss += dist(l.Val, x.Val)
			ss += dist(x.Val, r.Val)
//			fmt.Println("after", i, j+1, ss)
		}
		if ss <= k {
			update(j - i)
		}
		for ; i < j && ss > k; i++ {
//			fmt.Println("remove", i)
			x := t.Find(rnk[i])
			l := prev(x)
			r := next(x)
			ss += dist(l.Val, r.Val)
			ss -= dist(l.Val, x.Val)
			ss -= dist(x.Val, r.Val)
			t.EraseNode(x)
		}
	}
	fmt.Println(ans)
}


You are given an array $$$a_1, a_2, \ldots, a_n$$$.You need to perform $$$q$$$ queries of the following two types:  "MULTIPLY l r x" — for every $$$i$$$ ($$$l \le i \le r$$$) multiply $$$a_i$$$ by $$$x$$$. "TOTIENT l r" — print $$$\varphi(\prod \limits_{i=l}^{r} a_i)$$$ taken modulo $$$10^9+7$$$, where $$$\varphi$$$ denotes Euler's totient function. The Euler's totient function of a positive integer $$$n$$$ (denoted as $$$\varphi(n)$$$) is the number of integers $$$x$$$ ($$$1 \le x \le n$$$) such that $$$\gcd(n,x) = 1$$$.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 4 \cdot 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$) — the number of elements in array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300$$$) — the elements of array $$$a$$$. Then $$$q$$$ lines follow, describing queries in the format given in the statement.   "MULTIPLY l r x" ($$$1 \le l \le r \le n$$$, $$$1 \le x \le 300$$$) — denotes a multiplication query. "TOTIENT l r" ($$$1 \le l \le r \le n$$$) — denotes a query on the value of Euler's totient function.  It is guaranteed that there is at least one "TOTIENT" query.

For each "TOTIENT" query, print the answer to it.

4 4
5 9 1 2
TOTIENT 3 3
TOTIENT 3 4
MULTIPLY 4 4 3
TOTIENT 4 4

NoteIn the first example, $$$\varphi(1) = 1$$$ for the first query, $$$\varphi(2) = 1$$$ for the second query and $$$\varphi(6) = 2$$$ for the third one.

package main

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

const mod int64 = 1e9 + 7

type mulST []struct {
	l, r      int
	mul, todo int64
}

func (mulST) pow(x int64, n int) int64 {
	res := int64(1)
	for ; n > 0; n >>= 1 {
		if n&1 == 1 {
			res = res * x % mod
		}
		x = x * x % mod
	}
	return res
}

func (t mulST) _pushUp(o int) {
	t[o].mul = t[o<<1].mul * t[o<<1|1].mul % mod
}

func (t mulST) _build(a []int, o, l, r int) {
	t[o].l, t[o].r, t[o].todo = l, r, 1
	if l == r {
		t[o].mul = int64(a[l-1])
		return
	}
	m := (l + r) >> 1
	t._build(a, o<<1, l, m)
	t._build(a, o<<1|1, m+1, r)
	t._pushUp(o)
}

func (t mulST) _spread(o int) {
	if mul := t[o].todo; mul != 1 {
		lo, ro := &t[o<<1], &t[o<<1|1]
		lo.mul = lo.mul * t.pow(mul, lo.r-lo.l+1) % mod
		ro.mul = ro.mul * t.pow(mul, ro.r-ro.l+1) % mod
		lo.todo = lo.todo * mul % mod
		ro.todo = ro.todo * mul % mod
		t[o].todo = 1
	}
}

func (t mulST) _update(o, l, r, val int) {
	ol, or := t[o].l, t[o].r
	if l <= ol && or <= r {
		t[o].mul = t[o].mul * t.pow(int64(val), or-ol+1) % mod
		t[o].todo = t[o].todo * int64(val) % mod
		return
	}
	t._spread(o)
	m := (ol + or) >> 1
	if l <= m {
		t._update(o<<1, l, r, val)
	}
	if m < r {
		t._update(o<<1|1, l, r, val)
	}
	t._pushUp(o)
}

func (t mulST) _query(o, l, r int) (res int64) {
	if l <= t[o].l && t[o].r <= r {
		return t[o].mul
	}
	t._spread(o)
	res = 1
	m := (t[o].l + t[o].r) >> 1
	if l <= m {
		res = t._query(o<<1, l, r)
	}
	if m < r {
		res = res * t._query(o<<1|1, l, r) % mod
	}
	return
}

func (t mulST) init(a []int)         { t._build(a, 1, 1, len(a)) }
func (t mulST) update(l, r, val int) { t._update(1, l, r, val) }
func (t mulST) query(l, r int) int64 { return t._query(1, l, r) }

type orST []struct {
	l, r     int
	or, todo int64
}

func (t orST) _pushUp(o int) {
	t[o].or = t[o<<1].or | t[o<<1|1].or
}

func (t orST) _build(a []int64, o, l, r int) {
	t[o].l, t[o].r = l, r
	if l == r {
		t[o].or = a[l-1]
		return
	}
	m := (l + r) >> 1
	t._build(a, o<<1, l, m)
	t._build(a, o<<1|1, m+1, r)
	t._pushUp(o)
}

func (t orST) _spread(o int) {
	if or := t[o].todo; or != 0 {
		lo, ro := &t[o<<1], &t[o<<1|1]
		lo.or |= or
		ro.or |= or
		lo.todo |= or
		ro.todo |= or
		t[o].todo = 0
	}
}

func (t orST) _update(o, l, r int, val int64) {
	ol, or := t[o].l, t[o].r
	if l <= ol && or <= r {
		t[o].or |= val
		t[o].todo |= val
		return
	}
	t._spread(o)
	m := (ol + or) >> 1
	if l <= m {
		t._update(o<<1, l, r, val)
	}
	if m < r {
		t._update(o<<1|1, l, r, val)
	}
	t._pushUp(o)
}

func (t orST) _query(o, l, r int) (res int64) {
	if l <= t[o].l && t[o].r <= r {
		return t[o].or
	}
	t._spread(o)
	m := (t[o].l + t[o].r) >> 1
	if l <= m {
		res = t._query(o<<1, l, r)
	}
	if m < r {
		res |= t._query(o<<1|1, l, r)
	}
	return
}

func (t orST) init(a []int64)             { t._build(a, 1, 1, len(a)) }
func (t orST) update(l, r int, val int64) { t._update(1, l, r, val) }
func (t orST) query(l, r int) int64       { return t._query(1, l, r) }

// github.com/EndlessCheng/codeforces-go
func CF1114F(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	pow := func(x, n int64) int64 {
		res := int64(1)
		for ; n > 0; n >>= 1 {
			if n&1 == 1 {
				res = res * x % mod
			}
			x = x * x % mod
		}
		return res
	}
	div := func(p int64) int64 { return (p - 1) * pow(p, mod-2) % mod }

	const mx = 300
	factors := [mx + 1]int64{}
	p1p := []int64{}
	for i := 2; i <= mx; i++ {
		if factors[i] == 0 {
			for j := i; j <= mx; j += i {
				factors[j] |= 1 << len(p1p)
			}
			p1p = append(p1p, div(int64(i)))
		}
	}

	var n, q, l, r, x int
	var s []byte
	Fscan(in, &n, &q)
	a := make([]int, n)
	ors := make([]int64, n)
	for i := range a {
		Fscan(in, &a[i])
		ors[i] = factors[a[i]]
	}

	mt := make(mulST, 4*n)
	mt.init(a)
	ot := make(orST, 4*n)
	ot.init(ors)
	for ; q > 0; q-- {
		Fscan(in, &s, &l, &r)
		if s[0] == 'M' {
			Fscan(in, &x)
			mt.update(l, r, x)
			ot.update(l, r, factors[x])
		} else {
			ans := mt.query(l, r)
			ps := ot.query(l, r)
			for i, v := range p1p {
				if ps>>i&1 == 1 {
					ans = ans * v % mod
				}
			}
			Fprintln(out, ans)
		}
	}
}

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

package main

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

const mod = 1e9 + 7

type seg []struct {
	l, r         int
	mul, mulTodo int64
	or, orTodo   int64
}

func pow(x int64, n int) int64 {
	res := int64(1)
	for ; n > 0; n >>= 1 {
		if n&1 == 1 {
			res = res * x % mod
		}
		x = x * x % mod
	}
	return res
}

func (t seg) _pushUp(o int) {
	lo, ro := t[o<<1], t[o<<1|1]
	t[o].mul = lo.mul * ro.mul % mod
	t[o].or = lo.or | ro.or
}

func (t seg) _build(a []int, ors []int64, o, l, r int) {
	t[o].l, t[o].r, t[o].mulTodo = l, r, 1
	if l == r {
		t[o].mul = int64(a[l-1])
		t[o].or = ors[l-1]
		return
	}
	m := (l + r) >> 1
	t._build(a, ors, o<<1, l, m)
	t._build(a, ors, o<<1|1, m+1, r)
	t._pushUp(o)
}

func (t seg) _spread(o int) {
	lo, ro := &t[o<<1], &t[o<<1|1]
	if mul := t[o].mulTodo; mul != 1 {
		lo.mul = lo.mul * pow(mul, lo.r-lo.l+1) % mod
		ro.mul = ro.mul * pow(mul, ro.r-ro.l+1) % mod
		lo.mulTodo = lo.mulTodo * mul % mod
		ro.mulTodo = ro.mulTodo * mul % mod
		t[o].mulTodo = 1
	}
	if or := t[o].orTodo; or != 0 {
		lo.or |= or
		ro.or |= or
		lo.orTodo |= or
		ro.orTodo |= or
		t[o].orTodo = 0
	}
}

func (t seg) _update(o, l, r, mul int, orVal int64) {
	ol, or := t[o].l, t[o].r
	if l <= ol && or <= r {
		t[o].mul = t[o].mul * pow(int64(mul), or-ol+1) % mod
		t[o].mulTodo = t[o].mulTodo * int64(mul) % mod
		t[o].or |= orVal
		t[o].orTodo |= orVal
		return
	}
	t._spread(o)
	m := (ol + or) >> 1
	if l <= m {
		t._update(o<<1, l, r, mul, orVal)
	}
	if m < r {
		t._update(o<<1|1, l, r, mul, orVal)
	}
	t._pushUp(o)
}

func (t seg) _query(o, l, r int) (mul, or int64) {
	if l <= t[o].l && t[o].r <= r {
		return t[o].mul, t[o].or
	}
	t._spread(o)
	mul = 1
	m := (t[o].l + t[o].r) >> 1
	if l <= m {
		mul, or = t._query(o<<1, l, r)
	}
	if m < r {
		a, b := t._query(o<<1|1, l, r)
		mul = mul * a % mod
		or |= b
	}
	return
}

func (t seg) init(a []int, ors []int64)      { t._build(a, ors, 1, 1, len(a)) }
func (t seg) update(l, r, mul int, or int64) { t._update(1, l, r, mul, or) }
func (t seg) query(l, r int) (int64, int64)  { return t._query(1, l, r) }

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	const mx = 300
	factors := [mx + 1]int64{}
	p1p := []int64{}
	for i := 2; i <= mx; i++ {
		if factors[i] == 0 {
			for j := i; j <= mx; j += i {
				factors[j] |= 1 << len(p1p)
			}
			p1p = append(p1p, int64(i-1)*pow(int64(i), mod-2)%mod)
		}
	}

	var n, q, l, r, x int
	var s []byte
	Fscan(in, &n, &q)
	a := make([]int, n)
	ors := make([]int64, n)
	for i := range a {
		Fscan(in, &a[i])
		ors[i] = factors[a[i]]
	}

	t := make(seg, 4*n)
	t.init(a, ors)
	for ; q > 0; q-- {
		Fscan(in, &s, &l, &r)
		if s[0] == 'M' {
			Fscan(in, &x)
			t.update(l, r, x, factors[x])
		} else {
			ans, ps := t.query(l, r)
			for i, v := range p1p {
				if ps>>i&1 == 1 {
					ans = ans * v % mod
				}
			}
			Fprintln(out, ans)
		}
	}
}

package main

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

const mod int64 = 1e9 + 7

type lazyST []struct {
	l, r         int
	mul, mulTodo int64
	or, orTodo   int64
}

func (lazyST) pow(x int64, n int) int64 {
	res := int64(1)
	for ; n > 0; n >>= 1 {
		if n&1 == 1 {
			res = res * x % mod
		}
		x = x * x % mod
	}
	return res
}

func (t lazyST) _pushUp(o int) {
	lo, ro := t[o<<1], t[o<<1|1]
	t[o].mul = lo.mul * ro.mul % mod
	t[o].or = lo.or | ro.or
}

func (t lazyST) _build(a []int, ors []int64, o, l, r int) {
	t[o].l, t[o].r, t[o].mulTodo = l, r, 1
	if l == r {
		t[o].mul = int64(a[l-1])
		t[o].or = ors[l-1]
		return
	}
	m := (l + r) >> 1
	t._build(a, ors, o<<1, l, m)
	t._build(a, ors, o<<1|1, m+1, r)
	t._pushUp(o)
}

func (t lazyST) _spread(o int) {
	lo, ro := &t[o<<1], &t[o<<1|1]
	if mul := t[o].mulTodo; mul != 1 {
		lo.mul = lo.mul * t.pow(mul, lo.r-lo.l+1) % mod
		ro.mul = ro.mul * t.pow(mul, ro.r-ro.l+1) % mod
		lo.mulTodo = lo.mulTodo * mul % mod
		ro.mulTodo = ro.mulTodo * mul % mod
		t[o].mulTodo = 1
	}
	if or := t[o].orTodo; or != 0 {
		lo.or |= or
		ro.or |= or
		lo.orTodo |= or
		ro.orTodo |= or
		t[o].orTodo = 0
	}
}

func (t lazyST) _update(o, l, r, mul int, orVal int64) {
	ol, or := t[o].l, t[o].r
	if l <= ol && or <= r {
		t[o].mul = t[o].mul * t.pow(int64(mul), or-ol+1) % mod
		t[o].mulTodo = t[o].mulTodo * int64(mul) % mod
		t[o].or |= orVal
		t[o].orTodo |= orVal
		return
	}
	t._spread(o)
	m := (ol + or) >> 1
	if l <= m {
		t._update(o<<1, l, r, mul, orVal)
	}
	if m < r {
		t._update(o<<1|1, l, r, mul, orVal)
	}
	t._pushUp(o)
}

func (t lazyST) _query(o, l, r int) (mul, or int64) {
	if l <= t[o].l && t[o].r <= r {
		return t[o].mul, t[o].or
	}
	t._spread(o)
	mul = 1
	m := (t[o].l + t[o].r) >> 1
	if l <= m {
		mul, or = t._query(o<<1, l, r)
	}
	if m < r {
		a, b := t._query(o<<1|1, l, r)
		mul = mul * a % mod
		or |= b
	}
	return
}

func (t lazyST) init(a []int, ors []int64)      { t._build(a, ors, 1, 1, len(a)) }
func (t lazyST) update(l, r, mul int, or int64) { t._update(1, l, r, mul, or) }
func (t lazyST) query(l, r int) (int64, int64)  { return t._query(1, l, r) }

// github.com/EndlessCheng/codeforces-go
func CF1114F(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	pow := func(x, n int64) int64 {
		res := int64(1)
		for ; n > 0; n >>= 1 {
			if n&1 == 1 {
				res = res * x % mod
			}
			x = x * x % mod
		}
		return res
	}
	div := func(p int64) int64 { return (p - 1) * pow(p, mod-2) % mod }
	const mx = 300
	factors := [mx + 1]int64{}
	p1p := []int64{}
	for i := 2; i <= mx; i++ {
		if factors[i] == 0 {
			for j := i; j <= mx; j += i {
				factors[j] |= 1 << len(p1p)
			}
			p1p = append(p1p, div(int64(i)))
		}
	}

	var n, q, l, r, x int
	var s []byte
	Fscan(in, &n, &q)
	a := make([]int, n)
	ors := make([]int64, n)
	for i := range a {
		Fscan(in, &a[i])
		ors[i] = factors[a[i]]
	}

	t := make(lazyST, 4*n)
	t.init(a, ors)
	for ; q > 0; q-- {
		Fscan(in, &s, &l, &r)
		if s[0] == 'M' {
			Fscan(in, &x)
			t.update(l, r, x, factors[x])
		} else {
			ans, ps := t.query(l, r)
			for i, v := range p1p {
				if ps>>i&1 == 1 {
					ans = ans * v % mod
				}
			}
			Fprintln(out, ans)
		}
	}
}

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


When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a $$$2 \times n$$$ grid where each row is a permutation of the numbers $$$1,2,3,\ldots,n$$$.The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column.Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo $$$10^9+7$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 4 \cdot 10^5$$$). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers $$$1,2,3,\ldots,n$$$ and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.

For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo $$$10^9+7$$$. The answer for each test case should be on a separate line.

NoteThe two possible puzzle configurations for example $$$1$$$ are:  $$$[1,4,2,3]$$$ in the first row and $$$[3,2,1,4]$$$ in the second;  $$$[3,2,1,4]$$$ in the first row and $$$[1,4,2,3]$$$ in the second.

package main

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

func main() {
	r := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(r, &t)
	for k := 0; k < t; k++ {
		var n int
		fmt.Fscan(r, &n)
		arr := make([][]int, 2)
		arr[0] = make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(r, &arr[0][j])
		}

		arr[1] = make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(r, &arr[1][j])
		}
		solve1534C(arr)
	}
}
func solve1534C(arr [][]int) {
	n := len(arr[0])
	parent := make([]int, n)
	tmp := make([]int, n+1) //记录连通性的数组
	for i := 0; i < n; i++ {
		parent[i] = i
	}
	for i := 0; i < n; i++ {
		tmp[arr[0][i]] = i
	}
	for i := 0; i < n; i++ {
		pos := tmp[arr[1][i]]
		union1534C(pos, i, parent)
	}
	//计算集合的数量
	var setNums int
	for i := 0; i < n; i++ {
		if parent[i] == i {
			setNums++
		}
	}
	var mod int = 1e9 + 7
	var res int = 1
	for i := 0; i < setNums; i++ {
		res = ((res % mod) * 2) % mod
	}
	fmt.Println(res)
}
func find1534C(x int, parent []int) int {
	for x != parent[x] {
		parent[x] = parent[parent[x]]
		x = parent[x]
	}
	return x
}
func union1534C(x, y int, parent []int) {
	a := find1534C(x, parent)
	b := find1534C(y, parent)
	if a == b {
		return
	}
	parent[b] = a
}

package main

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

var in *bufio.Reader = bufio.NewReader(os.Stdin)
var out *bufio.Writer = bufio.NewWriter(os.Stdout)
var mod int64 = int64(1e9 + 7)

func find(parent *[]int, x int) int {
	if (*parent)[x] == x {
		return x
	}
	(*parent)[x] = find(parent, (*parent)[x])
	return (*parent)[x]
}

func merge(parent *[]int, x, y int) {
	parx := find(parent, x)
	pary := find(parent, y)
	if parx != pary {
		(*parent)[pary] = parx
	}
}

func dsu(g *[][]int, parent *[]int, x int, vis *[]bool) {
	for _, i := range (*g)[x] {
		if !(*vis)[i] {
			(*vis)[i] = true
			merge(parent, x, i)
			dsu(g, parent, i, vis)
		}
	}
}
func main() {
	defer out.Flush()
	solve := func(Case int) {
		var n int
		fmt.Fscan(in, &n)
		a, b := make([]int, n), make([]int, n)
		for i := range a {
			fmt.Fscan(in, &a[i])
			a[i]--
		}
		for i := range b {
			fmt.Fscan(in, &b[i])
			b[i]--
		}
		g := make([][]int, n)
		for i := range a {
			g[a[i]] = append(g[a[i]], b[i])
			g[b[i]] = append(g[b[i]], a[i])
		}
		vis := make([]bool, n)
		parent := make([]int, n)
		for i := range a {
			parent[i] = i
		}
		for i := range a {
			if !vis[i] {
				vis[i] = true
				dsu(&g, &parent, i, &vis)
			}
		}
		ans := int64(0)
		for i := range a {
			if find(&parent, i) == i {
				ans++
			}
		}
		fmt.Fprintln(out, powMod(int64(2), ans, mod))

	}

	T := 1
	fmt.Fscan(in, &T) //
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}
}

func powMod(x, y, mod int64) int64 {
	ans := int64(1)
	for y != 0 {
		if y&1 != 0 {
			ans = (ans * x) % mod
		}
		y = y >> 1
		x = (x * x) % mod
	}
	return ans
}
func max(x, y int) int {
	if x < y {
		return y
	}
	return x
}

func min(a []int) int {
	mn := int(1e9)
	for i := range a {
		if a[i] < mn {
			mn = a[i]
		}
	}
	return mn
}
func gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func reverse(s []byte) []byte {
	a := []byte(s)
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return a
}

package main

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

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

func (in *CF1534C) 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 *CF1534C) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

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

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

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

/**
 Run solve the problem CF1534C
 Date: 13/06/21
 User: pepradere
 URL: https://codeforces.com/contest/1534/problem/C
 Problem: CF1534C
**/
func (in *CF1534C) Run() {

	t := in.NextInt()
	for ; t > 0; t-- {
		n := in.NextInt()
		a := []int{}
		b := []int{}

		for i := 0; i < n; i++ {
			a = append(a, in.NextInt()-1)
		}

		for i := 0; i < n; i++ {
			b = append(b, in.NextInt()-1)
		}

		mady := []map[int]bool{}
		for i := 0; i < n; i++ {
			mady = append(mady, map[int]bool{})
		}

		for i := 0; i < n; i++ {
			mady[a[i]][b[i]] = true
			mady[b[i]][a[i]] = true
		}

		cola := []int{}
		vis := []bool{}
		for i := 0; i <= n; i++ {
			cola = append(cola, 0)
			vis = append(vis, false)
		}

		count := 0
		for i := 0; i < n; i++ {
			if !vis[i] {
				u := i
				vis[u] = true
				p, c := 0, 0
				cola[c] = u
				c++
				for ; p < c; {
					u = cola[p]
					p++
					for v, _ := range mady[u] {
						if !vis[v] {
							vis[v] = true
							cola[c] = v
							c++
						}

					}
				}
				count++
			}
		}

		const S = 1000000007
		ans := 1
		for i := 0; i < count; i++ {
			ans = ((ans%S) * 2) %S
		}

		//ans := int64(math.Pow(2.0, float64(count))) % 1000000007
		fmt.Println(ans)

	}
}

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

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

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)
		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 a { p[a[i]] = b[i] }

		for _, v := range a {
			if !vis[v] {
				cnt++
				dfs(v, p, vis)
			}
		}

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

}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1534C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T, n, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		pos := make([]int, n+1)
		for i := 0; i < n; i++ {
			Fscan(in, &v)
			pos[v] = i
		}
		b := make([]int, n)
		for i := range b {
			Fscan(in, &b[i])
		}
		ans := 1
		vis := make([]bool, n)
		for i, s := range vis {
			if !s {
				ans = ans * 2 % (1e9 + 7)
				for ; !vis[i]; i = pos[b[i]] {
					vis[i] = true
				}
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

var in *bufio.Reader = bufio.NewReader(os.Stdin)
var out *bufio.Writer = bufio.NewWriter(os.Stdout)
var mod int = int(1e9 + 7)

func find(parent *[]int, x int) int {
	if (*parent)[x] == x {
		return x
	}
	(*parent)[x] = find(parent, (*parent)[x])
	return (*parent)[x]
}

func merge(parent *[]int, x, y int) {
	parx := find(parent, x)
	pary := find(parent, y)
	if parx != pary {
		(*parent)[pary] = parx
	}
}

func dsu(g *[][]int, parent *[]int, x int, vis *[]bool) {
	for _, i := range (*g)[x] {
		if !(*vis)[i] {
			(*vis)[i] = true
			merge(parent, x, i)
			dsu(g, parent, i, vis)
		}
	}
}
func main() {
	defer out.Flush()
	solve := func(Case int) {
		var n int
		fmt.Fscan(in, &n)
		a, b := make([]int, n), make([]int, n)
		for i := range a {
			fmt.Fscan(in, &a[i])
			a[i]--
		}
		for i := range b {
			fmt.Fscan(in, &b[i])
			b[i]--
		}
		g := make([][]int, n)
		for i := range a {
			g[a[i]] = append(g[a[i]], b[i])
			g[b[i]] = append(g[b[i]], a[i])
		}
		vis := make([]bool, n)
		parent := make([]int, n)
		for i := range a {
			parent[i] = i
		}
		for i := range a {
			if !vis[i] {
				vis[i] = true
				dsu(&g, &parent, i, &vis)
			}
		}
		ans := 0
		for i := range a {
			if find(&parent, i) == i {
				ans++
			}
		}
		fmt.Fprintln(out, powMod(2, ans, mod))

	}

	T := 1
	fmt.Fscan(in, &T) //
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}
}

func powMod(x, y, mod int) int {
	ans := int(1)
	for y != 0 {
		if y&1 != 0 {
			ans = (ans * x) % mod
		}
		y = y >> 1
		x = (x * x) % mod
	}
	return ans
}
func max(x, y int) int {
	if x < y {
		return y
	}
	return x
}

func min(a []int) int {
	mn := int(1e9)
	for i := range a {
		if a[i] < mn {
			mn = a[i]
		}
	}
	return mn
}
func gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func reverse(s []byte) []byte {
	a := []byte(s)
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return a
}

package main

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

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

func (in *CF1534C) 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 *CF1534C) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

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

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

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

/**
 Run solve the problem CF1534C
 Date: 13/06/21
 User: pepradere
 URL: https://codeforces.com/contest/1534/problem/C
 Problem: CF1534C
**/
func (in *CF1534C) Run() {

	t := in.NextInt()
	for ; t > 0; t-- {
		n := in.NextInt()
		a := []int{}
		b := []int{}

		for i := 0; i < n; i++ {
			a = append(a, in.NextInt()-1)
		}

		for i := 0; i < n; i++ {
			b = append(b, in.NextInt()-1)
		}

		mady := []map[int]bool{}
		for i := 0; i < n; i++ {
			mady = append(mady, map[int]bool{})
		}

		for i := 0; i < n; i++ {
			mady[a[i]][b[i]] = true
			mady[b[i]][a[i]] = true
		}

		cola := []int{}
		vis := []bool{}
		for i := 0; i <= n; i++ {
			cola = append(cola, 0)
			vis = append(vis, false)
		}

		count := 0
		for i := 0; i < n; i++ {
			if !vis[i] {
				u := i
				vis[u] = true
				p, c := 0, 0
				cola[c] = u
				c++
				for ;p < c;{
					u = cola[p]
					p++
					for v , _ :=range mady[u] {
						if !vis[v]{
							vis[v] = true
							cola[c] = v
							c++
						}

					}
				}
				count++
			}
		}

		ans := int64(math.Pow(2.0, float64(count)))%1000000007
		fmt.Println(ans)

	}
}

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

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