Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var s, s0, s1 string
	var forward, backward bool

	fmt.Fscanf(reader, "%s\n", &s)
	fmt.Fscanf(reader, "%s\n", &s0)
	fmt.Fscanf(reader, "%s", &s1)

	findex0 := strings.Index(s, s0)
	findex1 := strings.LastIndex(s, s1)
	if findex0 == -1 || findex1 == -1 || findex1-findex0 < len(s0) {
		forward = false
	} else {
		forward = true
	}

	s = reverse(s)
	bindex0 := strings.Index(s, s0)
	bindex1 := strings.LastIndex(s, s1)
	if bindex0 == -1 || bindex1 == -1 || bindex1-bindex0 < len(s0) {
		backward = false
	} else {
		backward = true
	}

	if forward && backward {
		fmt.Printf("both\n")
	} else if forward && !backward {
		fmt.Printf("forward\n")
	} else if !forward && backward {
		fmt.Printf("backward\n")
	} else {
		fmt.Printf("fantasy")
	}
}

package main

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

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

	s, _ := reader.ReadString('\n')
	a, _ := reader.ReadString('\n')
	b, _ := reader.ReadString('\n')

	ans := solve(normalize(s), normalize(a), normalize(b))

	fmt.Println(ans)
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

func solve(s string, a string, b string) string {
	res1 := check(s, a, b)
	res2 := check(reverse(s), a, b)

	if res1 {
		if res2 {
			return "both"
		}
		return "forward"
	}

	if res2 {
		return "backward"
	}
	return "fantasy"
}

func check(s string, a string, b string) bool {
	x := getLps(a)
	y := getLps(b)

	i := find(s, a, x)
	if i >= 0 {
		j := i + len(a)

		if find(s[j:], b, y) >= 0 {
			return true
		}
	}
	return false
}

func find(s string, pat string, lps []int) int {
	for i, j := 0, 0; i < len(s); {
		if s[i] == pat[j] {
			i++
			j++
		}
		if j == len(pat) {
			return i - len(pat)
		}
		if i < len(s) && s[i] != pat[j] {
			if j > 0 {
				j = lps[j-1]
			} else {
				i++
			}
		}
	}

	return -1
}

func getLps(pat string) []int {
	m := len(pat)
	lps := make([]int, m)
	for l, i := 0, 1; i < m; {
		if pat[l] == pat[i] {
			l++
			lps[i] = l
			i++
		} else {
			if l > 0 {
				l = lps[l-1]
			} else {
				lps[i] = 0
				i++
			}
		}
	}
	return lps
}

func reverse(s string) string {
	buf := []byte(s)

	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		buf[i], buf[j] = buf[j], buf[i]
	}

	return string(buf)
}

package main

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

func solve() {
	s := readString()
	sr := Reverse(s)

	s1 := readString()
	s2 := readString()

	forward := try_it(s, s1, s2)
	backward := try_it(sr, s1, s2)

	if forward && backward {
		fmt.Println("both")
	} else if forward {
		fmt.Println("forward")
	} else if backward {
		fmt.Println("backward")
	} else {
		fmt.Println("fantasy")
	}
}

func try_it(s, s1, s2 string) bool {
	i := strings.Index(s, s1)
	if i == -1 {
		return false
	}

	i = strings.Index(s[i+len(s1):], s2)
	if i == -1 {
		return false
	}

	return true
}

func Reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

var scanner *bufio.Scanner

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

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

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

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

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func seek(s, a, b string) bool {
  aPos := strings.Index(s, a)
  if aPos != -1 {
    bPos := strings.Index(s[aPos+len(a):], b)
    if bPos != -1 {
      return true
    }
  }
  return false
}

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

  line, _ := reader.ReadString('\n')
  ab := strings.TrimSpace(line)
  n := len(ab)
  baBytes := make([]byte, n)
  for i := 0; i < n; i++ {
    baBytes[i] = ab[n-1-i]
  }
  ba := string(baBytes)
  line, _ = reader.ReadString('\n')
  s1 := strings.TrimSpace(line)
  line, _ = reader.ReadString('\n')
  s2 := strings.TrimSpace(line)
  forward, backward := seek(ab, s1, s2), seek(ba, s1, s2)
  result := "fantasy"
  if forward && backward {
    result = "both"
  } else if forward {
    result = "forward"
  } else if backward {
    result = "backward"
  }
  writer.WriteString(fmt.Sprintf("%s\n", result))
}

// https://codeforces.com/contest/8/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	var path, a, b string
	fmt.Fscanf(input, "%s\n", &path)
	fmt.Fscanf(input, "%s\n", &a)
	fmt.Fscanf(input, "%s\n", &b)
	var buffer bytes.Buffer
	for i := len(path) - 1; i >= 0; i-- {
		buffer.WriteByte(path[i])
	}
	rpath := buffer.String()
	la := strings.Index(path, a)
	ra := strings.Index(rpath, a)
	forward := la > -1 && la + len(a) - 1 < strings.LastIndex(path, b)
	backward := ra > -1 && ra + len(a) - 1 < strings.LastIndex(rpath, b)
	if forward && backward {
		fmt.Println("both")
	} else if !forward && !backward {
		fmt.Println("fantasy")
	} else if forward {
		fmt.Println("forward")
	} else  {
		fmt.Println("backward")
	}
}

package main

import (
	"strings"
	"fmt"
	"strconv"
	"errors"
	"io"
	"unicode/utf8"
	"bytes"
	"os"
)

func main() {
	s, a, b := nextWord(), nextWord(), nextWord()
	ss_ := make([]rune, len(s))
	for i, x := range []rune(s) {
		ss_[len(ss_) - 1 - i] = x
	}
	ss := string(ss_)
	fa, fb := strings.Index(s, a), strings.LastIndex(s, b)
	fwd :=  fa != -1 && fb != -1 && fb >= fa + len(a)
	ba, bb := strings.Index(ss, a), strings.LastIndex(ss, b)
	bwd :=  ba != -1 && bb != -1 && bb >= ba + len(a)

	switch {
	case fwd && bwd:
		printf("both")
	case fwd:
		printf("forward")
	case bwd:
		printf("backward")
	default:
		printf("fantasy")
	}
	printf("\n")
}

var lineScanner *Scanner
var wordScanner *Scanner

func init() {
	lineScanner = NewScanner(os.Stdin)
	wordScanner = NewScanner(strings.NewReader(""))
	wordScanner.Split(ScanWords)
}

func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

func nextWord() string {
	for !wordScanner.Scan() {
		if err := wordScanner.Err(); err != nil {
			panic(err)
		}
		line, err := nextLine()
		if err != nil {
			return ""
		}
		wordScanner = NewScanner(strings.NewReader(line))
		wordScanner.Split(ScanWords)
	}
	return wordScanner.Text()
}

func nextInt() int {
	res, err := strconv.Atoi(nextWord())
	if err != nil {
		panic(err)
	}
	return res
}

func nextInt64() int64 {
	res, err := strconv.ParseInt(nextWord(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func nextFloat64() float64 {
	res, err := strconv.ParseFloat(nextWord(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

// Scanner provides a convenient interface for reading data such as
// a file of newline-delimited lines of text. Successive calls to
// the Scan method will step through the 'tokens' of a file, skipping
// the bytes between the tokens. The specification of a token is
// defined by a split function of type SplitFunc; the default split
// function breaks the input into lines with line termination stripped. Split
// functions are defined in this package for scanning a file into
// lines, bytes, UTF-8-encoded runes, and space-delimited words. The
// client may instead provide a custom split function.
//
// Scanning stops unrecoverably at EOF, the first I/O error, or a token too
// large to fit in the buffer. When a scan stops, the reader may have
// advanced arbitrarily far past the last token. Programs that need more
// control over error handling or large tokens, or must run sequential scans
// on a reader, should use bufio.Reader instead.
//
type Scanner struct {
	r            io.Reader // The reader provided by the client.
	split        SplitFunc // The function to split the tokens.
	maxTokenSize int       // Maximum size of a token; modified by tests.
	token        []byte    // Last token returned by split.
	buf          []byte    // Buffer used as argument to split.
	start        int       // First non-processed byte in buf.
	end          int       // End of data in buf.
	err          error     // Sticky error.
	empties      int       // Count of successive empty tokens.
	scanCalled   bool      // Scan has been called; buffer is in use.
	done         bool      // Scan has finished.
}

// SplitFunc is the signature of the split function used to tokenize the
// input. The arguments are an initial substring of the remaining unprocessed
// data and a flag, atEOF, that reports whether the Reader has no more data
// to give. The return values are the number of bytes to advance the input
// and the next token to return to the user, plus an error, if any. If the
// data does not yet hold a complete token, for instance if it has no newline
// while scanning lines, SplitFunc can return (0, nil, nil) to signal the
// Scanner to read more data into the slice and try again with a longer slice
// starting at the same point in the input.
//
// If the returned error is non-nil, scanning stops and the error
// is returned to the client.
//
// The function is never called with an empty data slice unless atEOF
// is true. If atEOF is true, however, data may be non-empty and,
// as always, holds unprocessed text.
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

// Errors returned by Scanner.
var (
	ErrTooLong = errors.New("bufio.Scanner: token too long")
	ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
	ErrAdvanceTooFar = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
)

const (
	// MaxScanTokenSize is the maximum size used to buffer a token
	// unless the user provides an explicit buffer with Scan.Buffer.
	// The actual maximum token size may be smaller as the buffer
	// may need to include, for instance, a newline.
	MaxScanTokenSize = 2 * 1024 * 2014

	startBufSize = 4096 // Size of initial allocation for buffer.
)

// NewScanner returns a new Scanner to read from r.
// The split function defaults to ScanLines.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        ScanLines,
		maxTokenSize: MaxScanTokenSize,
	}
}

// Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Err() error {
	if s.err == io.EOF {
		return nil
	}
	return s.err
}

// Bytes returns the most recent token generated by a call to Scan.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Scan. It does no allocation.
func (s *Scanner) Bytes() []byte {
	return s.token
}

// Text returns the most recent token generated by a call to Scan
// as a newly allocated string holding its bytes.
func (s *Scanner) Text() string {
	return string(s.token)
}

// ErrFinalToken is a special sentinel error value. It is intended to be
// returned by a Split function to indicate that the token being delivered
// with the error is the last token and scanning should stop after this one.
// After ErrFinalToken is received by Scan, scanning stops with no error.
// The value is useful to stop processing early or when it is necessary to
// deliver a final empty token. One could achieve the same behavior
// with a custom error value but providing one here is tidier.
// See the emptyFinalToken example for a use of this value.
var ErrFinalToken = errors.New("final token")

// Scan advances the Scanner to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Scan returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil.
// Scan panics if the split function returns 100 empty tokens without
// advancing the input. This is a common error mode for scanners.
func (s *Scanner) Scan() bool {
	if s.done {
		return false
	}
	s.scanCalled = true
	// Loop until we have a token.
	for {
		// See if we can get a token with what we already have.
		// If we've run out of data but have an error, give the split function
		// a chance to recover any remaining, possibly empty token.
		if s.end > s.start || s.err != nil {
			advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
			if err != nil {
				if err == ErrFinalToken {
					s.token = token
					s.done = true
					return true
				}
				s.setErr(err)
				return false
			}
			if !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				if s.err == nil || advance > 0 {
					s.empties = 0
				} else {
					// Returning tokens not advancing input at EOF.
					s.empties++
					if s.empties > 100 {
						panic("bufio.Scan: 100 empty tokens without progressing")
					}
				}
				return true
			}
		}
		// We cannot generate a token with what we are holding.
		// If we've already hit EOF or an I/O error, we are done.
		if s.err != nil {
			// Shut it down.
			s.start = 0
			s.end = 0
			return false
		}
		// Must read more data.
		// First, shift data to beginning of buffer if there's lots of empty space
		// or space is needed.
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf) / 2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		// Is the buffer full? If so, resize.
		if s.end == len(s.buf) {
			// Guarantee no overflow in the multiplication below.
			const maxInt = int(^uint(0) >> 1)
			if len(s.buf) >= s.maxTokenSize || len(s.buf) > maxInt / 2 {
				s.setErr(ErrTooLong)
				return false
			}
			newSize := len(s.buf) * 2
			if newSize == 0 {
				newSize = startBufSize
			}
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		// Finally we can read some input. Make sure we don't get stuck with
		// a misbehaving Reader. Officially we don't need to do this, but let's
		// be extra careful: Scanner is for safe, simple jobs.
		for loop := 0;; {
			n, err := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if err != nil {
				s.setErr(err)
				break
			}
			if n > 0 {
				s.empties = 0
				break
			}
			loop++
			if loop > 10 {
				s.setErr(io.ErrNoProgress)
				break
			}
		}
	}
}

// advance consumes n bytes of the buffer. It reports whether the advance was legal.
func (s *Scanner) advance(n int) bool {
	if n < 0 {
		s.setErr(ErrNegativeAdvance)
		return false
	}
	if n > s.end - s.start {
		s.setErr(ErrAdvanceTooFar)
		return false
	}
	s.start += n
	return true
}

// setErr records the first error encountered.
func (s *Scanner) setErr(err error) {
	if s.err == nil || s.err == io.EOF {
		s.err = err
	}
}

// Buffer sets the initial buffer to use when scanning and the maximum
// size of buffer that may be allocated during scanning. The maximum
// token size is the larger of max and cap(buf). If max <= cap(buf),
// Scan will use this buffer only and do no allocation.
//
// By default, Scan uses an internal buffer and sets the
// maximum token size to MaxScanTokenSize.
//
// Buffer panics if it is called after scanning has started.
func (s *Scanner) Buffer(buf []byte, max int) {
	if s.scanCalled {
		panic("Buffer called after Scan")
	}
	s.buf = buf[0:cap(buf)]
	s.maxTokenSize = max
}

// Split sets the split function for the Scanner.
// The default split function is ScanLines.
//
// Split panics if it is called after scanning has started.
func (s *Scanner) Split(split SplitFunc) {
	if s.scanCalled {
		panic("Split called after Scan")
	}
	s.split = split
}

// Split functions

// ScanBytes is a split function for a Scanner that returns each byte as a token.
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	return 1, data[0:1], nil
}

var errorRune = []byte(string(utf8.RuneError))

// ScanRunes is a split function for a Scanner that returns each
// UTF-8-encoded rune as a token. The sequence of runes returned is
// equivalent to that from a range loop over the input as a string, which
// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
// Because of the Scan interface, this makes it impossible for the client to
// distinguish correctly encoded replacement runes from encoding errors.
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}

	// Fast path 1: ASCII.
	if data[0] < utf8.RuneSelf {
		return 1, data[0:1], nil
	}

	// Fast path 2: Correct UTF-8 decode without error.
	_, width := utf8.DecodeRune(data)
	if width > 1 {
		// It's a valid encoding. Width cannot be one for a correctly encoded
		// non-ASCII rune.
		return width, data[0:width], nil
	}

	// We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
	// Is the error because there wasn't a full rune to be decoded?
	// FullRune distinguishes correctly between erroneous and incomplete encodings.
	if !atEOF && !utf8.FullRune(data) {
		// Incomplete; get more bytes.
		return 0, nil, nil
	}

	// We have a real UTF-8 encoding error. Return a properly encoded error rune
	// but advance only one byte. This matches the behavior of a range loop over
	// an incorrectly encoded string.
	return 1, errorRune, nil
}

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data) - 1] == '\r' {
		return data[0 : len(data) - 1]
	}
	return data
}

// ScanLines is a split function for a Scanner that returns each line of
// text, stripped of any trailing end-of-line marker. The returned line may
// be empty. The end-of-line marker is one optional carriage return followed
// by one mandatory newline. In regular expression notation, it is `\r?\n`.
// The last non-empty line of input will be returned even if it has no
// newline.
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\n'); i >= 0 {
		// We have a full newline-terminated line.
		return i + 1, dropCR(data[0:i]), nil
	}
	// If we're at EOF, we have a final, non-terminated line. Return it.
	if atEOF {
		return len(data), dropCR(data), nil
	}
	// Request more data.
	return 0, nil, nil
}

// isSpace reports whether the character is a Unicode white space character.
// We avoid dependency on the unicode package, but check validity of the implementation
// in the tests.
func isSpace(r rune) bool {
	if r <= '\u00FF' {
		// Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
		switch r {
		case ' ', '\t', '\n', '\v', '\f', '\r':
			return true
		case '\u0085', '\u00A0':
			return true
		}
		return false
	}
	// High-valued ones.
	if '\u2000' <= r && r <= '\u200a' {
		return true
	}
	switch r {
	case '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
		return true
	}
	return false
}

// ScanWords is a split function for a Scanner that returns each
// space-separated word of text, with surrounding spaces deleted. It will
// never return an empty string. The definition of space is set by
// unicode.IsSpace.
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	// Skip leading spaces.
	start := 0
	for width := 0; start < len(data); start += width {
		var r rune
		r, width = utf8.DecodeRune(data[start:])
		if !isSpace(r) {
			break
		}
	}
	// Scan until space, marking end of word.
	for width, i := 0, start; i < len(data); i += width {
		var r rune
		r, width = utf8.DecodeRune(data[i:])
		if isSpace(r) {
			return i + width, data[start:i], nil
		}
	}
	// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	// Request more data.
	return start, nil, nil
}

// Author: sighduck
// URL: https://codeforces.com/contest/8/problem/A

package main

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

func isValidOrder(flags string, firstPeriod string, secondPeriod string) bool {
	firstPeriodForwardIndex := strings.Index(flags, firstPeriod)
	if firstPeriodForwardIndex == -1 {
		return false
	}
	secondPeriodForwardIndex := strings.Index(
		flags[firstPeriodForwardIndex+len(firstPeriod):],
		secondPeriod,
	)
	if secondPeriodForwardIndex == -1 {
		return false
	}
	return true
}

func reverse(s string) string {
	runes := []rune(s)
	for i := 0; i < len(s)/2; i++ {
		runes[i], runes[len(s)-1-i] = runes[len(s)-1-i], runes[i]
	}
	return string(runes)
}

func Solve(flags string, firstPeriod string, secondPeriod string) string {
	isValidForward := isValidOrder(flags, firstPeriod, secondPeriod)
	isValidBackward := isValidOrder(reverse(flags), firstPeriod, secondPeriod)
	if isValidForward && isValidBackward {
		return "both"
	} else if isValidForward {
		return "forward"
	} else if isValidBackward {
		return "backward"
	}
	return "fantasy"
}

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

	var flags string
	var firstPeriod string
	var secondPeriod string
	fmt.Fscanf(reader, "%s\n", &flags)
	fmt.Fscanf(reader, "%s\n", &firstPeriod)
	fmt.Fscanf(reader, "%s\n", &secondPeriod)
	fmt.Fprintf(writer, "%s\n", Solve(flags, firstPeriod, secondPeriod))
}

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func seek(s, a, b string) bool {
  aPos := strings.Index(s, a)
  if aPos != -1 {
    bPos := strings.Index(s[aPos+len(a):], b)
    if bPos != -1 {
      return true
    }
  }
  return false
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  ab := getS()
  n := len(ab)
  baBytes := make([]byte, n)
  for i := 0; i < n; i++ {
    baBytes[i] = ab[n-1-i]
  }
  ba := string(baBytes)
  s1, s2 := getS(), getS()
  forward, backward := seek(ab, s1, s2), seek(ba, s1, s2)
  result := "fantasy"
  if forward && backward {
    result = "both"
  } else if forward {
    result = "forward"
  } else if backward {
    result = "backward"
  }
  writer.WriteString(fmt.Sprintf("%s\n", result))
}

// https://codeforces.com/contest/8/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	var path, a, b string
	fmt.Fscanf(input, "%s\n", &path)
	fmt.Fscanf(input, "%s\n", &a)
	fmt.Fscanf(input, "%s\n", &b)
	var buffer bytes.Buffer
	for i := len(path) - 1; i >= 0; i-- {
		buffer.WriteByte(path[i])
	}
	rpath := buffer.String()
	la := strings.Index(path, a)
	ra := strings.Index(rpath, a)
	forward := la > -1 && la + len(a) < strings.LastIndex(path, b)
	backward := ra > -1 && ra + len(a) < strings.LastIndex(rpath, b)
	if forward && backward {
		fmt.Println("both")
	} else if !forward && !backward {
		fmt.Println("fantasy")
	} else if forward {
		fmt.Println("forward")
	} else  {
		fmt.Println("backward")
	}
}

// https://codeforces.com/contest/2/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscanln(input, &n)
	total := make(map[string]int)
	histn := make([]string, n)
	hists := make([]int, n)
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanln(input, &name, &score)
		histn[i] = name
		hists[i] = score
		total[name] += score
	}
	max := 0
	wins := make(map[string]bool)
	for name, scores := range total {
		if scores >= max {
			if scores > max {
				max = scores
				wins = make(map[string]bool)
			}
			wins[name] = true
		}
	}

	result := make(map[string]int)
	for i := 0; i < len(histn); i++ {
		name := histn[i]
		if wins[name] {
			result[name] += hists[i]
			if result[name] >= max {
				fmt.Println(name)
				return
			}
		}
	}
}

// https://codeforces.com/contest/8/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	var path, a, b string
	fmt.Fscanln(input, &path)
	fmt.Fscanln(input, &a)
	fmt.Fscanln(input, &b)
	var buffer bytes.Buffer
	for i := len(a) - 1; i >= 0; i-- {
		buffer.WriteByte(a[i])
	}
	reca := buffer.String()
	buffer.Reset()
	for i := len(b) - 1; i >= 0; i-- {
		buffer.WriteByte(b[i])
	}
	recb := buffer.String()
	la := strings.Index(path, a)
	forward := la > -1 && la < strings.LastIndex(path, b)
	rb := strings.Index(path, recb)
	backward := rb > -1 && rb < strings.LastIndex(path, reca)
	if forward && backward {
		fmt.Println("both")
	} else if !forward && !backward {
		fmt.Println("fantasy")
	} else if forward {
		fmt.Println("forward")
	} else  {
		fmt.Println("backward")
	}
}

// https://codeforces.com/contest/8/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	var path, a, b string
	fmt.Fscanln(input, &path)
	fmt.Fscanln(input, &a)
	fmt.Fscanln(input, &b)
	var buffer bytes.Buffer
	for i := len(path) - 1; i >= 0; i-- {
		buffer.WriteByte(path[i])
	}
	rpath := buffer.String()
	la := strings.Index(path, a)
	forward := la > -1 && la <= strings.LastIndex(path, b)
	ra := strings.Index(rpath, a)
	backward := ra > -1 && ra <= strings.LastIndex(rpath, b)
	if forward && backward {
		fmt.Println("both")
	} else if !forward && !backward {
		fmt.Println("fantasy")
	} else if forward {
		fmt.Println("forward")
	} else  {
		fmt.Println("backward")
	}
}

// https://codeforces.com/contest/8/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	var path, a, b string
	fmt.Fscanf(input, "%s\n", &path)
	fmt.Fscanf(input, "%s\n", &a)
	fmt.Fscanf(input, "%s\n", &b)
	var buffer bytes.Buffer
	for i := len(path) - 1; i >= 0; i-- {
		buffer.WriteByte(path[i])
	}
	rpath := buffer.String()
	la := strings.Index(path, a)
	forward := la > -1 && la <= strings.LastIndex(path, b)
	ra := strings.Index(rpath, a)
	backward := ra > -1 && ra <= strings.LastIndex(rpath, b)
	if forward && backward {
		fmt.Println("both")
	} else if !forward && !backward {
		fmt.Println("fantasy")
	} else if forward {
		fmt.Println("forward")
	} else  {
		fmt.Println("backward")
	}
}

// https://codeforces.com/contest/8/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	var path, a, b string
	fmt.Fscanln(input, &path)
	fmt.Fscanln(input, &a)
	fmt.Fscanln(input, &b)
	var buffer bytes.Buffer
	for i := len(path) - 1; i >= 0; i-- {
		buffer.WriteByte(path[i])
	}
	rpath := buffer.String()
	la := strings.Index(path, a)
	forward := la > -1 && la < strings.LastIndex(path, b)
	ra := strings.Index(rpath, a)
	backward := ra > -1 && ra < strings.LastIndex(rpath, b)
	if forward && backward {
		fmt.Println("both")
	} else if !forward && !backward {
		fmt.Println("fantasy")
	} else if forward {
		fmt.Println("forward")
	} else  {
		fmt.Println("backward")
	}
}

// https://codeforces.com/contest/8/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	var path, a, b string
	fmt.Fscanf(input, "%s", &path)
	fmt.Fscanf(input, "%s", &a)
	fmt.Fscanf(input, "%s", &b)
	var buffer bytes.Buffer
	for i := len(path) - 1; i >= 0; i-- {
		buffer.WriteByte(path[i])
	}
	rpath := buffer.String()
	la := strings.Index(path, a)
	forward := la > -1 && la <= strings.LastIndex(path, b)
	ra := strings.Index(rpath, a)
	backward := ra > -1 && ra <= strings.LastIndex(rpath, b)
	if forward && backward {
		fmt.Println("both")
	} else if !forward && !backward {
		fmt.Println("fantasy")
	} else if forward {
		fmt.Println("forward")
	} else  {
		fmt.Println("backward")
	}
}

// Author: sighduck
// URL: https://codeforces.com/contest/8/problem/A

package main

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

func isValidOrder(flags string, firstPeriod string, secondPeriod string) bool {
	firstPeriodForwardIndex := strings.Index(flags, firstPeriod)
	if firstPeriodForwardIndex == -1 {
		return false
	}
	secondPeriodForwardIndex := strings.Index(flags[firstPeriodForwardIndex:], secondPeriod)
	if secondPeriodForwardIndex == -1 {
		return false
	}
	return true
}

func reverse(s string) string {
	runes := []rune(s)
	for i := 0; i < len(s)/2; i++ {
		runes[i], runes[len(s)-1-i] = runes[len(s)-1-i], runes[i]
	}
	return string(runes)
}

func Solve(flags string, firstPeriod string, secondPeriod string) string {
	isValidForward := isValidOrder(flags, firstPeriod, secondPeriod)
	isValidBackward := isValidOrder(reverse(flags), firstPeriod, secondPeriod)
	if isValidForward && isValidBackward {
		return "both"
	} else if isValidForward {
		return "forward"
	} else if isValidBackward {
		return "backward"
	}
	return "fantasy"
}

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

	var flags string
	var firstPeriod string
	var secondPeriod string
	fmt.Fscanf(reader, "%s\n", &flags)
	fmt.Fscanf(reader, "%s\n", &firstPeriod)
	fmt.Fscanf(reader, "%s\n", &secondPeriod)
	fmt.Fprintf(writer, "%s\n", Solve(flags, firstPeriod, secondPeriod))
}


You are given array $$$a_1, a_2, \ldots, a_n$$$, consisting of non-negative integers.Let's define operation of "elimination" with integer parameter $$$k$$$ ($$$1 \leq k \leq n$$$) as follows:  Choose $$$k$$$ distinct array indices $$$1 \leq i_1 < i_2 < \ldots < i_k \le n$$$.  Calculate $$$x = a_{i_1} ~ \& ~ a_{i_2} ~ \& ~ \ldots ~ \& ~ a_{i_k}$$$, where $$$\&$$$ denotes the bitwise AND operation (notes section contains formal definition).  Subtract $$$x$$$ from each of $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$; all other elements remain untouched. Find all possible values of $$$k$$$, such that it's possible to make all elements of array $$$a$$$ equal to $$$0$$$ using a finite number of elimination operations with parameter $$$k$$$. It can be proven that exists at least one possible $$$k$$$ for any array $$$a$$$.Note that you firstly choose $$$k$$$ and only after that perform elimination operations with value $$$k$$$ you've chosen initially.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < 2^{30}$$$) — array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.

For each test case, print all values $$$k$$$, such that it's possible to make all elements of $$$a$$$ equal to $$$0$$$ in a finite number of elimination operations with the given parameter $$$k$$$. Print them in increasing order.

NoteIn the first test case:  If $$$k = 1$$$, we can make four elimination operations with sets of indices $$$\{1\}$$$, $$$\{2\}$$$, $$$\{3\}$$$, $$$\{4\}$$$. Since $$$\&$$$ of one element is equal to the element itself, then for each operation $$$x = a_i$$$, so $$$a_i - x = a_i - a_i = 0$$$.  If $$$k = 2$$$, we can make two elimination operations with, for example, sets of indices $$$\{1, 3\}$$$ and $$$\{2, 4\}$$$: $$$x = a_1 ~ \& ~ a_3$$$ $$$=$$$ $$$a_2 ~ \& ~ a_4$$$ $$$=$$$ $$$4 ~ \& ~ 4 = 4$$$. For both operations $$$x = 4$$$, so after the first operation $$$a_1 - x = 0$$$ and $$$a_3 - x = 0$$$, and after the second operation — $$$a_2 - x = 0$$$ and $$$a_4 - x = 0$$$.  If $$$k = 3$$$, it's impossible to make all $$$a_i$$$ equal to $$$0$$$. After performing the first operation, we'll get three elements equal to $$$0$$$ and one equal to $$$4$$$. After that, all elimination operations won't change anything, since at least one chosen element will always be equal to $$$0$$$.  If $$$k = 4$$$, we can make one operation with set $$$\{1, 2, 3, 4\}$$$, because $$$x = a_1 ~ \& ~ a_2 ~ \& ~ a_3 ~ \& ~ a_4$$$ $$$= 4$$$. In the second test case, if $$$k = 2$$$ then we can make the following elimination operations:  Operation with indices $$$\{1, 3\}$$$: $$$x = a_1 ~ \& ~ a_3$$$ $$$=$$$ $$$13 ~ \& ~ 25 = 9$$$. $$$a_1 - x = 13 - 9 = 4$$$ and $$$a_3 - x = 25 - 9 = 16$$$. Array $$$a$$$ will become equal to $$$[4, 7, 16, 19]$$$.  Operation with indices $$$\{3, 4\}$$$: $$$x = a_3 ~ \& ~ a_4$$$ $$$=$$$ $$$16 ~ \& ~ 19 = 16$$$. $$$a_3 - x = 16 - 16 = 0$$$ and $$$a_4 - x = 19 - 16 = 3$$$. Array $$$a$$$ will become equal to $$$[4, 7, 0, 3]$$$.  Operation with indices $$$\{2, 4\}$$$: $$$x = a_2 ~ \& ~ a_4$$$ $$$=$$$ $$$7 ~ \& ~ 3 = 3$$$. $$$a_2 - x = 7 - 3 = 4$$$ and $$$a_4 - x = 3 - 3 = 0$$$. Array $$$a$$$ will become equal to $$$[4, 4, 0, 0]$$$.  Operation with indices $$$\{1, 2\}$$$: $$$x = a_1 ~ \& ~ a_2$$$ $$$=$$$ $$$4 ~ \& ~ 4 = 4$$$. $$$a_1 - x = 4 - 4 = 0$$$ and $$$a_2 - x = 4 - 4 = 0$$$. Array $$$a$$$ will become equal to $$$[0, 0, 0, 0]$$$. Formal definition of bitwise AND:Let's define bitwise AND ($$$\&$$$) as follows. Suppose we have two non-negative integers $$$x$$$ and $$$y$$$, let's look at their binary representations (possibly, with leading zeroes): $$$x_k \dots x_2 x_1 x_0$$$ and $$$y_k \dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of number $$$x$$$, and $$$y_i$$$ is the $$$i$$$-th bit of number $$$y$$$. Let $$$r = x ~ \& ~ y$$$ is a result of operation $$$\&$$$ on number $$$x$$$ and $$$y$$$. Then binary representation of $$$r$$$ will be $$$r_k \dots r_2 r_1 r_0$$$, where:$$$$$$ r_i = \begin{cases} 1, ~ \text{if} ~ x_i = 1 ~ \text{and} ~ y_i = 1 \\ 0, ~ \text{if} ~ x_i = 0 ~ \text{or} ~ y_i = 0 \end{cases} $$$$$$

package main

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

/*
1
6
5 6 4 1 6 1
2 4 1 5 4 1
---
1 = min(3, 0+1)
=====
1
5
9 5 5 5 1
1 5 5 5 9
---
0
=======
1
4
1 5 1 1
9 9 3 9
---
14 = min(8+8, 2+4+8)
*/

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

	bitToCnt := make(map[int]int)

	for i := 0; i < n; i++ {
		var a int
		scanf("%d", &a)

		j := 1
		for j != 0 {
			if a&j > 0 {
				bitToCnt[j]++
			}
			j <<= 1
		}
	}
	scanf("\n")

	for i := 1; i <= n; i++ {
		divisibleToAll := true
		for _, cnt := range bitToCnt {
			if cnt%i != 0 {
				divisibleToAll = false
				break
			}
		}

		if divisibleToAll {
			fmt.Fprintf(writer, "%d ", i)
		}
	}
	fmt.Fprintln(writer)
}

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

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

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

const maxUint = ^uint(0)

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

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

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

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

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

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int64) int64 {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int64) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

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

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

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

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

	return true
}

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

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

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

	num = abs(num)

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

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

//goland:noinspection GoUnusedFunction
func findSet(parent []int, v int) int {
	if v == parent[v] {
		return v
	}

	parent[v] = findSet(parent, parent[v])

	return parent[v]
}

//goland:noinspection GoUnusedFunction
func unionSets(parent []int, v, u int) {
	v = findSet(parent, v)
	u = findSet(parent, u)

	if v != u {
		parent[v] = u
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"

)

var n int

var a []int

func main() {

	r := bufio.NewReader(os.Stdin)

	var t int

	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		fmt.Fscan(r, &n)

		a = make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(r, &a[j])
		}

		solve()

		fmt.Println()
	}
}

func solve()  {

	cnts := make([]int, 31)

	for i := 30; i >= 0; i-- {
		for j := 0; j < n; j++ {
			if a[j] >> uint(i) & 0x1 == 1 {
				cnts[i]++
			}
		}
	}

	var g int = cnts[0]

	for i := 1; i < 31; i++ {
		g = GCD(g, cnts[i])
	}

	for i := 1; i <= n; i++ {
		if g % i == 0 {
			fmt.Print(i)
			fmt.Print(" ")
		}
	}
}

// greatest common divisor (GCD) via Euclidean algorithm
func GCD(a, b int) int {
	for b != 0 {
		t := b
		b = a % b
		a = t
	}
	return a
}

package main

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

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

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

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

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

func bin(a int) []int {
	var b []int
	for a != 0 {
		b = append(b, a&1)
		a >>= 1
	}
	// for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
	// 	b[i], b[j] = b[j], b[i]
	// }
	return b
}

func main() {
	var T int
	T = 1
	scanf("%d", &T)
	for t := 0; t < T; t++ {
		var n int
		scanf("\n%d\n", &n)
		arr := make([]int, n)
		mp := make(map[int]int)
		for i := 0; i < n; i++ {
			scanf("%d", &arr[i])
			b := bin(arr[i])
			for id, x := range b {
				if x == 1 {
					mp[id]++
				}
			}
		}
		for i := 1; i <= n; i++ {
			var ok bool = true
			for _, value := range mp {
				if value % i != 0 {
					ok = false
					break
				}
			}
			if ok {
				fmt.Printf("%d ", i)
			}
		}
		fmt.Printf("\n")
	}
}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })

func MIN(x, y int64) int64 {
	if x > y {
		return y
	} else {
		return x
	}
}

func MINN(x, y int) int {
	if x > y {
		return y
	} else {
		return x
	}
}

func MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

func MAX(x, y int64) int64 {
	if x > y {
		return x
	} else {
		return y
	}
}

func MAXX(x, y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}
}

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

func MODULE(x, y int) int {
	if x > y {
		return x - y
	} else {
		return y - x
	}
}

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

func Sum(n, m int) int {
	var ans int

	if n == 1 {
		return 0
	} else {
		for i := 2; i < n; i++ {
			ans = (ans + Sum(i, m)) % m
		}
		for j := 2; j < n+1; j++ {
			ans = (ans + Sum(n/j, m)) % m
		}
		return ans
	}
}

func ChangeStringToDate(x string) (t time.Time, err error) {
	t, err = time.Parse("2006-01-02", x)
	return
}

func DiffrenceBetweenTwoDates(first, second time.Time) int64 {
	date := first
	date2 := second
	k := date.Unix() - date2.Unix()
	return k
}

func Union(a, b []int) []int {
	m := make(map[int]bool)

	for _, item := range a {
		m[item] = true
	}

	for _, item := range b {
		if _, ok := m[item]; !ok {
			a = append(a, item)
		}
	}
	return a
}

// for o := 0; o < t; o++ {
// 	var a, b, c int
// 	fmt.Fscan(input, &a, &b, &c)

// 	A := a % 2
// 	B := b % 2
// 	C := c % 2
// 	if A+B+C == 0 {
// 		fmt.Println(0)
// 	}
// 	if A+B+C == 1 {
// 		if A == 1 {
// 			fmt.Println(1)
// 		}
// 		if B == 1 {
// 			if a >= 2 {
// 				fmt.Println(0)
// 			} else {
// 				fmt.Println(2)
// 			}
// 		}
// 		if C == 1 {
// 			if a > 0
// 			fmt.Println(1)
// 		}
// 	}
// 	if A+B+C == 2 {

// 	}
// 	if A+B+C == 3 {
// 		fmt.Println(0)
// 	}

// }

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

func Ans(ARR []int) {
	if len(ARR) < 2 {
		return
	}
	if len(ARR) == 2 {
		fmt.Println(ARR[1])
		fmt.Println(-ARR[0])
	} else {
		if len(ARR) == 3 {
			first := ARR[0]
			Midd := ARR[1]
			Last := ARR[2]
			var F, M, L int
			Pos := 0
			Neg := 0
			if first > 0 {
				Pos++
			} else {
				Neg++
			}
			if Midd > 0 {
				Pos++
			} else {
				Neg++
			}
			if Last > 0 {
				Pos++
			} else {
				Neg++
			}
			if Pos*Neg != 0 {
				if ABS(first) == ABS(Midd) && ABS(Midd) == ABS(Last) {
					if first == Midd {
						if Midd == Last {
							F = -1
							M = -1
							L = 2
						} else {
							F = 1
							M = 1
							L = 2
						}
					} else {
						if first == Last {
							F = 1
							L = 1
							M = 2
						} else {
							M = 1
							L = 1
							F = 2
						}
					}
				} else {
					One := first + Midd
					Two := Midd + Last
					Thr := first + Last
					l := 0
					if One != 0 && ABS(One) <= 10000 {
						F = Last
						M = Last
						L = -One
						l = 1
					}

					if Two != 0 && ABS(Two) <= 10000 && l == 0 {
						F = -Two
						M = first
						L = first
						l = 1
					}
					if Thr != 0 && ABS(Thr) <= 10000 && l == 0 {
						F = Midd
						M = -Thr
						L = Midd
					}

				}
			} else {
				if ABS(first) == ABS(Midd) && ABS(Midd) == ABS(Last) {
					F = -1
					M = -1
					L = 2
				} else {
					One := first - Midd
					Two := Midd - Last
					Thr := first - Last
					l := 0
					if One != 0 && ABS(One) <= 10000 {
						F = -Last
						M = Last
						L = One
						l = 1
					}

					if Two != 0 && ABS(Two) <= 10000 && l == 0 {
						F = Two
						M = -first
						L = first
						l = 1
					}
					if Thr != 0 && ABS(Thr) <= 10000 && l == 0 {
						F = -Midd
						M = Thr
						L = Midd
					}

				}
			}

			fmt.Println(F)
			fmt.Println(M)
			fmt.Println(L)
		} else {
			Q := make([]int, 0)
			P := make([]int, 0)
			P = append(P, ARR[0], ARR[1])
			p := len(ARR)
			for i := 2; i < p; i++ {
				Q = append(Q, ARR[i])
			}
			Ans(P)
			Ans(Q)
		}
	}
}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)

		ARR := make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &ARR[i])
		}

		B := make([]int, 0)
		for j := 1; j < 32; j++ {
			p := 0
			for i := 0; i < n; i++ {
				if ARR[i]%2 == 1 {
					p++
				}
				ARR[i] = ARR[i] / 2
			}
			if p != 0 {
				B = append(B, p)
			}
		}

		if len(B) == 0 {
			for i := 1; i < n+1; i++ {
				fmt.Println(i)
			}
		} else {
			var Init int64
			Init = int64(B[0])
			s := len(B)
			for i := 1; i < s; i++ {
				Init = GCD(int64(Init), int64(B[i]))
			}

			for i := 1; int64(i) <= Init; i++ {
				if Init%int64(i) == 0 {
					fmt.Println(i)
				}
			}

		}

	}

}

package main

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

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

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

		m := make([]int, 30)
		for i := 0; i < n; i++ {
			var v int
			fmt.Fscan(in, &v)

			var pos int
			for v > 0 {
				if v%2 != 0 {
					m[pos]++
				}
				v /= 2
				pos++
			}
		}

		fmt.Fprintf(out, "1 ")
		for i := 2; i <= n; i++ {
			var f bool
			for _, v := range m {
				if v%i != 0 {
					f = false
					break
				}
				f = true
			}
			if f {
				fmt.Fprintf(out, "%d ", i)
			}
		}
		fmt.Fprintln(out)
	}
}


After playing with her beautiful array, Mishka decided to learn some math. After learning how to multiply, divide and what is divisibility, she is now interested in solving the following problem.You are given integer k and array a1, a2, ..., an of n integers. You are to find non-empty subsequence of array elements such that the product of its elements is divisible by k and it contains minimum possible number of elements.Formally, you are to find a sequence of indices 1 ≤ i1 < i2 < ... < im ≤ n such that  is divisible by k while m is minimum possible among all such variants.If there are more than one such subsequences, you should choose one among them, such that sum of its elements is minimum possible.Mishka quickly solved this problem. Will you do so?

The first line of the input contains two integers n and k (1 ≤ n ≤ 1 000, 1 ≤ k ≤ 1012). The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1012) — array elements.

Print single positive integer m in the first line — the number of elements in desired sequence. In the second line print m distinct integers — the sequence of indices of given array elements, which should be taken into the desired sequence.  If there are more than one such subsequence (e.g. subsequence of minimum possible number of elements and with minimum possible sum of elements), you can print any of them. If there are no such subsequences, print  - 1 in the only line.

package main

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

import "sort"

var in *bufio.Scanner
var out *bufio.Writer

func gcd(x int64, y int64) int64 {
	var r int64
	for y != 0 {
		r = x % y
		x = y
		y = r
	}
	return x
}

type int64array []int64

func (s int64array) Len() int {
	return len(s)
}

func (s int64array) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s int64array) Less(i, j int) bool {
	return s[i] < s[j]
}

const inf = 1000000000
const inf64 = 10000000000000000

var n, m int
var k, x int64
var a, d, b int64array
var pos map[int64]int
var f, trace [][]int
var g [][]int64

func main() {
	in = bufio.NewScanner(os.Stdin)
	out = bufio.NewWriter(os.Stdout)

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan()
	n, _ = strconv.Atoi(in.Text())

	in.Scan()
	k, _ = strconv.ParseInt(in.Text(), 10, 64)

	a = make([]int64, n+1)
	b = make([]int64, n+1)
	for i := 1; i <= n; i++ {
		in.Scan()
		a[i], _ = strconv.ParseInt(in.Text(), 10, 64)
		b[i] = gcd(k, a[i])
	}

	if k == 1 {
		best := 1
		for i := 2; i <= n; i++ {
			if a[i] < a[best] {
				best = i
			}
		}
		out.WriteString("1\n")
		out.WriteString(strconv.Itoa(best))
		out.WriteByte('\n')
		return
	}

	for x = 1; x*x <= k; x++ {
		if k%x == 0 {
			d = append(d, x)
			if k/x != x {
				d = append(d, k/x)
			}
		}
	}

	m = len(d)
	sort.Sort(d)

	pos = make(map[int64]int)
	f = make([][]int, m)
	g = make([][]int64, m)
	trace = make([][]int, m)

	for i := 0; i < m; i++ {
		f[i] = make([]int, n+1)
		g[i] = make([]int64, n+1)
		trace[i] = make([]int, n+1)
		pos[d[i]] = i
	}

	for j := 0; j <= n; j++ {
		f[0][j] = 0
		g[0][j] = 0
	}

	for i := 1; i < m; i++ {
		f[i][0] = inf
		g[i][0] = inf
		for j := 1; j <= n; j++ {
			f[i][j] = f[i][j-1]
			g[i][j] = g[i][j-1]
			trace[i][j] = i
			y := gcd(d[i], b[j])
			if d[i]%y == 0 {
				x := d[i] / y
				p := pos[x]
				if (f[i][j] > f[p][j-1]+1) || ((f[i][j] == f[p][j-1]+1) && (g[i][j] > g[p][j-1]+a[j])) {
					f[i][j] = f[p][j-1] + 1
					g[i][j] = g[p][j-1] + a[j]
					trace[i][j] = p
				}
			}
		}
	}

	res := f[m-1][n]
	if res < inf {
		out.WriteString(strconv.Itoa(res))
		out.WriteByte('\n')
		i := m - 1
		for j := n; j >= 1; j-- {
			p := trace[i][j]
			if p < i {
				out.WriteString(strconv.Itoa(j))
				out.WriteByte(' ')
				i = p
			}
		}
	} else {
		out.WriteString("-1\n")
	}
}

package main

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

var in *bufio.Scanner
var out *bufio.Writer

func gcd(x int64, y int64) int64 {
	var r int64
	for y != 0 {
		r = x % y
		x = y
		y = r
	}
	return x
}

type int64array []int64

func (s int64array) Len() int {
	return len(s)
}

func (s int64array) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s int64array) Less(i, j int) bool {
	return s[i] < s[j]
}

const inf = 1000000000

var n, m int
var k, x int64
var a, d, g int64array
var f []int
var pos map[int64]int
var trace [][]int

func main() {
	in = bufio.NewScanner(os.Stdin)
	out = bufio.NewWriter(os.Stdout)

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan()
	n, _ = strconv.Atoi(in.Text())

	in.Scan()
	k, _ = strconv.ParseInt(in.Text(), 10, 64)

	a = make([]int64, n)
	for i := 0; i < n; i++ {
		in.Scan()
		a[i], _ = strconv.ParseInt(in.Text(), 10, 64)
		a[i] = gcd(k, a[i])
	}

	for x = 1; x*x <= k; x++ {
		if k%x == 0 {
			d = append(d, x)
			if k/x != x {
				d = append(d, k/x)
			}
		}
	}

	m = len(d)
	sort.Sort(d)

	pos = make(map[int64]int)
	f = make([]int, m)
	g = make([]int64, m)

	for j := 0; j < m; j++ {
		pos[d[j]] = j
		f[j] = inf
		g[j] = inf
	}
	f[0] = 0
	g[0] = 0

	trace = make([][]int, n)

	for i := 0; i < n; i++ {
		trace[i] = make([]int, m)
		for j := 0; j < m; j++ {
			trace[i][j] = i - 1
			if d[j]%a[i] == 0 {
				x := d[j] / a[i]
				p := pos[x]
				if f[j] > f[p]+1 {
					f[j] = f[p] + 1
					g[j] = g[p] + a[i]
					trace[i][j] = i
				} else if (f[j] == f[p]+1) && (g[j] > g[p]+a[i]) {
					g[j] = g[p] + a[i]
					trace[i][j] = i
				}
			}
		}
	}

	if f[m-1] < inf {
		out.WriteString(strconv.Itoa(f[m-1]))
		out.WriteByte('\n')

		j := m - 1
		for i := n - 1; i >= 0; i-- {
			t := trace[i][j]
			if t == i {
				x := d[j] / a[i]
				j = pos[x]
				out.WriteString(strconv.Itoa(i + 1))
				out.WriteByte(' ')
			}
		}
	} else {
		out.WriteString("-1\n")
	}
}

package main

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

var in *bufio.Scanner
var out *bufio.Writer

func gcd(x int64, y int64) int64 {
	var r int64
	for y != 0 {
		r = x % y
		x = y
		y = r
	}
	return x
}

type int64array []int64

func (s int64array) Len() int {
	return len(s)
}

func (s int64array) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s int64array) Less(i, j int) bool {
	return s[i] < s[j]
}

const inf = 1000000000

var n, m int
var k, x int64
var a, d int64array
var f []int
var pos map[int64]int
var trace [][]int

func main() {
	in = bufio.NewScanner(os.Stdin)
	out = bufio.NewWriter(os.Stdout)

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan()
	n, _ = strconv.Atoi(in.Text())

	in.Scan()
	k, _ = strconv.ParseInt(in.Text(), 10, 64)

	a = make([]int64, n)
	for i := 0; i < n; i++ {
		in.Scan()
		a[i], _ = strconv.ParseInt(in.Text(), 10, 64)
		a[i] = gcd(k, a[i])
	}

	for x = 1; x*x <= k; x++ {
		if k%x == 0 {
			d = append(d, x)
			if k/x != x {
				d = append(d, k/x)
			}
		}
	}

	m = len(d)
	sort.Sort(d)

	pos = make(map[int64]int)
	f = make([]int, m)

	for j := 0; j < m; j++ {
		pos[d[j]] = j
		f[j] = inf
	}
	f[0] = 0

	trace = make([][]int, n)

	for i := 0; i < n; i++ {
		trace[i] = make([]int, m)
		for j := 0; j < m; j++ {
			trace[i][j] = i - 1
			if d[j]%a[i] == 0 {
				x := d[j] / a[i]
				p := pos[x]
				if f[j] > f[p]+1 {
					f[j] = f[p] + 1
					trace[i][j] = i
				}
			}
		}
	}

	if f[m-1] < inf {
		out.WriteString(strconv.Itoa(f[m-1]))
		out.WriteByte('\n')

		j := m - 1
		for i := n - 1; i >= 0; i-- {
			t := trace[i][j]
			if t == i {
				x := d[j] / a[i]
				j = pos[x]
				out.WriteString(strconv.Itoa(i + 1))
				out.WriteByte(' ')
			}
		}
	} else {
		out.WriteString("-1\n")
	}
}

package main

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

var in *bufio.Scanner
var out *bufio.Writer

func gcd(x int64, y int64) int64 {
	var r int64
	for y != 0 {
		r = x % y
		x = y
		y = r
	}
	return x
}

type int64array []int64

func (s int64array) Len() int {
	return len(s)
}

func (s int64array) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s int64array) Less(i, j int) bool {
	return s[i] < s[j]
}

const inf = 1000000000
const inf64 = 10000000000000000

var n, m int
var k, x int64
var a, b, d, g int64array
var f []int
var pos map[int64]int
var trace [][]int

func main() {
	in = bufio.NewScanner(os.Stdin)
	out = bufio.NewWriter(os.Stdout)

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan()
	n, _ = strconv.Atoi(in.Text())

	in.Scan()
	k, _ = strconv.ParseInt(in.Text(), 10, 64)

	a = make([]int64, n)
	b = make([]int64, n)
	for i := 0; i < n; i++ {
		in.Scan()
		a[i], _ = strconv.ParseInt(in.Text(), 10, 64)
		b[i] = gcd(k, a[i])
	}

	for x = 1; x*x <= k; x++ {
		if k%x == 0 {
			d = append(d, x)
			if k/x != x {
				d = append(d, k/x)
			}
		}
	}

	m = len(d)
	sort.Sort(d)

	pos = make(map[int64]int)
	f = make([]int, m)
	g = make([]int64, m)

	for j := 0; j < m; j++ {
		pos[d[j]] = j
		f[j] = inf
		g[j] = inf64
	}
	f[0] = 0
	g[0] = 0

	trace = make([][]int, n)

	for i := 0; i < n; i++ {
		trace[i] = make([]int, m)
		for j := 0; j < m; j++ {
			trace[i][j] = i - 1
			if d[j]%b[i] == 0 {
				x := d[j] / b[i]
				p := pos[x]
				if (f[j] > f[p]+1) || ((f[j] == f[p]+1) && (g[j] > g[p]+a[i])) {
					f[j] = f[p] + 1
					g[j] = g[p] + a[i]
					trace[i][j] = i
				}
			}
		}
	}

	if f[m-1] < inf {
		out.WriteString(strconv.Itoa(f[m-1]))
		out.WriteByte('\n')

		j := m - 1
		for i := n - 1; i >= 0; i-- {
			t := trace[i][j]
			if t == i {
				x := d[j] / b[i]
				j = pos[x]
				out.WriteString(strconv.Itoa(i + 1))
				out.WriteByte(' ')
			}
		}
	} else {
		out.WriteString("-1\n")
	}
}

package main

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

var in *bufio.Scanner
var out *bufio.Writer

func gcd(x int64, y int64) int64 {
	var r int64
	for y != 0 {
		r = x % y
		x = y
		y = r
	}
	return x
}

type int64array []int64

func (s int64array) Len() int {
	return len(s)
}

func (s int64array) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s int64array) Less(i, j int) bool {
	return s[i] < s[j]
}

const inf = 1000000000
const inf64 = 10000000000000000

var n, m int
var k, x int64
var a, b, d int64array
var pos map[int64]int
var f, trace [][]int
var g [][]int64

func main() {
	in = bufio.NewScanner(os.Stdin)
	out = bufio.NewWriter(os.Stdout)

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan()
	n, _ = strconv.Atoi(in.Text())

	in.Scan()
	k, _ = strconv.ParseInt(in.Text(), 10, 64)

	a = make([]int64, n+1)
	b = make([]int64, n+1)
	for i := 1; i <= n; i++ {
		in.Scan()
		a[i], _ = strconv.ParseInt(in.Text(), 10, 64)
		b[i] = gcd(k, a[i])
	}

	for x = 1; x*x <= k; x++ {
		if k%x == 0 {
			d = append(d, x)
			if k/x != x {
				d = append(d, k/x)
			}
		}
	}

	m = len(d)
	sort.Sort(d)

	pos = make(map[int64]int)
	f = make([][]int, m)
	g = make([][]int64, m)
	trace = make([][]int, m)

	for i := 0; i < m; i++ {
		f[i] = make([]int, n+1)
		g[i] = make([]int64, n+1)
		trace[i] = make([]int, n+1)
		pos[d[i]] = i
	}

	for j := 0; j <= n; j++ {
		f[0][j] = 0
		g[0][j] = 0
	}

	for i := 1; i < m; i++ {
		f[i][0] = inf
		g[i][0] = inf
		for j := 1; j <= n; j++ {
			f[i][j] = f[i][j-1]
			g[i][j] = g[i][j-1]
			trace[i][j] = i
			y := gcd(d[i], b[j])
			if d[i]%y == 0 {
				x := d[i] / y
				p := pos[x]
				if (f[i][j] > f[p][j-1]+1) || ((f[i][j] == f[p][j-1]+1) && (g[i][j] > g[p][j-1]+a[j])) {
					f[i][j] = f[p][j-1] + 1
					g[i][j] = g[p][j-1] + a[j]
					trace[i][j] = p
				}
			}
		}
	}

	res := f[m-1][n]
	if res < inf {
		out.WriteString(strconv.Itoa(res))
		out.WriteByte('\n')
		i := m - 1
		for j := n; j >= 1; j-- {
			p := trace[i][j]
			if p < i {
				out.WriteString(strconv.Itoa(j))
				out.WriteByte(' ')
				i = p
			}
		}
	} else {
		out.WriteString("-1\n")
	}
}

package main

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

var in *bufio.Scanner
var out *bufio.Writer

func gcd(x int64, y int64) int64 {
	var r int64
	for y != 0 {
		r = x % y
		x = y
		y = r
	}
	return x
}

type int64array []int64

func (s int64array) Len() int {
	return len(s)
}

func (s int64array) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s int64array) Less(i, j int) bool {
	return s[i] < s[j]
}

const inf = 1000000000
const inf64 = 10000000000000000

var n, m int
var k, x int64
var a, b, d int64array
var pos map[int64]int
var f, trace [][]int
var g [][]int64

func main() {
	in = bufio.NewScanner(os.Stdin)
	out = bufio.NewWriter(os.Stdout)

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan()
	n, _ = strconv.Atoi(in.Text())

	in.Scan()
	k, _ = strconv.ParseInt(in.Text(), 10, 64)

	a = make([]int64, n+1)
	b = make([]int64, n+1)
	for i := 1; i <= n; i++ {
		in.Scan()
		a[i], _ = strconv.ParseInt(in.Text(), 10, 64)
		b[i] = gcd(k, a[i])
	}

	for x = 1; x*x <= k; x++ {
		if k%x == 0 {
			d = append(d, x)
			if k/x != x {
				d = append(d, k/x)
			}
		}
	}

	m = len(d)
	sort.Sort(d)

	pos = make(map[int64]int)
	f = make([][]int, m)
	g = make([][]int64, m)
	trace = make([][]int, m)

	for i := 0; i < m; i++ {
		f[i] = make([]int, n+1)
		g[i] = make([]int64, n+1)
		trace[i] = make([]int, n+1)
		pos[d[i]] = i
	}

	for j := 0; j <= n; j++ {
		f[0][j] = 0
		g[0][j] = 0
	}

	for i := 1; i < m; i++ {
		f[i][0] = inf
		g[i][0] = inf
		for j := 1; j <= n; j++ {
			f[i][j] = f[i][j-1]
			g[i][j] = g[i][j-1]
			trace[i][j] = i
			if d[i]%b[j] == 0 {
				x := d[i] / b[j]
				p := pos[x]
				if (f[i][j] > f[p][j-1]+1) || ((f[i][j] == f[p][j-1]+1) && (g[i][j] > g[p][j-1]+a[j])) {
					f[i][j] = f[p][j-1] + 1
					g[i][j] = g[p][j-1] + a[j]
					trace[i][j] = p
				}
			}
		}
	}

	res := f[m-1][n]
	if res < inf {
		out.WriteString(strconv.Itoa(res))
		out.WriteByte('\n')
		i := m - 1
		for j := n; j >= 1; j-- {
			p := trace[i][j]
			if p < i {
				out.WriteString(strconv.Itoa(j))
				out.WriteByte(' ')
				i = p
			}
		}
	} else {
		out.WriteString("-1\n")
	}
}


Polycarp found under the Christmas tree an array $$$a$$$ of $$$n$$$ elements and instructions for playing with it:   At first, choose index $$$i$$$ ($$$1 \leq i \leq n$$$) — starting position in the array. Put the chip at the index $$$i$$$ (on the value $$$a_i$$$).  While $$$i \leq n$$$, add $$$a_i$$$ to your score and move the chip $$$a_i$$$ positions to the right (i.e. replace $$$i$$$ with $$$i + a_i$$$).  If $$$i > n$$$, then Polycarp ends the game. For example, if $$$n = 5$$$ and $$$a = [7, 3, 1, 2, 3]$$$, then the following game options are possible:   Polycarp chooses $$$i = 1$$$. Game process: $$$i = 1 \overset{+7}{\longrightarrow} 8$$$. The score of the game is: $$$a_1 = 7$$$.  Polycarp chooses $$$i = 2$$$. Game process: $$$i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_2 + a_5 = 6$$$.  Polycarp chooses $$$i = 3$$$. Game process: $$$i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_3 + a_4 = 3$$$.  Polycarp chooses $$$i = 4$$$. Game process: $$$i = 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_4 = 2$$$.  Polycarp chooses $$$i = 5$$$. Game process: $$$i = 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_5 = 3$$$. Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output on a separate line one number — the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from $$$1$$$ to $$$n$$$ in such a way as to maximize his result.

NoteThe first test case is explained in the statement.In the second test case, the maximum score can be achieved by choosing $$$i = 1$$$.In the third test case, the maximum score can be achieved by choosing $$$i = 2$$$.In the fourth test case, the maximum score can be achieved by choosing $$$i = 1$$$.

package main

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

var (
	t      int
	input  io.Reader = bufio.NewReader(os.Stdin)
	output           = bufio.NewWriter(os.Stdout)
)

func solve() {
	var n int
	fmt.Fscan(input, &n)

	arr := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(input, &arr[i])
	}

	var ans int64
	d := make([]int64, n)
	for i := (n - 1); i >= 0; i-- {
		if (i + arr[i]) >= n {
			d[i] = int64(arr[i])
		} else {
			ff := i + arr[i]
			d[i] = int64(arr[i]) + int64(d[ff])
		}

		if d[i] > ans {
			ans = d[i]
		}
	}

	fmt.Fprintln(output, ans)
}

func main() {
	fmt.Fscan(input, &t)

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

	//

	defer output.Flush()
}

package main

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

var (
	t      int
	input  io.Reader = bufio.NewReader(os.Stdin)
	output           = bufio.NewWriter(os.Stdout)
)

func solve() {
	var n int
	fmt.Fscan(input, &n)

	arr := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(input, &arr[i])
	}

	var ans int64
	d := make([]int64, n)
	for i := (n - 1); i >= 0; i-- {
		if (i + arr[i]) >= n {
			d[i] = int64(arr[i])
		} else {
			ff := i + arr[i]
			d[i] = int64(arr[i]) + int64(d[ff])
		}

		if d[i] > ans {
			ans = d[i]
		}
	}

	fmt.Fprintln(output, ans)
}

func main() {
	fmt.Fscan(input, &t)

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

	defer output.Flush()
}

package main

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

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)

		arr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &arr[i])
		}

		var ans int64
		d := make([]int64, n)
		for i := (n - 1); i >= 0; i-- {
			if (i + arr[i]) >= n {
				d[i] = int64(arr[i])
			} else {
				ff := i + arr[i]
				d[i] = int64(arr[i]) + int64(d[ff])
			}

			if d[i] > ans {
				ans = d[i]
			}
		}

		fmt.Println(ans)
	}
}

package main

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

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)

		arr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &arr[i])
		}

		d := make([]int64, n)

		for i := (n - 1); i >= 0; i-- {
			if (i + arr[i]) >= n {
				d[i] = int64(arr[i])
			} else {
				ff := i + arr[i]
				d[i] = int64(arr[i]) + int64(d[ff])
			}
		}

		var ans int64
		for i := 0; i < n; i++ {
			if d[i] > ans {
				ans = d[i]
			}
		}

		fmt.Println(ans)
	}
}

package main

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

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)

		arr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &arr[i])
		}

		d := make([]int64, n)

		for i := (n - 1); i >= 0; i-- {
			if (i + arr[i]) >= n {
				d[i] = int64(arr[i])
			} else {
				ff := i + arr[i]
				d[i] = int64(arr[i]) + int64(d[ff])
			}
		}

		var anss int64
		for i := 0; i < n; i++ {
			if d[i] > anss {
				anss = d[i]
			}
		}

		fmt.Println(anss)
	}
}

package main

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

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
	t   int
	n   int
)

func main() {

	defer out.Flush()

	fmt.Fscan(in, &t)

	for ; t > 0; t-- {

		fmt.Fscan(in, &n)
		a := make([]int, n)

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

		fmt.Fprintln(out, solve(a, n))
		//fmt.Fprintln(out, solve2(a, max, maxP))

	}

}

func solve(a []int, n int) int64 {

	max := int64(0)

	/*for i := int64(0); i < n; i++ {

		index := i
		sum := int64(0)

		for index < n {

			sum += a[index]
			index += a[index]

		}

		if sum > max {
			max = sum
		}

	}*/

	arr := make([]int64, n)

	for i := n - 1; i >= 0; i-- {

		if a[i]+i >= n {
			arr[i] = int64(a[i])
		} else {
			next := i + a[i]
			arr[i] = int64(a[i]) + arr[next]
		}

	}

	for i := 0; i < n; i++ {
		if arr[i] > max {
			max = arr[i]
		}
	}

	return max

}

//取絕對值
func abs(n int) int {
	if n >= 0 {
		return n
	} else {
		return -n
	}
}

//印出數字陣列
func printArr(array []int) {

	for i := range array {
		fmt.Printf("%d ", array[i])
	}

	fmt.Println()

}

//取質數
func Prime(a int, b int) []int {
	result := make([]int, 0)

	switch a {
	case 0, 1:
		if b >= 3 {
			result = append(result, 2)
			result = append(result, 3)

			a = 5
		} else if b == 2 {
			result = append(result, 2)
			return result
		} else {
			return result
		}
	case 2:
		result = append(result, 2)

		if b == 2 {
			return result
		}

		result = append(result, 3)
		a = 5
	case 3:
		result = append(result, 3)
		a = 5
	default:
		if a%2 == 0 {
			a++
		}
	}

outer:
	for n := a; n <= b; n += 2 {
		m := n % 6

		if m != 1 && m != 5 {
			continue
		}

		nSqrt := int(math.Floor(math.Sqrt(float64(n))))

		if nSqrt >= a {
			for i := 5; i < a; i += 6 {
				if n%i == 0 || n%(i+2) == 0 { // n % i: 6n + 5 -> 6(n + 1) - 1 -> 6n - 1, n % (i + 2): 6n + 1
					continue outer
				}
			}

			for _, p := range result {
				if p > nSqrt {
					break
				}

				if n%p == 0 {
					continue outer
				}
			}
		} else {
			for i := 5; i <= nSqrt; i += 6 {
				if n%i == 0 || n%(i+2) == 0 { // n % i: 6n + 5 -> 6(n + 1) - 1 -> 6n - 1, n % (i + 2): 6n + 1
					continue outer
				}
			}
		}

		result = append(result, n)
	}

	return result
}

/*
func gain() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)

		arr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &arr[i])
		}

		d := make([]int64, n)

		for i := (n - 1); i >= 0; i-- {
			if (i + arr[i]) >= n {
				d[i] = int64(arr[i])
			} else {
				ff := i + arr[i]
				d[i] = int64(arr[i]) + int64(d[ff])
			}
		}

		var anss int64
		for i := 0; i < n; i++ {
			if d[i] > anss {
				anss = d[i]
			}
		}

		fmt.Println(anss)
	}
}
*/

package main

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

func Solve() {
	n := ri()
	dp := make([]int64, n+1)
	for i := 0; i < n; i++ {
		x := ri64()
		pos := min64(int64(n), int64(i)+x)
		dp[pos] = max64(dp[pos], dp[i]+x)
	}
	println(dp[n])
}

func main() {
	T := 0 // 如果是多组样例，请讲 T := 1 改为 T := 0
	in, out = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	if T == 0 {
		scan(&T)
	}
	for t := 0; t < T; t++ {
		Solve()
	}
	out.Flush()
}

var in *bufio.Reader
var out *bufio.Writer

// ri 将直接读入并返回一个 int
func ri() (x int) {
	scan(&x)
	return x
}

// ri64 将直接读入并返回一个 int64
func ri64() (x int64) {
	scan(&x)
	return x
}

//rs 将直接读入并返回一个 string
func rs() (s string) {
	scan(&s)
	return s
}

//scan 用法与 fmt.scan() 相似，可以传入多个变量的地址进行读入操作
func scan(a ...interface{}) { Fscan(in, a...) }

//print 用法与 fmt.print() 相似，可以传入多个变量进行输出。
//注意，这个函数不会换行，多个变量之间有空格
func print(a ...interface{}) { Fprint(out, a...) }

//println 用法与 fmt.println() 相似，可以传入多个变量进行输出。
//这个函数会换行，多个变量之间有空格
func println(a ...interface{}) { Fprintln(out, a...) }

//min 可以传入多个 int 变量，求出这些变量的最小值
func min(a ...int) int {
	ans := a[0]
	for i := 1; i < len(a); i++ {
		if a[i] < ans {
			ans = a[i]
		}
	}
	return ans
}

//min64 可以传入多个 int64 变量，求出这些变量的最小值
func min64(a ...int64) int64 {
	ans := a[0]
	for i := 1; i < len(a); i++ {
		if a[i] < ans {
			ans = a[i]
		}
	}
	return ans
}

//max 可以传入多个 int 变量，求出这些变量的最大值
func max(a ...int) int {
	ans := a[0]
	for i := 1; i < len(a); i++ {
		if a[i] > ans {
			ans = a[i]
		}
	}
	return ans
}

//max64 可以传入多个 int64 变量，求出这些变量的最大值
func max64(a ...int64) int64 {
	ans := a[0]
	for i := 1; i < len(a); i++ {
		if a[i] > ans {
			ans = a[i]
		}
	}
	return ans
}

//sum 可以传入多个 int 变量，求出这些变量的总和，并返回总和。
//你可以使用 ... 运算符打散数组，使得 sum 函数可以求出数组的和。
func sum(a ...int) int {
	ans := 0
	for _, x := range a {
		ans += x
	}
	return ans
}

//sum64 可以传入多个 int64 变量，求出这些变量的总和，并返回总和。
//你可以使用 ... 运算符打散数组，使得 sum 函数可以求出数组的和。
func sum64(a ...int64) int64 {
	ans := int64(0)
	for _, x := range a {
		ans += x
	}
	return ans
}

//reverse 用于翻转 int 切片，所有元素将会变成原切片的倒序
func reverse(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

//reverse64 用于翻转 int64 切片，所有元素将会变成原切片的倒序
func reverse64(a []int64) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

//lowerBound 类似于 C++ 中的 lower_bound。
//用于二分查找 int 切片中，第一个大于等于 k 的元素在切片中的位置。
//如果元素不存在，则返回切片的长度。
//注意，lowerBound 作用的 int 切片必须升序。
func lowerBound(a []int, k int) int {
	l, r, pos := 0, len(a)-1, len(a)
	for l <= r {
		mid := (l + r) >> 1
		if a[mid] < k {
			l = mid + 1
		} else {
			pos, r = mid, mid-1
		}
	}
	return pos
}

//lowerBound64 类似于 C++ 中的 lower_bound。
//用于二分查找 int64 切片中，第一个大于等于 k 的元素在切片中的位置。
//如果元素不存在，则返回切片的长度。
//注意，lowerBound 作用的 int64 切片必须升序。
func lowerBound64(a []int64, k int64) int {
	l, r, pos := 0, len(a)-1, len(a)
	for l <= r {
		mid := (l + r) >> 1
		if a[mid] < k {
			l = mid + 1
		} else {
			pos, r = mid, mid-1
		}
	}
	return pos
}

//upperBound 类似于 C++ 中的 upper_bound。
//用于二分查找 int 切片中，第一个大于 k 的元素在切片中的位置。
//如果元素不存在，则返回切片的长度。
//注意，upperBound 作用的 int 切片必须升序。
func upperBound(a []int, k int) int {
	l, r, pos := 0, len(a)-1, len(a)
	for l <= r {
		mid := (l + r) >> 1
		if a[mid] <= k {
			l = mid + 1
		} else {
			pos, r = mid, mid-1
		}
	}
	return pos
}

//upperBound64 类似于 C++ 中的 upper_bound。
//用于二分查找 int64 切片中，第一个大于 k 的元素在切片中的位置。
//如果元素不存在，则返回切片的长度。
//注意，upperBound 作用的 int64 切片必须升序。
func upperBound64(a []int64, k int64) int {
	l, r, pos := 0, len(a)-1, len(a)
	for l <= r {
		mid := (l + r) >> 1
		if a[mid] <= k {
			l = mid + 1
		} else {
			pos, r = mid, mid-1
		}
	}
	return pos
}

type Stack struct {
	s []int
}

func (st *Stack) top() int   { return st.s[len(st.s)-1] }
func (st *Stack) size() int  { return len(st.s) }
func (st *Stack) pop()       { st.s = st.s[:len(st.s)-1] }
func (st *Stack) push(x int) { st.s = append(st.s, x) }

type Queue struct {
	que chan int
}

func MakeQueue(size int) Queue {
	var q Queue
	q.que = make(chan int, size)
	return q
}

package main

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

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

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

		a := make([]int, n)
		for i := range a { fmt.Fscan(r, &a[i]) }

		dp := make([]int, n)
		for i := n-1; i >= 0; i-- {
			dp[i] = a[i]
			if i + a[i] < n { dp[i] += dp[i+a[i]] }
			if dp[i] > res { res = dp[i] }
		}

		fmt.Fprintln(w, res)
	}
}

package main

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

var (
	reader *bufio.Reader = bufio.NewReader(os.Stdin)
	writer *bufio.Writer = bufio.NewWriter(os.Stdout)
	debug                = fmt.Println
)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func IntArray(size int) []int {
	arr := make([]int, size)
	for i := 0; i < size; i++ {
		scanf("%d", &arr[i])
	}
	scanf("\n")
	return arr
}

func Max(args ...int) int {
	m := args[0]
	for i := range args {
		if args[i] > m {
			m = args[i]
		}
	}
	return m
}

func Min(args ...int) int {
	m := args[0]
	for i := range args {
		if args[i] < m {
			m = args[i]
		}
	}
	return m
}

func solve() {
	var n int
	scanf("%d\n", &n)

	arr := IntArray(n)

	dp := make([]int, n)
	dp[n-1] = arr[n-1]
	max := dp[n-1]

	for i := n - 2; i >= 0; i-- {
		if i+arr[i] < n {
			dp[i] = dp[i+arr[i]] + arr[i]
		} else {
			dp[i] = arr[i]
		}
		max = Max(max, dp[i])
	}

	printf("%d\n", max)
}

func main() {
	defer writer.Flush()

	var cases int

	scanf("%d\n", &cases)

	for c := 0; c < cases; c++ {
		solve()
	}
}

/*

 */

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t      int
	n      int64
)

func solve(n int64, a []int64) int64 {
	maxScore := int64(0)
	s := make([]int64, n)
	for i := n - 1; i >= 0; i-- {
		if i+a[i] > n-1 {
			s[i] = a[i]
		} else {
			s[i] = a[i] + s[i+a[i]]
		}
		if maxScore < s[i] {
			maxScore = s[i]
		}
	}
	return maxScore
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		a := make([]int64, n)
		for i := int64(0); i < n; i++ {
			fmt.Fscan(reader, &a[i])
		}
		fmt.Println(solve(n, a))
	}
}

package main

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

var bytes []byte

func nextByte() byte {
	b := bytes[0]
	bytes = bytes[1:]
	return b
}

func scanInt64() int64 {
	var negative bool
	var result int64

	b := nextByte()

	for ; b < '0' || b > '9'; b = nextByte() {
		if b == '-' {
			negative = true
		}
	}

	for ; '0' <= b && b <= '9'; b = nextByte() {
		result = (result << 3) + (result << 1) + int64(b-'0')
	}

	if negative {
		return -result
	} else {
		return result
	}
}

func scanInt() int {
	return int(scanInt64())
}

func ScanString() string {
	builder := strings.Builder{}

	for b := nextByte(); b != '\r'; b = nextByte() {
		if b != '\n' {
			builder.WriteByte(b)
		}
	}

	return builder.String()
}

func init() {
	f, err := os.Open("in.txt")

	if err == nil {
		defer f.Close()
	} else {
		f = os.Stdin
	}

	bytes, _ = ioutil.ReadAll(bufio.NewReader(f))
}

func main() {
	var a [200000]int64
	for t := scanInt(); t > 0; t-- {
		n, max := scanInt64(), int64(0)

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

		for i := n - 1; i >= 0; i-- {
			if i+a[i] < n {
				a[i] += a[i+a[i]]
			}

			if a[i] > max {
				max = a[i]
			}
		}

		fmt.Println(max)
	}
}

package main

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

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

func scan(a ...interface{}) (n int, err error)             { return fmt.Fscan(in, a...) }
func scanf(f string, a ...interface{}) (n int, err error)  { return fmt.Fscanf(in, f, a...) }
func printf(f string, a ...interface{}) (n int, err error) { return fmt.Fprintf(out, f, a...) }

//https://codeforces.com/problemset/problem/1472/C
// dp

func main() {
	defer out.Flush()

	var t, n int
	scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		scanf("%d\n", &n)
		a := make([]int, n)
		dp := make([]int, n)
		for j := 0; j < n; j++ {
			scan(&a[j])
			if j == n-1 {
				scanf("\n")
			}
		}
		ans := 0
		for j := n - 1; j >= 0; j-- {
			dp[j] = a[j]
			if j+a[j] < n {
				dp[j] += dp[j+a[j]]
			}
			ans = max(ans, dp[j])
		}
		printf("%d\n", ans)
	}
}

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

package main

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

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

func init() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1e6), 1e6)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func sbytes() []byte {
	scanner.Scan()
	return scanner.Bytes()
}

func main() {
	defer writer.Flush()
	for t := sint64(); t > 0; t-- {
		n := sint64()
		a := make([]int64, n)
		for i := range a {
			a[i] = sint64()
		}
		printf("%d\n", sol(a))
	}
}

func sol(a []int64) int64 {
	for i := int64(len(a) - 1); i > -1; i-- {
		if i+a[i] < int64(len(a)) {
			a[i] += a[i+a[i]]
		}
	}
	maxSoFar := a[0]
	for _, v := range a {
		if v > maxSoFar {
			maxSoFar = v
		}
	}
	return maxSoFar
}

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)

// var file, _ = os.Open("input")
// var reader *bufio.Reader = bufio.NewReader(file)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func main() {
	var t int
	scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		var n int
		scanf("%d\n", &n)
		fmt.Println(process(reader, int64(n)))
	}
}

func process(reader *bufio.Reader, n int64) int64 {
	a := make([]int64, n)
	var i int64
	for i = 0; i < n; i++ {
		if i != n-1 {
			scanf("%d", &a[i])
		} else {
			scanf("%d\n", &a[i])
		}
	}
	result := make([]int64, n)
	var maxResult int64
	for i = n - 1; i >= 0; i-- {
		if a[i]+i < n {
			result[i] = a[i] + result[i+a[i]]
		} else {
			result[i] = a[i]
		}
		if maxResult < result[i] {
			maxResult = result[i]
		}
	}
	return maxResult
}

package main

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

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

func scanf(f string, a ...interface{}) {
	fmt.Fscanf(reader, f, a...)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}

func solve() int {
	var n int
	scanf("%d\n", &n)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		if i+1 == n {
			scanf("%d\n", &a[i])
		} else {
			scanf("%d ", &a[i])
		}
	}

	dp := make([]int64, n)
	var ans int64

	for i := n - 1; i >= 0; i-- {
		dp[i] = int64(a[i])
		if (i + a[i]) < n {
			dp[i] += dp[i+a[i]]
		}
		if dp[i] > ans {
			ans = dp[i]
		}
	}

	printf("%d\n", ans)

	return 0
}

func main() {
	defer writer.Flush()
	tt := 1
	scanf("%d\n", &tt)
	for tt > 0 {
		solve()
		tt--
	}
}

package main

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

func main() {
	t := ReadInt()
	for i := 0; i < t; i++ {
		size := ReadInt()
		weights := ReadIntSliceln(size)
		fmt.Println(process(weights))
	}
}

func process(w []int) (ans int) {
	for i := len(w) - 1; i >= 0; i-- {
		if i+w[i] < len(w) {
			w[i] = w[i] + w[i+w[i]]
		}
		if w[i] > ans {
			ans = w[i]
		}
		//fmt.Println(w)
	}
	return ans
}

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

// ReadInt Read a single integer followed by a space
func ReadInt() (v int) {
	fmt.Fscan(reader, &v)
	return v
}

// ReadIntSliceln reads a line of integers into a slice.
func ReadIntSliceln(size int) []int {
	a := make([]int, size)
	for i := range a {
		fmt.Fscan(reader, &a[i])
	}
	//fmt.Scanf("\n")
	return a
}

package main

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

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
func main() {
    var t int
	fmt.Fscan(input, &t)
    for t > 0 {
        t--
        solve()
    }
    output.Flush()
}

func solve() {
    var n int
    fmt.Fscan(input, &n)
    a := make([]int, n)
    dp := make([]int64, n + 1) // max result of i
    ans := int64(0)
    for i := 0; i < len(a); i++ {
        fmt.Fscan(input, &a[i])
        if i + a[i] >= n {
            ans = max(ans, dp[i] + int64(a[i]))
            continue
        }
        if dp[i + a[i]] < dp[i] + int64(a[i]) {
            dp[i + a[i]] = dp[i] + int64(a[i])
        }
        ans = max(ans, dp[i + a[i]])
    }
    fmt.Fprintln(output, ans)
}

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

package main

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

func main() {
	sc := NewScanner()
	t := sc.NextInt()
	for i := 0; i < t; i++ {
		N := sc.NextInt()
		a := sc.NextInt64Array()
		fmt.Println(solve(N, a))
	}

}

func dfs(memo []int64, v int, a []int64) int64 {
	if v > len(memo) {
		return 0
	}
	if memo[v-1] >= 0 {
		return memo[v-1]
	}
	ret := dfs(memo, v+int(a[v-1]), a)
	memo[v-1] = ret + a[v-1]
	return memo[v-1]
}

func solve(N int, a []int64) int64 {
	memo := make([]int64, N)
	fillInt(memo, -1)
	mx := int64(0)
	for i := 1; i <= N; i++ {
		mx = max(mx, dfs(memo, i, a))
	}
	return mx
}
func max(a int64, b int64) int64 {
	if a < b {
		return b
	}
	return a
}

func fillInt(arr []int64, v int) {
	for i := 0; i < len(arr); i++ {
		arr[i] = int64(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) NextFloat() float64 {
	v, _ := strconv.ParseFloat(s.Next(), 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]int {
	s.pre()
	start := s.p
	mp := map[int]int{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v]++
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v]++

	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 (
	"bufio"
	. "fmt"
	"os"
	"strconv"
)

func main () {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t,n int
	Fscan(in, &t)
	for tt := 0; tt < t ; tt++ {
		Fscan(in, &n)
		p := make([]int, n)
		a := make([]int, n)
		for i := 0; i<n; i++ {
			Fscan(in, &p[i])
		}
		ans := 0
		for i := range p{
			now := count(p, a, i)
			if now > ans {
				ans = now
			}
		}
		out.WriteString(strconv.Itoa(ans))
		out.WriteString("\n")
	}
}

func count(p []int, a []int, i int) int {
	if a[i] > 0 {
		return a[i]
	}
	c := p[i]
	if i + p[i] < len(p){
		c += count(p, a, i + p[i])
	}
	a[i] = c
	return c

}

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		n := ReadInt()
		println(solve(ReadInts(n)))
	}
}

func solve(a []int) int {
	max := 0
	memo := make([]*int, len(a))
	for i := 0; i < len(a); i++ {
		max = Max(max, f(memo, i, a))
	}
	return max
}

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

func f(memo []*int, i int, a []int) int {
	if i >= len(memo) {
		return 0
	}
	if memo[i] != nil {
		return *memo[i]
	}
	ret := a[i] + f(memo, i+a[i], a)
	memo[i] = &ret
	return *memo[i]
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func print(a ...interface{})            { fmt.Fprint(_w, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(_w, f, a...) }
func println(a ...interface{})          { fmt.Fprintln(_w, a...) }
func printInts(a ...int)                { s := fmt.Sprint(a); println(s[1 : len(s)-1]) }
func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) (a []int64) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt64())
	}
	return
}

package main

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

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

	solve := func(Case int) {
		var n int
		Fscan(in, &n)
		a := make([]int64, n)
		for i := range a {
			Fscan(in, &a[i])
		}
ans := int64(0)
		dp := make([]int64, n)
		for i := len(a) - 1; i >= 0; i-- {
			v := a[i]
			if int64(i)+v >= int64(n) {
				dp[i] = v

			} else {
				dp[i] = v+dp[int64(i)+v]
			}
			ans = max(ans, dp[i])
		}

		Fprintln(out, ans)
	}

	var t int
	Fscan(in, &t)
	for Case := 1; Case <= t; Case++ {
		solve(Case)
	}

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}
}

func main() { run(os.Stdin, os.Stdout) }
func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

package main

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

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)

		arr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &arr[i])
		}

		d := make([]int64, n)

		for i := (n - 1); i >= 0; i-- {
			if (i + arr[i]) >= n {
				d[i] = int64(arr[i])
			} else {
				d[i] = int64(arr[i] + arr[i+arr[i]])
			}
		}

		var ans int64
		for i := 0; i < n; i++ {
			if d[i] > ans {
				ans = d[i]
			}
		}

		fmt.Println(ans)
	}
}

package main

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

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
	t   int
	n   int
)

func main() {

	defer out.Flush()

	fmt.Fscan(in, &t)

	for ; t > 0; t-- {

		fmt.Fscan(in, &n)
		a := make([]int, n)

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

		fmt.Fprintln(out, solve(a, n))
		//fmt.Fprintln(out, solve2(a, max, maxP))

	}

}

func solve(a []int, n int) int {

	max := 0
	maxIndex := 0

	for i := 0; i < n; i++ {

		if a[i] <= maxIndex {
			continue
		}

		maxIndex = a[i]

		index := i
		sum := 0

		for index < n {

			sum += a[index]
			index += a[index]

		}

		if sum > max {
			max = sum
		}

	}

	return max

}

//取絕對值
func abs(n int) int {
	if n >= 0 {
		return n
	} else {
		return -n
	}
}

//印出數字陣列
func printArr(array []int) {

	for i := range array {
		fmt.Printf("%d ", array[i])
	}

	fmt.Println()

}

//取質數
func Prime(a int, b int) []int {
	result := make([]int, 0)

	switch a {
	case 0, 1:
		if b >= 3 {
			result = append(result, 2)
			result = append(result, 3)

			a = 5
		} else if b == 2 {
			result = append(result, 2)
			return result
		} else {
			return result
		}
	case 2:
		result = append(result, 2)

		if b == 2 {
			return result
		}

		result = append(result, 3)
		a = 5
	case 3:
		result = append(result, 3)
		a = 5
	default:
		if a%2 == 0 {
			a++
		}
	}

outer:
	for n := a; n <= b; n += 2 {
		m := n % 6

		if m != 1 && m != 5 {
			continue
		}

		nSqrt := int(math.Floor(math.Sqrt(float64(n))))

		if nSqrt >= a {
			for i := 5; i < a; i += 6 {
				if n%i == 0 || n%(i+2) == 0 { // n % i: 6n + 5 -> 6(n + 1) - 1 -> 6n - 1, n % (i + 2): 6n + 1
					continue outer
				}
			}

			for _, p := range result {
				if p > nSqrt {
					break
				}

				if n%p == 0 {
					continue outer
				}
			}
		} else {
			for i := 5; i <= nSqrt; i += 6 {
				if n%i == 0 || n%(i+2) == 0 { // n % i: 6n + 5 -> 6(n + 1) - 1 -> 6n - 1, n % (i + 2): 6n + 1
					continue outer
				}
			}
		}

		result = append(result, n)
	}

	return result
}


Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.Implement a program that can, given two distinct words S and T of the same length n determine how many words W of length n + 1 are there with such property that you can transform W into both S, and T by deleting exactly one character. Words S and T consist of lowercase English letters. Word W also should consist of lowercase English letters.

The first line contains integer n (1 ≤ n ≤ 100 000) — the length of words S and T. The second line contains word S. The third line contains word T. Words S and T consist of lowercase English letters. It is guaranteed that S and T are distinct words.

Print a single integer — the number of distinct words W that can be transformed to S and T due to a typo.

NoteIn the first sample test the two given words could be obtained only from word "treading" (the deleted letters are marked in bold).In the second sample test the two given words couldn't be obtained from the same word by removing one letter.In the third sample test the two given words could be obtained from either word "tory" or word "troy".

package main

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

// github.com/EndlessCheng/codeforces-go
func CF533E(in io.Reader, out io.Writer) {
	var n, ans int
	var s, t string
	Fscan(bufio.NewReader(in), &n, &s, &t)
	for i := range s {
		if s[i] != t[i] {
			s, t = s[i:], t[i:]
			break
		}
	}
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] != t[i] {
			s, t = s[:i+1], t[:i+1]
			break
		}
	}
	if s[1:] == t[:len(t)-1] {
		ans++
	}
	if t[1:] == s[:len(s)-1] {
		ans++
	}
	Fprint(out, ans)
}

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