You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.Let's number the rows with integers from 1 to n from top to bottom and the columns with integers from 1 to m from left to right. Let's denote a cell on the intersection of the r-th row and the c-th column as (r, c). You are staying in the cell (r1, c1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (r2, c2) since the exit to the next level is there. Can you do this?

The first line contains two integers, n and m (1 ≤ n, m ≤ 500) — the number of rows and columns in the cave description. Each of the next n lines describes the initial state of the level of the cave, each line consists of m characters "." (that is, intact ice) and "X" (cracked ice). The next line contains two integers, r1 and c1 (1 ≤ r1 ≤ n, 1 ≤ c1 ≤ m) — your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (r1, c1), that is, the ice on the starting cell is initially cracked. The next line contains two integers r2 and c2 (1 ≤ r2 ≤ n, 1 ≤ c2 ≤ m) — the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one.

If you can reach the destination, print 'YES', otherwise print 'NO'.

NoteIn the first sample test one possible path is:After the first visit of cell (2, 2) the ice on it cracks and when you step there for the second time, your character falls through the ice as intended.

package main

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

var scanner *bufio.Scanner
var writer *bufio.Writer

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

var (
  dr = []int{ -1, 0, 1, 0 }
  dc = []int{ 0, 1, 0, -1 }
  n, m, rBegin, cBegin, rEnd, cEnd int
  grid [][]byte
)

func solve() bool {
  used := make([][]bool, n)
  for r := range used {
    used[r] = make([]bool, m)
    for c, char := range grid[r] {
      if char == 'X' {
        used[r][c] = true
      }
    }
  }
  queue := [][]int{ []int{ rBegin, cBegin } }
  tail := 0
  for tail != len(queue) {
    r, c := queue[tail][0], queue[tail][1]
    tail++
    for i := 0; i < 4; i++ {
      R, C := r+dr[i], c+dc[i]
      if R >= 0 && R < n && C >= 0 && C < m && !used[R][C] {
        if R == rEnd && C == cEnd {
          return true
        }
        used[R][C] = true
        queue = append(queue, []int{ R, C })
      }
    }
  }
  return false
}

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

  n, m = getI(), getI()
  grid = make([][]byte, n)
  for r := range grid {
    grid[r] = []byte(getS())
  }
  rBegin, cBegin = getI()-1, getI()-1
  rEnd, cEnd = getI()-1, getI()-1
  result := "NO"
  if grid[rEnd][cEnd] == 'X' {
    grid[rEnd][cEnd] = '.'
    if solve() {
      result = "YES"
    }
  } else {
    for i := 0; i < 4; i++ {
      r, c := rEnd+dr[i], cEnd+dc[i]
      if r >= 0 && r < n && c >= 0 && c < m && grid[r][c] == '.' {
        grid[r][c] = 'X'
        if solve() {
          result = "YES"
        }
        grid[r][c] = '.'
      }
    }
  }
  writer.WriteString(fmt.Sprintf("%s\n", result))
}

package main

import "fmt"
import "log"

func get(b [][]byte, r int, c int) byte {
	if r < 0 || r >= len(b) || c < 0 || c >= len(b[r]) {
	  //fmt.Printf("%v %v\n", r, c)
		return '-'
	}
	//fmt.Printf("%v\n", b[r][c])
	return b[r][c]
}

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

// Get neighbour stat
func get_nb_stat(b [][]byte, r int, c int) map[byte]int {
	m := make(map[byte]int)
	m[get(b, r-1, c)]++
	m[get(b, r+1, c)]++
	m[get(b, r, c-1)]++
	m[get(b, r, c+1)]++
	return m
}

func print_board(b [][]byte) {
	for i := 0; i < len(b); i++ {
		fmt.Printf("%s\n", string(b[i]))
	}
}

func visit(b [][]byte, r int, c int) {
	if get(b, r, c) != '.' {
		return
	}
	b[r][c] = '*'
	visit(b, r-1, c)
	visit(b, r+1, c)
	visit(b, r, c-1)
	visit(b, r, c+1)
}

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
  b := make([][]byte, n)
	for i := 0; i < n; i++ {
		var s string
		fmt.Scanln(&s)
		if len(s) != m {
			log.Fatalf("Wrong len: %d\n", len(s))
		}
		b[i] = []byte(s)
	}
	var r1, c1, r2, c2 int
	fmt.Scanf("%d %d\n", &r1, &c1);
	r1--
	c1--
	fmt.Scanf("%d %d\n", &r2, &c2);
	r2--
	c2--

  if (abs(r1-r2)+abs(c1-c2)) == 1 {
		// End and start are neighbours
		if b[r2][c2] == '.' && get_nb_stat(b, r2, c2)['.'] == 0 {
			fmt.Printf("NO\n")
			return
		}
		fmt.Printf("YES\n")
		return
  }

	visit(b, r1-1, c1)
	visit(b, r1+1, c1)
	visit(b, r1, c1-1)
	visit(b, r1, c1+1)

  //print_board(b)

	nb1 := get_nb_stat(b, r1, c1)
	nb2 := get_nb_stat(b, r2, c2)

	if nb1['*'] == 0 {
		fmt.Printf("NO\n")
		return
	}

	if b[r2][c2] == '.' {
		// The final point could not be reached from the starting point.
		fmt.Printf("NO\n")
		return
	}
	if b[r2][c2] == '*' && !(nb2['*'] >= 2 || (nb2['*'] == 1 && nb2['.'] > 0)) {
		// If the final point is reachable and not cracked ice, then we must be
		// able to step out and step back once we reach it.  For that, it must
		// either have two or more reachable neighbours or one reachable neighbour
		// and non-zero non-cracked-ice neighbours.
		fmt.Printf("NO\n")
		return
	}
	if b[r2][c2] == 'X' && nb2['*'] == 0 {
		// If the final point is cracked ice, it must have a reachable neighbour.
		fmt.Printf("NO\n")
		return
	}

	fmt.Printf("YES\n")

}

package main

import "fmt"

var isCracked [][] bool
var visited [][] bool
var n, m, r1, c1, r2, c2 int

func main() {
	fmt.Scan(&n, &m)

	isCracked = make([][]bool, n)
	for i := 0; i < n; i++ {
		isCracked[i] = make([]bool, m)
	}

	visited = make([][] bool, n)
	for i := 0; i < n; i ++ {
		visited[i] = make([]bool, m)
	}

	for i := 0; i < n; i++ {
		var str string
		fmt.Scan(&str)
		for j := 0; j < m; j++ {
			isCracked[i][j] = str[j] == 'X'
		}
	}
	fmt.Scan(&r1, &c1, &r2, &c2);
	r1--
	c1--
	r2--
	c2--
	isCracked[r1][c1] = false

	if dfs(r1, c1) {
		fmt.Print("YES")
	} else {
		fmt.Print("NO")
	}
}

func hasGoodNeighbor(r, c int) bool {
	neighborCracked := true

	if r-1 >= 0 && !isCracked[r-1][c] {
		neighborCracked = false
	}

	if r+1 < n && !isCracked[r+1][c] {
		neighborCracked = false
	}

	if c-1 >= 0 && !isCracked[r][c-1] {
		neighborCracked = false
	}

	if c+1 < m && !isCracked[r][c+1] {
		neighborCracked = false
	}

	return !neighborCracked
}

func dfs(r, c int) bool {
	if r == r2 && c == c2 {
		if isCracked[r][c] {
			return true
		}
		return hasGoodNeighbor(r, c)
	}

	if r < 0 || r >= n || c < 0 || c >= m || isCracked[r][c] || visited[r][c] {
		return false
	}

	isCracked[r][c] = true

	result := dfs(r-1, c) || dfs(r, c+1) || dfs(r, c-1) || dfs(r+1, c)

	if !result {
		isCracked[r][c] = false
		visited[r][c] = true
	}
	return result
}

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/540/C

package main

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

type Cell struct {
	R int
	C int
}

func Solve(n int, m int, cave [][]string, start Cell, end Cell) string {
	dx := []int{0, 0, -1, 1}
	dy := []int{-1, 1, 0, 0}
	queue := []Cell{start}
	cave[start.R-1][start.C-1] = "."
	for len(queue) > 0 {
		node := queue[len(queue)-1]
		queue = queue[:len(queue)-1]
		if node == end && cave[node.R-1][node.C-1] == "X" {
			return "YES"
		}
		if cave[node.R-1][node.C-1] == "." {
			cave[node.R-1][node.C-1] = "X"
		} else {
			continue
		}
		for i := 0; i < 4; i++ {
			x, y := node.R+dx[i], node.C+dy[i]
			if 1 <= x && x <= n && 1 <= y && y <= m {
				if !(cave[x-1][y-1] == "X" && Cell{x, y} != end) {
					queue = append(queue, Cell{x, y})
				}
			}
		}
	}
	return "NO"
}

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

	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	cave := make([][]string, n)
	for i := 0; i < n; i++ {
		cave[i] = make([]string, m)
		var s string
		fmt.Fscanf(reader, "%s\n", &s)
		for j, elem := range s {
			cave[i][j] = string(elem)
		}
	}
	var start, end Cell
	fmt.Fscanf(reader, "%d %d\n%d %d\n", &start.R, &start.C, &end.R, &end.C)

	fmt.Fprintf(writer, "%s\n", Solve(n, m, cave, start, end))
}

package main

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

var scanner *bufio.Scanner
var writer *bufio.Writer

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

var (
  dr = []int{ -1, 0, 1, 0 }
  dc = []int{ 0, 1, 0, -1 }
  n, m, rBegin, cBegin, rEnd, cEnd int
  grid [][]byte
)

func solve() bool {
  used := make([][]bool, n)
  for r := range used {
    used[r] = make([]bool, m)
    for c, char := range grid[r] {
      if char == 'X' {
        used[r][c] = true
      }
    }
  }
  used[rBegin][cBegin] = true
  queue := [][]int{ []int{ rBegin, cBegin } }
  tail := 0
  for tail != len(queue) {
    r, c := queue[tail][0], queue[tail][1]
    tail++
    for i := 0; i < 4; i++ {
      R, C := r+dr[i], c+dc[i]
      if R >= 0 && R < n && C >= 0 && C < m && !used[R][C] {
        if R == rEnd && C == cEnd {
          return true
        }
        used[R][C] = true
        queue = append(queue, []int{ R, C })
      }
    }
  }
  return false
}

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

  n, m = getI(), getI()
  grid = make([][]byte, n)
  for r := range grid {
    grid[r] = []byte(getS())
  }
  rBegin, cBegin = getI()-1, getI()-1
  rEnd, cEnd = getI()-1, getI()-1
  result := "NO"
  if rBegin == rEnd && cBegin == cEnd {
    result = "YES"
  }
  if grid[rEnd][cEnd] == 'X' {
    grid[rEnd][cEnd] = '.'
    if solve() {
      result = "YES"
    }
  } else {
    for i := 0; i < 4; i++ {
      r, c := rEnd+dr[i], cEnd+dc[i]
      if r >= 0 && r < n && c >= 0 && c < m && grid[r][c] == '.' {
        grid[r][c] = 'X'
        if solve() {
          result = "YES"
        }
        grid[r][c] = '.'
      }
    }
  }
  writer.WriteString(fmt.Sprintf("%s\n", result))
}

package main

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

var scanner *bufio.Scanner
var writer *bufio.Writer

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

var (
  dr = []int{ -1, 0, 1, 0 }
  dc = []int{ 0, 1, 0, -1 }
  n, m, rBegin, cBegin, rEnd, cEnd int
  grid [][]byte
)

func solve() bool {
  used := make([][]bool, n)
  for r := range used {
    used[r] = make([]bool, m)
    for c, char := range grid[r] {
      if char == 'X' {
        used[r][c] = true
      }
    }
  }
  used[rBegin][cBegin] = true
  queue := [][]int{ []int{ rBegin, cBegin } }
  tail := 0
  for tail != len(queue) {
    r, c := queue[tail][0], queue[tail][1]
    tail++
    for i := 0; i < 4; i++ {
      R, C := r+dr[i], c+dc[i]
      if R >= 0 && R < n && C >= 0 && C < m && !used[R][C] {
        if R == rEnd && C == cEnd {
          return true
        }
        used[R][C] = true
        queue = append(queue, []int{ R, C })
      }
    }
  }
  return false
}

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

  n, m = getI(), getI()
  grid = make([][]byte, n)
  for r := range grid {
    grid[r] = []byte(getS())
  }
  rBegin, cBegin = getI()-1, getI()-1
  rEnd, cEnd = getI()-1, getI()-1
  result := "NO"
  if grid[rEnd][cEnd] == 'X' {
    grid[rEnd][cEnd] = '.'
    if solve() {
      result = "YES"
    }
  } else {
    for i := 0; i < 4; i++ {
      r, c := rEnd+dr[i], cEnd+dc[i]
      if r >= 0 && r < n && c >= 0 && c < m && grid[r][c] == '.' {
        grid[r][c] = 'X'
        if solve() {
          result = "YES"
        }
        grid[r][c] = '.'
      }
    }
  }
  writer.WriteString(fmt.Sprintf("%s\n", result))
}

package main

import "fmt"
import "log"

func get(b [][]byte, r int, c int) byte {
	if r < 0 || r >= len(b) || c < 0 || c >= len(b[r]) {
	  //fmt.Printf("%v %v\n", r, c)
		return '-'
	}
	//fmt.Printf("%v\n", b[r][c])
	return b[r][c]
}

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

// Get neighbour stat
func get_nb_stat(b [][]byte, r int, c int) map[byte]int {
	m := make(map[byte]int)
	m[get(b, r-1, c)]++
	m[get(b, r+1, c)]++
	m[get(b, r, c-1)]++
	m[get(b, r, c+1)]++
	return m
}

func print_board(b [][]byte) {
	for i := 0; i < len(b); i++ {
		fmt.Printf("%s\n", string(b[i]))
	}
}

func visit(b [][]byte, r int, c int) {
	if get(b, r, c) != '.' {
		return
	}
	b[r][c] = '*'
	visit(b, r-1, c)
	visit(b, r+1, c)
	visit(b, r, c-1)
	visit(b, r, c+1)
}

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
  b := make([][]byte, n)
	for i := 0; i < n; i++ {
		var s string
		fmt.Scanln(&s)
		if len(s) != m {
			log.Fatalf("Wrong len: %d\n", len(s))
		}
		b[i] = []byte(s)
	}
	var r1, c1, r2, c2 int
	fmt.Scanf("%d %d\n", &r1, &c1);
	r1--
	c1--
	fmt.Scanf("%d %d\n", &r2, &c2);
	r2--
	c2--

	visit(b, r1-1, c1)
	visit(b, r1+1, c1)
	visit(b, r1, c1-1)
	visit(b, r1, c1+1)

  //print_board(b)

	nb1 := get_nb_stat(b, r1, c1)
	if nb1['*'] == 0 && (abs(r1-r2)+abs(c1-c2)) != 1 {
		fmt.Printf("NO\n")
		return
	}

	nb2 := get_nb_stat(b, r2, c2)
	if b[r2][c2] == '.' {
		// The final point could not be reached from the starting point.
		fmt.Printf("NO\n")
		return
	}
	if b[r2][c2] == '*' && !(nb2['*'] >= 2 || (nb2['*'] == 1 && nb2['.'] > 0)) {
		// If the final point is reachable and not cracked ice, then we must be
		// able to step out and step back once we reach it.  For that, it must
		// either have two or more reachable neighbours or one reachable neighbour
		// and non-zero non-cracked-ice neighbours.
		fmt.Printf("NO\n")
		return
	}
	if b[r2][c2] == 'X' && nb2['*'] == 0 && (abs(r1-r2)+abs(c1-c2)) != 1 {
		// If the final point is cracked ice, it must have a reachable neighbour.
		fmt.Printf("NO\n")
		return
	}

	fmt.Printf("YES\n")

}

package main

import "fmt"

func get(b [][]byte, r int, c int) byte {
	if r < 0 || r >= len(b) || c < 0 || c >= len(b[r]) {
		return '-'
	}
	return b[r][c]
}

// Get neighbour stat
func get_nb_stat(b [][]byte, r int, c int) map[byte]int {
	m := make(map[byte]int)
	m[get(b, r-1, c)]++
	m[get(b, r+1, c)]++
	m[get(b, r, c-1)]++
	m[get(b, r, c+1)]++
	return m
}

func visit(b [][]byte, r int, c int) {
	if get(b, r, c) != '.' {
		return
	}
	b[r][c] = '*'
	visit(b, r-1, c)
	visit(b, r+1, c)
	visit(b, r, c-1)
	visit(b, r, c+1)
}

func main() {
	var n, m int
	fmt.Scanf("%d %d", &n, &m)
  b := make([][]byte, n)
	for i := 0; i < n; i++ {
		var s string
		fmt.Scanln(&s)
		b[i] = []byte(s)
	}
	var r1, c1, r2, c2 int
	fmt.Scanf("&d &d", &r1, &c1);
	fmt.Scanf("&d &d", &r2, &c2);

	visit(b, r1-1, c1)
	visit(b, r1+1, c1)
	visit(b, r1, c1-1)
	visit(b, r1, c1+1)

	nb1 := get_nb_stat(b, r1, c1)
	if nb1['*'] == 0 {
		fmt.Printf("NO\n")
		return
	}

	nb2 := get_nb_stat(b, r2, c2)
	if b[r2][c2] == '.' {
		// The final point could not be reached from the starting point.
		fmt.Printf("NO\n")
		return
	}
	if b[r2][c2] == '*' && !(nb2['*'] >= 2 || (nb2['*'] == 1 && nb2['.'] > 0)) {
		// If the final point is reachable and not cracked ice, then we must be
		// able to step out and step back once we reach it.  For that, it must
		// either have two or more reachable neighbours or one reachable neighbour
		// and non-zero non-cracked-ice neighbours.
		fmt.Printf("NO\n")
		return
	}
	if b[r2][c2] == 'X' && nb2['*'] == 0 {
		// If the final point is cracked ice, it must have a reachable neighbour.
		fmt.Printf("NO\n")
		return
	}

	fmt.Printf("YES\n")

  // fmt.Printf("%#v\n", b)
}

package main

import "fmt"
import "log"

func get(b [][]byte, r int, c int) byte {
	if r < 0 || r >= len(b) || c < 0 || c >= len(b[r]) {
	  //fmt.Printf("%v %v\n", r, c)
		return '-'
	}
	//fmt.Printf("%v\n", b[r][c])
	return b[r][c]
}

// Get neighbour stat
func get_nb_stat(b [][]byte, r int, c int) map[byte]int {
	m := make(map[byte]int)
	m[get(b, r-1, c)]++
	m[get(b, r+1, c)]++
	m[get(b, r, c-1)]++
	m[get(b, r, c+1)]++
	return m
}

func print_board(b [][]byte) {
	for i := 0; i < len(b); i++ {
		fmt.Printf("%s\n", string(b[i]))
	}
}

func visit(b [][]byte, r int, c int) {
	if get(b, r, c) != '.' {
		return
	}
	b[r][c] = '*'
	visit(b, r-1, c)
	visit(b, r+1, c)
	visit(b, r, c-1)
	visit(b, r, c+1)
}

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
  b := make([][]byte, n)
	for i := 0; i < n; i++ {
		var s string
		fmt.Scanln(&s)
		if len(s) != m {
			log.Fatalf("Wrong len: %d\n", len(s))
		}
		b[i] = []byte(s)
	}
	var r1, c1, r2, c2 int
	fmt.Scanf("%d %d\n", &r1, &c1);
	r1--
	c1--
	fmt.Scanf("%d %d\n", &r2, &c2);
	r2--
	c2--

	visit(b, r1-1, c1)
	visit(b, r1+1, c1)
	visit(b, r1, c1-1)
	visit(b, r1, c1+1)

  //print_board(b)

	nb1 := get_nb_stat(b, r1, c1)
	if nb1['*'] == 0 {
		fmt.Printf("NO\n")
		return
	}

	nb2 := get_nb_stat(b, r2, c2)
	if b[r2][c2] == '.' {
		// The final point could not be reached from the starting point.
		fmt.Printf("NO\n")
		return
	}
	if b[r2][c2] == '*' && !(nb2['*'] >= 2 || (nb2['*'] == 1 && nb2['.'] > 0)) {
		// If the final point is reachable and not cracked ice, then we must be
		// able to step out and step back once we reach it.  For that, it must
		// either have two or more reachable neighbours or one reachable neighbour
		// and non-zero non-cracked-ice neighbours.
		fmt.Printf("NO\n")
		return
	}
	if b[r2][c2] == 'X' && nb2['*'] == 0 {
		// If the final point is cracked ice, it must have a reachable neighbour.
		fmt.Printf("NO\n")
		return
	}

	fmt.Printf("YES\n")

}


Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last.

The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n). Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.

Print the total number of moves Alice and Bob will make.

NoteIn the first example the tree looks like this:  The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this:  The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4

// ProblemURL : https://codeforces.com/problemset/problem/813/C
// ---------------------------------------------
package main

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

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func diff(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}
func larger(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func smaller(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func largest(a, b, c int) (lgst int) {
	if a > b {
		lgst = a
	} else {
		lgst = b
	}
	if c > lgst {
		lgst = c
	}
	return
}
func smallest(a, b, c int) (slst int) {
	if a < b {
		slst = a
	} else {
		slst = b
	}
	if c < slst {
		slst = c
	}
	return
}
func intsMax(a []int) (val int) {
	if len(a) == 0 {
		panic("func intsMax: zero length slice")
	}
	val = a[0]
	for _, aa := range a {
		if aa > val {
			val = aa
		}
	}
	return
}
func intsMaxIdx(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func intsMaxIdx: zero length slice")
	}
	val = a[0]
	for i, aa := range a {
		if aa > val {
			idx, val = i, aa
		}
	}
	return
}
func intsMin(a []int) (val int) {
	if len(a) == 0 {
		panic("func intsMin: zero length slice")
	}
	val = a[0]
	for _, aa := range a {
		if aa < val {
			val = aa
		}
	}
	return
}
func intsMinIdx(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func intsMinIdx: zero length slice")
	}
	val = a[0]
	for i, aa := range a {
		if aa < val {
			idx, val = i, aa
		}
	}
	return
}
func intsSum(a []int) int {
	res := 0
	for _, v := range a {
		res += v
	}
	return res
}
func intsAve(s []int) float64 {
	return float64(intsSum(s)) / float64(len(s))
}
func intsAdd(a *[]int, x int)    { *a = append(*a, x) }
func intsDelete(a *[]int, i int) { *a = append((*a)[:i], (*a)[i+1:]...) }
func intsJoin(a, b []int) []int  { return append(a, b...) }
func intsClear(a []int) []int    { return a[:0] }
func intsCopy(a []int) []int     { return append([]int(nil), a...) }
func intsCopySortAsc(a []int) []int {
	s := intsCopy(a)
	sort.Ints(s)
	return s
}
func intsCopySortDesc(a []int) []int {
	s := intsCopy(a)
	sort.Sort(sort.Reverse(sort.IntSlice(s)))
	return s
}
func intsReverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}
func intsFill(a []int, val int) {
	for i := 0; i < len(a); i++ {
		a[i] = val
	}
}
func intsPeekBack(a []int) int {
	if len(a) == 0 {
		panic("func peekBack: zero length slice")
	}
	return a[len(a)-1]
}
func intsPeekFront(a []int) int {
	if len(a) == 0 {
		panic("func peekFront: zero length slice")
	}
	return a[0]
}
func intsPopBack(a *[]int) int {
	if len(*a) == 0 {
		panic("func popBack: zero length slice")
	}
	t := (*a)[len(*a)-1]
	*a = (*a)[:len(*a)-1]
	return t
}
func intsPopFront(a *[]int) int {
	if len(*a) == 0 {
		panic("func popFront: zero length slice")
	}
	h := (*a)[0]
	*a = (*a)[1:]
	return h
}
func intsPushBack(a *[]int, x int) { *a = append(*a, x) }
func intsPushFront(a *[]int, x int) {
	*a = append(*a, 0)
	copy((*a)[1:], (*a)[0:])
	(*a)[0] = x
}
func intsAppendSentinelHead(a *[]int, sentinel int) { intsPushFront(a, sentinel) }
func intsAppendSentinelTail(a *[]int, sentinel int) { intsPushBack(a, sentinel) }
func intsAppendSentinels(a *[]int, sentinel int) {
	intsPushFront(a, sentinel)
	intsPushBack(a, sentinel)
}
func intsIota(n int) []int {
	as := make([]int, n)
	for i := range as {
		as[i] = i
	}
	return as
}
func intsHaveDuplicateElm(a []int) bool {
	m := make(map[int]bool, len(a))
	for _, aa := range a {
		if _, exists := m[aa]; exists {
			return true
		} else {
			m[aa] = true
		}
	}
	return false
}
func isEven(n int) bool     { return n&1 == 0 }
func isOdd(n int) bool      { return n&1 == 1 }
func floor(x float64) int   { return int(x) }
func ceil(x float64) int    { return int(math.Ceil(x)) }
func ceilDiv(x, y int) int  { return ((x) + (y) - 1) / (y) }
func floorDiv(x, y int) int { return (x) / (y) }
func pow(x, y int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for ; y != 0; y >>= 1 {
		if y&1 == 1 {
			z *= x
		}
		x *= x
	}
	return z
}
func fact(x int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact *= i
	}
	return fact
}
func sigmaK(n int) int  { return n * (n + 1) / 2 }
func sigmaKK(n int) int { return (n * (n + 1) / 2) * (2*n + 1) / 3 }
func euclideanDistance(a, b point) float64 {
	s := diff(a.x, b.x)
	s *= s
	t := diff(a.y, b.y)
	t *= t
	return math.Sqrt(float64(s) + float64(t))
}
func manhattanDistance(a, b point) int {
	s := diff(a.x, b.x)
	t := diff(a.y, b.y)
	return s + t
}
func swap(a, b *int) { *a, *b = *b, *a }
func chmax(a *int, b int) bool {
	if *a < b {
		*a = b
		return true
	}
	return false
}
func chmin(a *int, b int) bool {
	if *a > b {
		*a = b
		return true
	}
	return false
}
func cumsumBuild(a []int) []int {
	b := append([]int{0}, a...)
	for i := 1; i < len(b); i++ {
		b[i] += b[i-1]
	}
	return b
}
func bytesReverse(a []byte) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}
func strIsUpperAlphabet(s string) bool {
	if len(s) != 1 {
		panic("wrong arg")
	}
	t := s[0]
	return 'A' <= t && t <= 'Z'
}
func strIsLowerAlphabet(s string) bool {
	if len(s) != 1 {
		panic("wrong arg")
	}
	t := s[0]
	return 'a' <= t && t <= 'z'
}
func strToUpperCase(s string) string { return strings.ToUpper(s) }
func strToLowerCase(s string) string { return strings.ToLower(s) }
func strAlphaUpperCaseToInt(s string) int {
	if len(s) != 1 {
		panic("wrong arg")
	}
	t := s[0]
	if !('A' <= t && t <= 'Z') {
		panic("arg must be upper case alphabet")
	}
	return int(t - 'A')
}
func strAlphaLowerCaseToInt(s string) int {
	if len(s) != 1 {
		panic("wrong arg")
	}
	t := s[0]
	if !('a' <= t && t <= 'z') {
		panic("arg must be lower case alphabet")
	}
	return int(t - 'a')
}
func strCountAlphabetsLower(alphaLower string) (ctAlphas [26]int) {
	ct := [26]int{}
	for _, ss := range alphaLower {
		if !('a' <= ss && ss <= 'z') {
			panic("func strCountAlphabetsLower: argument must be lowercase string")
		}
		ct[ss-'a']++
	}
	return ct
}
func strCountAlphabetsUpper(alphaUpper string) (ctAlphas [26]int) {
	ct := [26]int{}
	for _, ss := range alphaUpper {
		if !('A' <= ss && ss <= 'Z') {
			panic("func strCountAlphabetsUpper: argument must be uppercase string")
		}
		ct[ss-'A']++
	}
	return ct
}
func strReverse(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}
func runeIsUpperAlphabet(r rune) bool { return 'A' <= r && r <= 'Z' }
func runeIsLowerAlphabet(r rune) bool { return 'a' <= r && r <= 'z' }
func runesReverse(a []rune) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}
func strToInt(s string) int {
	i, err := strconv.Atoi(s)
	if err != nil {
		panic(err)
	}
	return i
}
func intToStr(i int) string     { return strconv.Itoa(i) }
func CalcMod(a, mod int) int    { return (a%mod + mod) % mod }
func ModSum(a *int, b, mod int) { *a = (((*a) % mod) + mod + (b % mod)) % mod }
func ModMul(a *int, b, mod int) { *a = (((*a) % mod) * (b % mod)) % mod }
func ModPow(x, y, mod int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for ; y != 0; y >>= 1 {
		if y&1 == 1 {
			z = (z * x) % mod
		}
		x = (x * x) % mod
	}
	return z
}
func ModFact(x, mod int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact = fact * i % mod
	}
	return fact
}
func ModInv(x, mod int) int { return ModPow(x, mod-2, mod) }
func initMatrixBool(parentSize, childSize int, initialValue bool) *[][]bool {
	res := make([][]bool, parentSize)
	for i := range res {
		res[i] = make([]bool, childSize)
		for j := range res[i] {
			res[i][j] = initialValue
		}
	}
	return &res
}
func initMatrixInt(parentSize, childSize int, initialValue int) *[][]int {
	res := make([][]int, parentSize)
	for i := range res {
		res[i] = make([]int, childSize)
		for j := range res[i] {
			res[i][j] = initialValue
		}
	}
	return &res
}

var (
	sc = bufio.NewScanner(os.Stdin)
	bw = bufio.NewWriterSize(os.Stdout, bwBufSize)
)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1e7), 1e7)
}
func ru() (n int) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}
func ri() (n int) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	b := sc.Bytes()
	neg := false
	if b[0] == 45 {
		neg = true
		b = b[1:]
	}
	for _, v := range b {
		n = n*10 + int(v-48)
	}
	if neg {
		n = -n
	}
	return
}
func ri64() (n int64) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	b := sc.Bytes()
	neg := false
	if b[0] == 45 {
		neg = true
		b = b[1:]
	}
	for _, v := range b {
		n = n*10 + int64(v-48)
	}
	if neg {
		n = -n
	}
	return
}
func rf64() float64 {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	f, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return f
}
func rs() string {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return sc.Text()
}
func rb() []byte {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return sc.Bytes()
}
func rr() []rune {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return []rune(sc.Text())
}
func ris(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = ri()
	}
	return s
}
func risZeroBased(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = ri() - 1
	}
	return s
}
func ri64s(n int) []int64 {
	s := make([]int64, n)
	for i := range s {
		s[i] = ri64()
	}
	return s
}
func riis(n int) ([]int, []int) {
	s := make([]int, n)
	t := make([]int, n)
	for i := range s {
		s[i] = ri()
		t[i] = ri()
	}
	return s, t
}
func rss(n int) []string {
	s := make([]string, n)
	for i := range s {
		s[i] = rs()
	}
	return s
}
func pf(format string, a ...interface{}) {
	if _, err := fmt.Fprintf(bw, format, a...); err != nil {
		panic(err)
	}
}
func pln(a ...interface{}) {
	if _, err := fmt.Fprintln(bw, a...); err != nil {
		panic(err)
	}
}
func pints(a []int) {
	for _, v := range a {
		fmt.Fprintln(bw, v)
	}
}
func pintsol(a []int) {
	s := fmt.Sprint(a)
	if _, err := fmt.Fprintln(bw, s[1:len(s)-1]); err != nil {
		panic(err)
	}
}
func dbg(a ...interface{}) {
	if _, err := fmt.Fprintln(os.Stderr, a...); err != nil {
		panic(err)
	}
}
func dbgMatrix(a [][]int) {
	for i := 0; i < len(a); i++ {
		dbg(a[i])
	}
}
func flush() {
	if err := bw.Flush(); err != nil {
		panic(err)
	}
}
func YESorNO(b bool) string {
	if b {
		return "YES"
	} else {
		return "NO"
	}
}
func YesOrNo(b bool) string {
	if b {
		return "Yes"
	} else {
		return "No"
	}
}
func main() {
	solve()
	flush()
}

const (
	bwBufSize = 1e6

	alphabetLower = "abcdefghijklmnopqrstuvwxyz"
	alphabetUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	// maxInt64  = 9223372036854775807  // 9e18
	// maxInt32  = 2147483647           // 2e9
	// maxUint64 = 18446744073709551615 // 1e19
	inf = 1 << 60
	mod = 1e9 + 7
)

type pair struct{ fi, se int }
type byFiSe []pair

func (p byFiSe) Len() int      { return len(p) }
func (p byFiSe) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p byFiSe) Less(i, j int) bool {
	if p[i].fi == p[j].fi {
		return p[i].se < p[j].se
	}
	return p[i].fi < p[j].fi
}

type point struct{ x, y int }

type UnDirectedTree struct{ g [][]int }

func NewUnDirectedTree(size int) *UnDirectedTree { return &UnDirectedTree{g: make([][]int, size)} }
func (tr *UnDirectedTree) AddEdge(u, v int) {
	tr.g[u] = append(tr.g[u], v)
	tr.g[v] = append(tr.g[v], u)
}
func (tr *UnDirectedTree) DFS(r int) []int {
	ds := make([]int, len(tr.g))
	var f func(int, int, int)
	f = func(c, p, d int) {
		ds[c] = d
		for _, nv := range tr.g[c] {
			if nv == p {
				continue
			}
			f(nv, c, d+1)
		}
	}
	f(r, -1, 0)
	return ds
}

func solve() {
	n, x := ri(), ri()-1

	t := NewUnDirectedTree(n)
	for i := 0; i < n-1; i++ {
		a, b := ri()-1, ri()-1
		t.AddEdge(a, b)
	}

	distX := t.DFS(x)
	distA := t.DFS(0)

	distAtoZ := distA[x]
	q := []int{x}
	var now int
	isVisited := make([]bool, len(t.g))
	for len(q) != 0 {
		now, q = q[0], q[1:]
		isVisited[now] = true
		chmax(&distAtoZ, distA[now])
		for _, next := range t.g[now] {
			if isVisited[next] {
				continue
			}
			if !(distX[next] < distA[next]) {
				continue
			}
			q = append(q, next)
		}
	}

	pln(distAtoZ * 2)
}

package main

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

var n, x int
var tree [][]int

func bfs(start int) []int {
	q := []int{start}

	dist := make([]int, n + 1)
	dist[start] = 1

	for len(q) > 0 {
		t := q[0]
		q = q[1:]

		for _, next := range tree[t] {
			if dist[next] == 0 {
				dist[next] = dist[t] + 1
				q = append(q, next)
			}
		}
	}

	return dist
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &x)
	tree = make([][]int, n + 1)
	for i := 0; i < n - 1; i++ {
		var t1, t2 int
		fmt.Fscanf(buf, "%d %d\n", &t1, &t2)
		tree[t1] = append(tree[t1], t2)
		tree[t2] = append(tree[t2], t1)
	}

	ds := bfs(1)
	dx := bfs(x)

	best := 0
	for i := 1; i <= n; i++ {
		if ds[i] > dx[i] && ds[i] > best {
			best = ds[i]
		}
	}
	fmt.Println((best - 1) * 2)
}


You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.

The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.

Print the lexicographically maximum subsequence of string s.

NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA

package main
import (
	"fmt"
	"bufio"
	"os"
	//"strconv"
)

func main() {
	//input:= bufio.NewScanner(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	//input.Scan()
	reader := bufio.NewReader(os.Stdin)
	var s string
	var p int
	var c uint8
	p=0
	fmt.Fscan(reader,&s)
	//s = input.Text()
	for c='z';c>='a';c-- {
		for i:=p;i<len(s);i++ {
			if s[i]==c {
				out.WriteString(string(s[i]))
				p=i+1
			}
		}
	}
	out.Flush()
	//fmt.Println(res)
}

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    writer := bufio.NewWriter(os.Stdout)
    var s string
    fmt.Fscan(reader,&s)
    ans := make([]byte,0,len(s))
    for i := len(s)-1; i >= 0; i-- {
        if (len(ans) == 0) || (ans[len(ans)-1] <= s[i]) {
            ans = append(ans,s[i])
        }
    }
    for i := len(ans)-1; i >= 0; i-- {
        writer.WriteByte(ans[i])
    }
    writer.WriteRune('\n')
    writer.Flush()
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	s, err := reader.ReadString('\n')
	if err != nil {
		writer.WriteString(fmt.Sprintf("reading error: %s\n", err))
		return
	}
	s = s[0:len(s)-1]
	last := map[uint8]int{}
	for ch := uint8('a'); ch <= 'z'; ch++ {
		last[ch] = -1
	}
	for i := 0; i < len(s); i++ {
		last[s[i]] = i
	}
	best := []uint8{}
	ch := uint8('z')
	for i := 0; i < len(s); i++ {
		for last[ch] < i {
			ch--
		}
		if s[i] == ch {
			best = append(best, ch)
		}
	}
	writer.WriteString(fmt.Sprintf("%s\n", best))
}

package main
import (
	"fmt"
	"bufio"
	"os"
	//"strconv"
)

func main() {
	input:= bufio.NewScanner(os.Stdin)
	//out := bufio.NewWriter(os.Stdout)
	input.Scan()
	var s,res string
	var p int
	var c uint8
	p=0
	s = input.Text()
	for c='z';c>='a';c-- {
		for i:=p;i<len(s);i++ {
			if s[i]==c {
				res+=string(s[i])
				p=i+1
			}
		}
	}
	fmt.Println(res)
}

package main

import (
    "bufio"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    writer := bufio.NewWriter(os.Stdout)
    s, _, _ := reader.ReadLine()
    ans := make([]byte,0,len(s))
    for i := len(s)-1; i >= 0; i-- {
        if (len(ans) == 0) || (ans[len(ans)-1] <= s[i]) {
            ans = append(ans,s[i])
        }
    }
    for i := len(ans)-1; i >= 0; i-- {
        writer.WriteByte(ans[i])
    }
    writer.WriteRune('\n')
    writer.Flush()
}

package main

import (
    "bufio"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    writer := bufio.NewWriter(os.Stdout)
    scanner.Scan()
    s := scanner.Text()
    ans := make([]byte,0,len(s))
    for i := len(s)-1; i >= 0; i-- {
        if (len(ans) == 0) || (ans[len(ans)-1] <= s[i]) {
            ans = append(ans,s[i])
        }
    }
    for i := len(ans)-1; i >= 0; i-- {
        writer.WriteByte(ans[i])
    }
    writer.WriteRune('\n')
    writer.Flush()
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	scanner.Scan()
	s := scanner.Text()
	last := map[uint8]int{}
	for ch := uint8('a'); ch <= 'z'; ch++ {
		last[ch] = -1
	}
	for i := 0; i < len(s); i++ {
		last[s[i]] = i
	}
	best := []uint8{}
	ch := uint8('z')
	for i := 0; i < len(s); i++ {
		for last[ch] < i {
			ch--
		}
		if s[i] == ch {
			best = append(best, ch)
		}
	}
	best = append(best, 0)
	writer.WriteString(fmt.Sprintf("%s\n", best))
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	scanner.Scan()
	s := scanner.Text()
	last := map[uint8]int{}
	for ch := uint8('a'); ch <= 'z'; ch++ {
		last[ch] = -1
	}
	for i := 0; i < len(s); i++ {
		last[s[i]] = i
	}
	best := []uint8{}
	ch := uint8('z')
	for i := 0; i < len(s); i++ {
		for last[ch] < i {
			ch--
		}
		if s[i] == ch {
			best = append(best, ch)
		}
	}
	writer.WriteString(fmt.Sprintf("%s\n", best))
}


You are given several queries. Each query consists of three integers $$$p$$$, $$$q$$$ and $$$b$$$. You need to answer whether the result of $$$p/q$$$ in notation with base $$$b$$$ is a finite fraction.A fraction in notation with base $$$b$$$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of queries. Next $$$n$$$ lines contain queries, one per line. Each line contains three integers $$$p$$$, $$$q$$$, and $$$b$$$ ($$$0 \le p \le 10^{18}$$$, $$$1 \le q \le 10^{18}$$$, $$$2 \le b \le 10^{18}$$$). All numbers are given in notation with base $$$10$$$.

For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.

package main

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

/*
def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

def finite(p, q, b):
    d = gcd(p, q)
    p, q = p // d, q // d

    while True:
        d = gcd(q, b)
        if d == 1:
            break
        while q % d == 0:
            q //= d
    return q == 1

n = int(stdin.readline())
for i in range(n):
    p, q, b = map(int, stdin.readline().strip().split())
    if finite(p, q, b):
        print('Finite')
    else:
        print('Infinite')
*/

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

func finite(p, q, b int64) bool {
	d := gcd(p, q)
	p, q = p/d, q/d
	for {
		d = gcd(q, b)
		if d == 1 {
			break
		}
		for q%d == 0 {
			q /= d
		}
	}
	return q == 1
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < n; i++ {
		scanner.Scan()
		line := strings.Split(scanner.Text(), " ")
		p, _ := strconv.ParseInt(line[0], 10, 64)
		q, _ := strconv.ParseInt(line[1], 10, 64)
		b, _ := strconv.ParseInt(line[2], 10, 64)
		if finite(p, q, b) {
			fmt.Println("Finite")
		} else {
			fmt.Println("Infinite")
		}
	}
}

package main

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

var n int
var p, q, b int64

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

func main() {
	inBuf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(inBuf, "%d\n", &n)
	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() } ()
	for i := 0; i < n; i++ {
		fmt.Fscanf(inBuf, "%d %d %d\n", &p, &q, &b)
		m := gcd(p, q)
		q /= m
		for {
			m := gcd(q, b)
			for m != 1 && q % m == 0 {
				q /= m
			}
			if m == 1 {
				if b%q != 0 {
					fmt.Fprintln(outBuf, "Infinite")
				} else {
					fmt.Fprintln(outBuf, "Finite")
				}
				break
			}
		}
	}
}

package main

import (
	"bufio"
	"os"
)

var in = bufio.NewScanner(os.Stdin)

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

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

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

	for n := readInt(); n > 0; n-- {
		p := readInt()
		q := readInt()
		b := readInt()
		for {
			g := gcd(q, b)
			if g == 1 {
				break
			}
			q /= g
			for q % g == 0 {
				q /= g
			}
		}
		if p%q == 0 {
			out.WriteString("Finite\n")
		} else {
			out.WriteString("Infinite\n")
		}
	}
}

package main

import (
	"bufio"
	"os"
)

func gcd(a, b int64) int64 {
	for b != 0 {
		var r int64 = a % b;
		a = b;
		b = r;
	}
	return a;
}

var in = bufio.NewScanner(os.Stdin)

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

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

	var t int64 = readInt();

	for ; t > 0; t-- {
		p := readInt();
		q := readInt();
		b := readInt();

		var k int64 = gcd(p, q);
		p /= k;
		q /= k;

		var bad bool = false;
		for q != 1 {
			k = gcd(q, b);
			if k == 1 {
				bad = true;
				break;
			}
			for q % k == 0 {
				q /= k;
			}
		}

		if bad {
			out.WriteString("Infinite\n");
		} else {
			out.WriteString("Finite\n");
		}
	}
}


Ksusha is a beginner coder. Today she starts studying arrays. She has array a1, a2, ..., an, consisting of n positive integers.Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!

The first line contains integer n (1 ≤ n ≤ 105), showing how many numbers the array has. The next line contains integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the array elements.

Print a single integer — the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1. If there are multiple answers, you are allowed to print any of them.

package main

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

func main() {
	var n int
	cek:=true
	min:=1000000000
	reader := bufio.NewReader(os.Stdin)
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
		if min>a[i] { min=a[i]}
	}
	for i := 0; i < n; i++ {
		if (a[i] %min)!=0 {
			cek=false
			break
		}
	}
	if cek {
		fmt.Println(min)
	}else{
		fmt.Println(-1)
	}
}

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

func main() {
	var nn, x int64
	var aa[100000]int64
	var flag bool
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	flag=false
	r.Scan()
	nn, _ = strconv.ParseInt(r.Text(), 0, 64)
	for i:=0; int64(i)<nn; i++ {
		r.Scan()
		aa[i], _ = strconv.ParseInt(r.Text(), 0, 64)
	}
	x=aa[0]
	for i:=0; int64(i)<nn; i++ {
		if aa[i]<x {
			x=aa[i]
		}
	}
	for i:=0; int64(i)<nn; i++ {
		if aa[i]%x!=0 {
			flag=true
			break
		}
	}

	if flag==false {
		fmt.Println(x)
	} else if flag==true {
		fmt.Println("-1")
	}
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := range a {
		fmt.Scan(&a[i])
	}
	sort.Ints(a)
	yes := true
	for _, v := range a {
		if v % a[0] != 0 {
			yes = false
			break
		}
	}
	if yes {
		fmt.Println(a[0])
	} else {
		fmt.Println(-1)
	}
}

package main

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

func main() {
	var n int
	fmt.Scanln(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	sort.Ints(a)
	for i := 1; i < n; i++  {
		if a[i] % a[0] != 0 {
			fmt.Println(-1)
			os.Exit(0)
		}
	}
	fmt.Println(a[0])
}

package main

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

func main() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	sort.Ints(a)
	yes := true
	for i := 1; i < n; i++  {
		if a[i] % a[0] != 0 {
			yes = false
			break
		}
	}
	if yes {
		fmt.Println(a[0])
	} else {
		fmt.Println(-1)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	line, _ := in.ReadString('\n')
	line, _ = in.ReadString('\n')
	tmp := strings.Fields(line)
	a := make([]int, len(tmp))
	min := 1 << 31 - 1
	for i := range(tmp){
		a[i], _ = strconv.Atoi(tmp[i])
		if a[i] < min{
			min = a[i]
		}
	}
	for _, v := range(a){
		if v % min != 0{
			fmt.Println(-1)
			os.Exit(0)
		}
	}
	fmt.Println(min)
}

package main

import "fmt"

func main() {
	n, min := 0, 1 << 31 - 1
	fmt.Scan(&n)
	a := make([]int, n)
	for i := range a {
		fmt.Scan(&a[i])
		if a[i] < min {
			min = a[i]
		}
	}
	yes := true
	for _, v := range a {
		if v % min != 0 {
			yes = false
			break
		}
	}
	if yes {
		fmt.Println(min)
	} else {
		fmt.Println(-1)
	}
}

// 299A
package main

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

func main() {
	var a [111111]int
	var n int
	in := bufio.NewReader(os.Stdin)
	fmt.Scan(&n)
	min := 1111111111
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &a[i])
		if a[i] < min {
			min = a[i]
		}
	}
	for i := 0; i < n; i++ {
		if a[i]%min != 0 {
			fmt.Print(-1)
			return
		}
	}
	fmt.Print(min)
}

// 299A
package main

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

func main() {
	var n int
	z := bufio.NewReader(os.Stdin)
	fmt.Scan(&n)
	x := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(z, &x[i])
	}
	sort.Sort(sort.IntSlice(x))
	min := x[0]
	for i := 0; i < n; i++ {
		if x[i]%min != 0 {
			fmt.Println("-1")
			return
		}
	}
	fmt.Println(min)
}

package main

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

func main() {
	var n int
	min:=10000000
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &n)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
		if min>a[i] { min=a[i]}
	}
	cek:=true
	for i := 0; i < n; i++ {
		if (a[i] %min)!=0 {
			cek=false
			break
		}
	}
	if cek {
		fmt.Println(min)
	}else{
		fmt.Println(-1)
	}
}

package main

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

func main() {
	var n int
	cek:=true
	min:=10000000
	reader := bufio.NewReader(os.Stdin)
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
		if min>a[i] { min=a[i]}
	}
	for i := 0; i < n; i++ {
		if (a[i] %min)!=0 {
			cek=false
			break
		}
	}
	if cek {
		fmt.Println(min)
	}else{
		fmt.Println(-1)
	}
}

// 299A
package main

import (
	"fmt"
)

func main() {
	var a [111111]int
	var n int
	fmt.Scan(&n)
	min := 1111111111
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
		if a[i] < min {
			min = a[i]
		}
	}
	for i := 0; i < n; i++ {
		if a[i]%min != 0 {
			fmt.Print(-1)
			return
		}
		fmt.Print(min)
		return
	}
}

// 299A
package main

import (
	"fmt"
)

func main() {
	var a [111111]int
	var n int
	fmt.Scan(&n)
	min := 1111111111
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
		if a[i] < min {
			min = a[i]
		}
	}
	for i := 0; i < n; i++ {
		if a[i]%min != 0 {
			fmt.Print(-1)
			return
		}
		fmt.Print(min)
	}
}

// 299A
package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, a int
	fmt.Scan(&n)
	x := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&x[i])
	}
	sort.Sort(sort.IntSlice(x))
	if x[0] == 1 {
		fmt.Println(x[0])
		return
	} else {
		for i := 0; i < n-1; i++ {
			if x[i] == x[i+1] {
				continue
			} else {
				a = x[i+1] - x[i]
			}
		}
		for i := 0; i < n-1; i++ {
			if x[i+1]-x[i] != a && x[i+1] != x[i] {
				fmt.Println("-1")
				return
			}
		}
	}
	fmt.Println(x[n-1] / x[0])
}

// 299A
package main

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

func main() {
	var n, a int
	z := bufio.NewReader(os.Stdin)
	fmt.Scan(&n)
	x := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(z, &x[i])
	}
	sort.Sort(sort.IntSlice(x))
	if n == 1 {
		fmt.Println(x[0])
		return
	}
	if x[0] == 1 {
		fmt.Println(x[0])
		return
	} else {
		for i := 0; i < n-1; i++ {
			if x[i] == x[i+1] {
				continue
			} else {
				a = x[i+1] - x[i]
			}
		}
		for i := 0; i < n-1; i++ {
			if x[i+1]-x[i] != a && x[i+1] != x[i] {
				fmt.Println("-1")
				return
			}
		}
	}
	fmt.Println(x[n-1] / x[0])
}


Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi ≠ yi).In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n - 1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers xi, yi (1 ≤ xi, yi ≤ 105; xi ≠ yi) — the color numbers for the home and away kits of the i-th team.

For each team, print on a single line two space-separated integers — the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input.

package main

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

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

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

	n := nextInt()

	// x, y := make([]int, n), make([]int, n)
	y := make([]int, n)
	colors := make([]int, 100001)

	for i := 0; i < n; i++ {
		// x[i] = nextInt()
		colors[nextInt()]++
		y[i] = nextInt()

	}

	for i := 0; i < n; i++ {
		println((n - 1) + colors[y[i]], (n - 1) - colors[y[i]])
	}
}

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

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

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

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

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

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

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

func main() {
	var n,kit1,kit2 int
	store:=0
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	out := bufio.NewWriter(os.Stdout)
	x:=make([]int,100001)
	y:=make([]int,100001)
	fmt.Scan(&n)
	for i:=0;i<n;i++ {
		input.Scan()
		aa,_:= strconv.Atoi(input.Text())
		store=aa
		input.Scan()
		bb,_:= strconv.Atoi(input.Text())
		y[i]=bb
		//fmt.Scan(&store, &y[i])
		x[store]++
	}
	var s string
	for i:=0;i<n;i++ {
		kit1=n+x[y[i]]-1
		kit2=n-x[y[i]]-1
		s=strconv.Itoa(kit1)+" "+strconv.Itoa(kit2)+"\n"
		//out.WriteString(strconv.Itoa(kit1))
		out.WriteString(s)
		//out.Flush()
		//fmt.Print(" ")
//		out.WriteString(strconv.Itoa(n-x[y[i]]-1))
		out.Flush()
		//fmt.Println()
		//fmt.Println(kit1,kit2)
	}
	//out.Flush()
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    writer := bufio.NewWriter(os.Stdout)
    var n int
    var home,away [100005]int
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        scanner.Scan()
        h, _ := strconv.Atoi(scanner.Text())
        home[h]++
        scanner.Scan()
        away[i], _ = strconv.Atoi(scanner.Text())
    }
    for i := 0; i < n; i++ {
        writer.WriteString(strconv.Itoa(n-1+home[away[i]])+" "+strconv.Itoa(n-1-home[away[i]])+"\n")
    }
    writer.Flush()
}

package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"strconv"
	"time"
)

// ******************************** CODE STARTS ********************************

var ()

func solve() {
	n := readInt()
	X := make([]int, n)
	Y := make([]int, n)
	M := make(map[int]int)
	for i := 0; i < n; i++ {
		X[i] = readInt()
		M[X[i]]++
		Y[i] = readInt()
	}

	for i := 0; i < n; i++ {
		printInt(n - 1 + M[Y[i]])
		printString(" ")
		printInt(n - 1 - M[Y[i]])
		printLine()
	}

}

// ********************************* CODE ENDS *********************************

// IO.

var (
	scanner *bufio.Scanner
	writer  *bufio.Writer
	logger  *log.Logger
)

func main() {
	local := flag.Bool("local", false, "Equals true, if run is local.")
	flag.Parse()

	var (
		input  *os.File
		output *os.File
	)

	if *local {
		startTime := time.Now()
		defer func() {
			println(fmt.Sprintf("Time: %.5fs", time.Since(startTime).Seconds()))
		}()
		input, _ = os.Open("/home/outside/coding/workspace/go/io/input.txt")
		output, _ = os.Create("/home/outside/coding/workspace/go/io/output.txt")
		logger = log.New(output, "log: ", 0)
	} else {
		input = os.Stdin
		output = os.Stdout
		// input, _ = os.Open("")
		// output, _ = os.Create("")
	}
	defer input.Close()
	defer output.Close()

	scanner = bufio.NewScanner(input)
	scanner.Split(bufio.ScanWords)

	writer = bufio.NewWriter(output)
	defer writer.Flush()

	solve()
}

// Read.

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

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

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

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

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

// Write.

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

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

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

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

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

// Log.

func logln(value ...interface{}) {
	writer.Flush()
	logger.Println(value...)
}
func logf(format string, value ...interface{}) {
	writer.Flush()
	logger.Printf(format, value...)
}

// Tuple

type Tuple struct {
	a, b int
}

func (p Tuple) Equals(key Key) bool {
	return p.a == key.(Tuple).a
}

func (p Tuple) Less(key Key) bool {
	return p.a < key.(Tuple).a
}

type TupleSlice []Tuple

func (p TupleSlice) Len() int {
	return len(p)
}

func (p TupleSlice) Less(j, i int) bool {
	return p[j].a < p[i].a
}

func (p TupleSlice) Swap(j, i int) {
	p[j], p[i] = p[i], p[j]
}

// Min, max, abs.

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

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

func absInt(a int) int {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

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

func minInt64(a, b int64) int64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absInt64(a int64) int64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absFloat64(a float64) float64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

// Set Key interface implementations.

type Int int

func (p Int) Equals(key Key) bool {
	return int(p) == int(key.(Int))
}

func (p Int) Less(key Key) bool {
	return int(p) < int(key.(Int))
}

// Set.

type Key interface {
	Equals(key Key) bool
	Less(key Key) bool
}

type node struct {
	key   Key
	left  *node
	right *node
}

func newNode(key Key) *node {
	return &node{key, nil, nil}
}

type SplayTree struct {
	root *node
	tmp  *node
	len  int
}

func NewSplayTree() *SplayTree {
	return &SplayTree{nil, newNode(nil), 0}
}

func rotateLeft(x, p *node) {
	p.right = x.left
	x.left = p
}

func rotateRight(x, p *node) {
	p.left = x.right
	x.right = p
}

func (p *SplayTree) splay(x *node, key Key) *node {
	if x == nil {
		return nil
	}

	left := p.tmp
	right := p.tmp

	for {
		if key.Less(x.key) {
			y := x.left
			if y == nil {
				break
			}
			if key.Less(y.key) { // zig-zig
				rotateRight(y, x)
				x = y
				if x.left == nil {
					break
				}
			}
			// link right
			right.left = x
			right = x
			// move left
			x = x.left
		} else if x.key.Less(key) {
			y := x.right
			if y == nil {
				break
			}
			if y.key.Less(key) { // zig-zig
				rotateLeft(y, x)
				x = y
				if x.right == nil {
					break
				}
			}
			// link left
			left.right = x
			left = x
			// move right
			x = x.right
		} else {
			break
		}
	}

	left.right = x.left
	right.left = x.right
	x.left = p.tmp.right
	x.right = p.tmp.left

	return x
}

// left <= key < right
func (p *SplayTree) split(key Key) (left, right *node) {
	p.root = p.splay(p.root, key)
	if p.root.key.Equals(key) || p.root.key.Less(key) {
		right := p.root.right
		p.root.right = nil
		return p.root, right
	} else {
		left := p.root.left
		p.root.left = nil
		return left, p.root
	}
}

// keys from left tree must be less then keys from right tree
func (p *SplayTree) join(left, right *node) *node {
	if left == nil {
		return right
	} else if right == nil {
		return left
	}
	left = p.splay(left, right.key)
	left.right = right
	return left
}

type Set interface {
	Len() int
	Insert(key Key) error
	Find(key Key) bool
	Remove(key Key) error
}

func NewSet() Set {
	return Set(NewSplayTree())
}

func (p *SplayTree) Len() int {
	return p.len
}

func (p *SplayTree) Insert(key Key) error {
	if p.root == nil {
		p.root = newNode(key)
		p.len++
	} else {
		p.root = p.splay(p.root, key)
		if p.root.key.Equals(key) {
			return errors.New("Such key already exists")
		} else {
			left, right := p.split(key)
			p.root = newNode(key)
			p.root.left = left
			p.root.right = right
			p.len++
		}
	}
	return nil
}

func (p *SplayTree) Find(key Key) bool {
	if p.root == nil {
		return false
	}
	p.root = p.splay(p.root, key)
	return p.root.key.Equals(key)
}

func (p *SplayTree) Remove(key Key) error {
	p.root = p.splay(p.root, key)
	if p.root == nil || !p.root.key.Equals(key) {
		return errors.New("Such key doesn't exist")
	}
	p.root = p.join(p.split(key))
	return nil
}

package main

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

type Kit struct {
	home, away int
}

func main() {
	var n int
	fmt.Scan(&n)

	kits := make([]Kit, n, n)
	ans := make([]Kit, n, n)

	bs := bufio.NewScanner(os.Stdin)
	bs.Split(bufio.ScanWords)
	counts := make([]int, 100001, 100001)
	for i := 0; i < n; i++ {
		bs.Scan()
		kits[i].home, _ = strconv.Atoi(bs.Text())
		bs.Scan()
		kits[i].away, _ = strconv.Atoi(bs.Text())

		ans[i].home = n - 1
		ans[i].away = n - 1
		counts[kits[i].home]++
	}

	for i := 0; i < n; i++ {
		ans[i].home += counts[kits[i].away]
		ans[i].away -= counts[kits[i].away]
	}

	var buffer bytes.Buffer
	for i := 0; i < n; i++ {
		buffer.WriteString(strconv.Itoa(ans[i].home) + " " + strconv.Itoa(ans[i].away) + "\n")
	}
	fmt.Print(buffer.String())
}

// 432B-mic
package main

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

func main() {
    w := bufio.NewScanner(os.Stdin)
    w.Split(bufio.ScanWords)
    r := bufio.NewWriter(os.Stdout)
    var n int
    var a, h [100003]int
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        w.Scan()
        j, _ := strconv.Atoi(w.Text())
        w.Scan()
        o, _ := strconv.Atoi(w.Text())
        a[i] = o
        h[j]++
    }
    for i := 0; i < n; i++ {
        k := strconv.Itoa(n-1+h[a[i]]) + " " + strconv.Itoa(n-1-h[a[i]]) + "\n"
        r.WriteString(k)
        r.Flush()
    }
}


You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x < n$$$ and $$$1 \le y < m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.

If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.

// To execute Go code, please declare a func main() in a package "main"

package main

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

func getNumsFromOneLine(ir *bufio.Reader) []int {
  stream, _ := ir.ReadString('\n')
  // Trims the stream and then splits
  trimmedStream := strings.TrimSpace(stream)
  splitArr := strings.Split(trimmedStream, " ")
  // convert strings to integers and store them in a slice
  nums := make([]int, len(splitArr))
  for index, val := range splitArr {
    nums[index], _ = strconv.Atoi(val)
  }
  return nums
}

func main() {
  ir := bufio.NewReader(os.Stdin)
  nm := getNumsFromOneLine(ir)
  n, m := nm[0], nm[1]
  a := make([][]int, n)
  b := make([][]int, n)

  for i := 0; i < n; i++ {
    a[i] = make([]int, m)
    b[i] = make([]int, m)
    nums := getNumsFromOneLine(ir)
    for j := 0; j < m; j++ {
      a[i][j] = nums[j]
    }
  }

  res := make([][2]int, 0)
  for i := 0; i < n-1; i++ {
    for j := 0; j < m-1; j++ {
      flag := a[i][j] == 1 && a[i+1][j] == 1 && a[i][j+1] == 1 && a[i+1][j+1] == 1
      if flag {
        b[i][j] = 1
        b[i+1][j] = 1
        b[i][j+1] = 1
        b[i+1][j+1] = 1
        res = append(res, [2]int{i+1, j+1})
      }

    }

  }
  f := true
  for i := 0; i < n; i++ {
    for j := 0; j < m; j++ {
      if a[i][j] != b[i][j] {
        f = false
        break
      }
    }
  }

  if f {
    fmt.Println(len(res))
    for i := 0; i < len(res); i++ {
      fmt.Println(res[i][0], res[i][1])
    }
  } else {
    fmt.Println(-1)
  }

}

package main

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

/* solution */

var n, m int
var a, b [][]int

func solve() {

	n, m = readInt(), readInt()
	a = make([][]int, n)
	b = make([][]int, n)

	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		b[i] = make([]int, m)
		for j := 0; j < m; j++ {
			a[i][j] = readInt()
		}
	}

	ans := make([][]int, 0)

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == 1 {
				x, y := check(i, j)
				if x != -1 {
					b[x][y] = 1
					b[x+1][y] = 1
					b[x][y+1] = 1
					b[x+1][y+1] = 1
					ans = append(ans, []int{x, y})
				}
			}
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] != b[i][j] {
				printLnInt(-1)
				return
			}
		}
	}

	printLnInt(len(ans))
	for i := 0; i < len(ans); i++ {
		printInt(ans[i][0] + 1)
		printLnInt(ans[i][1] + 1)
	}

}

func check(i, j int) (int, int) {
	if checkOne(i, j) {
		return i, j
	}
	if checkOne(i-1, j) {
		return i - 1, j
	}
	if checkOne(i-1, j-1) {
		return i - 1, j - 1
	}
	if checkOne(i, j-1) {
		return i, j - 1
	}
	return -1, -1
}

func checkOne(i, j int) bool {
	if i < 0 || j < 0 || i >= n-1 || j >= m-1 {
		return false
	}
	return a[i][j] == 1 && a[i+1][j] == 1 && a[i][j+1] == 1 && a[i+1][j+1] == 1 && !(b[i][j] == 1 && b[i+1][j] == 1 && b[i][j+1] == 1 && b[i+1][j+1] == 1)
}

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
		defer f.Close()
	} else {
		f = os.Stdin
	}

	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	reader = bufio.NewScanner(f)
	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

func read() string {
	reader.Scan()
	return reader.Text()
}

func readInt() int {
	reader.Scan()
	ret, _ := strconv.Atoi(reader.Text())
	return ret
}

func print(s string) {
	writer.WriteString(s)
	writer.WriteString(" ")
}

func printLn(s string) {
	writer.WriteString(s)
	writer.WriteString("\n")
}

func printInt(i int) {
	print(strconv.Itoa(i))
}

func printLnInt(i int) {
	printLn(strconv.Itoa(i))
}

package main

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

func check(arr [][]int, i, j int) bool {
	return arr[i][j] == 1 && arr[i][j+1] == 1 && arr[i+1][j] == 1 && arr[i+1][j+1] == 1
}

func color(arr [][]int, i, j int) {
	arr[i][j] = 1
	arr[i][j+1] = 1
	arr[i+1][j] = 1
	arr[i+1][j+1] = 1
}

func equal(firstArr, secondArr [][]int, m, n int) bool {
	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			if firstArr[i][j] != secondArr[i][j] {
				return false
			}
		}
	}
	return true
}

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1024*1024)
	var m, n int
	fmt.Scanf("%d %d\n", &m, &n)
	var firstArr [][]int
	secondArr := make([][]int, m)
	for i := 0; i < m; i++ {
		sRowTemp := strings.Split(readLine(reader), " ")
		var sRow []int
		secondArr[i] = make([]int, n)
		for _, sRowItem := range sRowTemp {
			sItemTemp, err := strconv.ParseInt(sRowItem, 10, 64)
			checkError(err)
			sItem := int(sItemTemp)
			sRow = append(sRow, sItem)
		}
		firstArr = append(firstArr, sRow)
	}

	var res [][]int
	for i := 0; i < m-1; i++ {
		for j := 0; j < n-1; j++ {
			if check(firstArr, i, j) {
				color(secondArr, i, j)
				res = append(res, []int{i + 1, j + 1})
			}
		}
	}
	if equal(firstArr, secondArr, m, n) {
		fmt.Println(len(res))
		for _, pair := range res {
			fmt.Printf("%d %d\n", pair[0], pair[1])
		}
	} else {
		fmt.Print(-1)
	}
}

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

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

// Author: sighduck
// URL: https://codeforces.com/contest/1207/problem/B

package main

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

type Move struct {
	X int
	Y int
}

type Solution struct {
	Moves  []Move
	Exists bool
}

func isLegal(A [][]int, B [][]int, i int, j int) bool {
	return A[i][j] == 1 && A[i][j+1] == 1 && A[i+1][j] == 1 && A[i+1][j+1] == 1 &&
		(B[i][j] == 0 || B[i][j+1] == 0 || B[i+1][j] == 0 || B[i+1][j+1] == 0)
}

func Solve(n int, m int, A [][]int) Solution {
	B := make([][]int, n)
	for i := 0; i < n; i++ {
		B[i] = make([]int, m)
		for j := 0; j < m; j++ {
			B[i][j] = 0
		}
	}

	moves := []Move{}
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if i != n-1 && j != m-1 && isLegal(A, B, i, j) {
				moves = append(moves, Move{X: i + 1, Y: j + 1})
				B[i][j] = 1
				B[i][j+1] = 1
				B[i+1][j] = 1
				B[i+1][j+1] = 1
			} else if B[i][j] != A[i][j] {
				return Solution{Moves: []Move{}, Exists: false}
			}
		}
	}
	return Solution{Moves: moves, Exists: true}
}

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

	var n, m int
	fmt.Fscan(reader, &n, &m)
	A := make([][]int, n)
	for i := 0; i < n; i++ {
		A[i] = make([]int, m)
		for j := 0; j < m; j++ {
			fmt.Fscan(reader, &A[i][j])
		}
	}
	solution := Solve(n, m, A)
	if !solution.Exists {
		fmt.Fprintf(writer, "-1\n")
	} else {
		fmt.Fprintf(writer, "%d\n", len(solution.Moves))
		for _, move := range solution.Moves {
			fmt.Fprintf(writer, "%d %d\n", move.X, move.Y)
		}
	}
}

package main

import "fmt"

type Pair struct {
	First, Second int
}

var a, b [55][55]int
var ans []Pair

func apply(y, x int) {
	ans = append(ans, Pair{y + 1, x + 1})
	b[y][x] = 1
	b[y+1][x] = 1
	b[y][x+1] = 1
	b[y+1][x+1] = 1
}

func ok(y, x int) bool {
	return a[y][x] == 1 && a[y+1][x] == 1 && a[y][x+1] == 1 && a[y+1][x+1] == 1
}

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			fmt.Scan(&a[i][j])
		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if ok(i, j) {
				apply(i, j)
			}
		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] != b[i][j] {
				fmt.Println(-1)
				return
			}
		}
	}
	fmt.Println(len(ans))
	for _, p := range ans {
		fmt.Println(p.First, p.Second)
	}
}

// Author: sighduck
// URL: https://codeforces.com/contest/1207/problem/B

package main

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

type Move struct {
	X int
	Y int
}

type Solution struct {
	Moves  []Move
	Exists bool
}

func isLegal(A [][]int, B [][]int, i int, j int) bool {
	return A[i][j] == 1 && A[i][j+1] == 1 && A[i+1][j] == 1 && A[i+1][j+1] == 1 &&
		(B[i][j] == 0 || B[i][j+1] == 0 || B[i+1][j] == 0 || B[i+1][j+1] == 0)
}

func Solve(n int, m int, A [][]int) Solution {
	B := make([][]int, n)
	for i := 0; i < n; i++ {
		B[i] = make([]int, m)
		for j := 0; j < m; j++ {
			B[i][j] = 0
		}
	}

	moves := []Move{}
	for i := 0; i < n-1; i++ {
		for j := 0; j < m-1; j++ {
			if isLegal(A, B, i, j) {
				moves = append(moves, Move{X: i + 1, Y: j + 1})
				B[i][j] = 1
				B[i][j+1] = 1
				B[i+1][j] = 1
				B[i+1][j+1] = 1
			} else if B[i][j] == 0 && A[i][j] == 1 {
				return Solution{Moves: []Move{}, Exists: false}
			}
		}
	}
	return Solution{Moves: moves, Exists: true}
}

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

	var n, m int
	fmt.Fscan(reader, &n, &m)
	A := make([][]int, n)
	for i := 0; i < n; i++ {
		A[i] = make([]int, m)
		for j := 0; j < m; j++ {
			fmt.Fscan(reader, &A[i][j])
		}
	}
	solution := Solve(n, m, A)
	if !solution.Exists {
		fmt.Fprintf(writer, "-1\n")
	} else {
		fmt.Fprintf(writer, "%d\n", len(solution.Moves))
		for _, move := range solution.Moves {
			fmt.Fprintf(writer, "%d %d\n", move.X, move.Y)
		}
	}
}

// Author: sighduck
// URL: https://codeforces.com/contest/1207/problem/B

package main

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

type Move struct {
	X int
	Y int
}

type Solution struct {
	Moves  []Move
	Exists bool
}

func isLegal(A [][]int, B [][]int, i int, j int) bool {
	return A[i][j] == 1 && A[i][j+1] == 1 && A[i+1][j] == 1 && A[i+1][j+1] == 1 &&
		(B[i][j] == 0 || B[i][j+1] == 0 || B[i+1][j] == 0 || B[i+1][j+1] == 0)
}

func Solve(n int, m int, A [][]int) Solution {
	B := make([][]int, n)
	for i := 0; i < n; i++ {
		B[i] = make([]int, m)
		for j := 0; j < m; j++ {
			B[i][j] = 0
		}
	}

	moves := []Move{}
	for i := 0; i < n-1; i++ {
		for j := 0; j < m-1; j++ {
			if isLegal(A, B, i, j) {
				moves = append(moves, Move{X: i + 1, Y: j + 1})
				B[i][j] = 1
				B[i][j+1] = 1
				B[i+1][j] = 1
				B[i+1][j+1] = 1
			} else if B[i][j] == 0 && A[i][j] == 1 {
				return Solution{Moves: []Move{}, Exists: false}
			}
		}
	}
	return Solution{Moves: moves, Exists: true}
}

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

	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	A := make([][]int, n)
	for i := 0; i < n; i++ {
		A[i] = make([]int, m)
		for j := 0; j < m; j++ {
			fmt.Fscanf(reader, "%d ", &A[i][j])
		}
	}
	solution := Solve(n, m, A)
	if !solution.Exists {
		fmt.Fprintf(writer, "-1\n")
	} else {
		fmt.Fprintf(writer, "%d\n", len(solution.Moves))
		for _, move := range solution.Moves {
			fmt.Fprintf(writer, "%d %d\n", move.X, move.Y)
		}
	}
}

package main

import "fmt"

type Pair struct {
	First, Second int
}

var a, b [55][55]int
var ans []Pair

func apply(y, x int) {
	ans = append(ans, Pair{x + 1, y + 1})
	b[y][x] = 1
	b[y+1][x] = 1
	b[y][x+1] = 1
	b[y+1][x+1] = 1
}

func ok(y, x int) bool {
	return a[y][x] == 1 && a[y+1][x] == 1 && a[y][x+1] == 1 && a[y+1][x+1] == 1
}

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			fmt.Scan(&a[i][j])
		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if ok(i, j) {
				apply(i, j)
			}
		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] != b[i][j] {
				fmt.Println(-1)
				return
			}
		}
	}
	fmt.Println(len(ans))
	for _, p := range ans {
		fmt.Println(p.First, p.Second)
	}
}


Each day in Berland consists of $$$n$$$ hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence $$$a_1, a_2, \dots, a_n$$$ (each $$$a_i$$$ is either $$$0$$$ or $$$1$$$), where $$$a_i=0$$$ if Polycarp works during the $$$i$$$-th hour of the day and $$$a_i=1$$$ if Polycarp rests during the $$$i$$$-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.

The first line contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — number of hours per day. The second line contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i=0$$$ if the $$$i$$$-th hour in a day is working and $$$a_i=1$$$ if the $$$i$$$-th hour is resting. It is guaranteed that $$$a_i=0$$$ for at least one $$$i$$$.

Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.

NoteIn the first example, the maximal rest starts in last hour and goes to the first hour of the next day.In the second example, Polycarp has maximal rest from the $$$4$$$-th to the $$$5$$$-th hour.In the third example, Polycarp has maximal rest from the $$$3$$$-rd to the $$$5$$$-th hour.In the fourth example, Polycarp has no rest at all.

package main

import (
	"fmt"
)

func getMaxRestingHours(a []bool) int {
	var max, current int

	// Process every element of the slice
	for _, b := range a {
		if b {
			current++
		} else if current != 0 {
			if current > max {
				max = current
			}
			current = 0
		}
	}

	// If we ended on a streak
	if current != 0 {
		// Continue on the beginning of the array until we hit a false
		for _, b := range a {
			if b {
				current++
			} else {
				// Update max
				if current > max {
					max = current
				}
				current = 0
				break
			}
		}
	}

	return max
}

func main() {
	// Read input array
	// scanner := bufio.NewScanner(os.Stdin)
	// scanner.Scan() // Ignore first line
	// scanner.Scan()
	// astr := strings.Fields(scanner.Text())
	// a := make([]bool, len(astr))
	// for i, s := range astr {
	// 	a[i] = (s == "1")
	// }

	var n int
	fmt.Scanf("%d\n", &n)

	a := make([]bool, n)
	for i := 0; i < n; i++ {
		var k int
		fmt.Scanf("%d", &k)
		a[i] = (k == 1)
	}

	// Do the thing
	m := getMaxRestingHours(a)
	fmt.Println(m)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, a, firstLen, lastLen, maxLen int
	fmt.Fscan(reader, &n)
	first := true
	for ; n > 0; n-- {
		fmt.Fscan(reader, &a)
		if a == 0 {
			if first {
				first = false
				firstLen = lastLen
			}
			if lastLen > maxLen {
				maxLen = lastLen
			}
			lastLen = 0
		} else {
			lastLen += 1
		}
	}
	if lastLen+firstLen > maxLen {
		maxLen = lastLen + firstLen
	}
	fmt.Println(maxLen)
}

package main

import "fmt"

func main() {
	var n, a, firstLen, lastLen, maxLen int
	fmt.Scan(&n)
	first := true
	for ; n > 0; n-- {
		fmt.Scan(&a)
		if a == 0 {
			if first {
				first = false
				firstLen = lastLen
			}
			if lastLen > maxLen {
				maxLen = lastLen
			}
			lastLen = 0
		} else {
			lastLen += 1
		}
	}
	if lastLen+firstLen > maxLen {
		maxLen = lastLen + firstLen
	}
	fmt.Println(maxLen)
}

package main

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

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

	var n, p,f int
	fmt.Fscanf(buf, "%d\n", &n)
	var first,end int
	mat := make([]int,n+1)
	for i:=0;i < n;i++{
		fmt.Fscanf(buf, "%d", &mat[i])
	}
	fmt.Fscanf(buf, "\n")
	ans := 0
	for p < n{
		if mat[p]==0{
			p++
			continue
		}
		f=p
		for f < n&&mat[f]==1{
			f++
		}
		if p == 0{
			first=f-p
		}
		if f==n{
			end=f-p
		}
		if f-p > ans{
			ans = f-p
		}
		//fmt.Printf("-%d %d\n",p,f)
		p = f

	}
	if first+end <= n&&ans < first+end{
		ans = first+end
	}
	fmt.Printf("%d\n",ans)

}

package main

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

func main()  {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var n ,x int
	fmt.Fscan(in,&n)
	a := make([]int,0)
	for i := 0 ; i < n; i++{
		fmt.Fscan(in,&x)
		a = append(a,x)
	}
	ans,cnt := 0,0

	for _, i := range a{
		if(i == 1){
			cnt ++
		}else{
				if(ans < cnt){
					ans = cnt
				}
				cnt = 0
		}
	}
	beg := 0
	for _, i := range a{
		if(i == 1){
			beg ++
		}else{
				break;
		}
	}
	for i := len(a) - 1 ;i >= 0; i--{
		if(a[i] == 1){
			beg ++;
		}else{
			break;
		}
	}
	fmt.Fprint(out,max(ans,min(beg,n)))
}

func max(i int, i2 int) int {
	if(i < i2){
		return i2
	}else{
		return i
	}
}
func min(i int , i2 int)  int {
	if(i < i2){
		return i
	}else{
		return i2
	}

}

package main

import "fmt"

func main() {
	var n int
	fmt.Scanln(&n)

	rest := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Scan(&rest[i])
	}

	ones := 0
	for i := n-1; rest[i] == 1; i-- {
		ones += 1
	}
	maxRest := 0
	for _, value := range rest {
		if value == 1 {
			ones += 1
			if ones > maxRest {
				maxRest = ones
			}
		} else {
			ones = 0
		}
	}

	fmt.Println(maxRest)
}

package main

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

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

func p(a ...interface{})                { fmt.Fprint(writer, a...) }
func pln(a ...interface{})              { fmt.Fprintln(writer, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

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

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

func main() {
	defer writer.Flush()
	var n, a int
	m := 0
	first, set := 0, false
	current := 0

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

	for i := 0; i < n; i++ {
		scan(&a)

		if a == 0 {
			m = max(m, current)
			if !set {
				first = current
				set = true
			}
			current = 0
		} else {
			current++
		}
	}
	m = max(m, current)
	if current > 0 {
		m = max(m, current+first)
	}

	pln(m)
	return
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(reader, &n)
	arr := make([]int, n)

	var bk []int
	var lm bool
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &arr[i])
		if arr[i] == 0 && !lm {
			bk = append(bk, arr[:i]...)
			lm = true
		}
	}

	arr = append(arr, bk...)
	// fmt.Println(arr)
	var mx int
	var count int
	for _, vl := range arr {
		if vl == 1 {
			count++
		} else {
			mx = max(mx, count)
			count = 0
		}
	}

	fmt.Println(max(mx, count))
}

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

package main

import "fmt"
import "math"

func main() {
	var n int
	fmt.Scan(&n)
	var a []int = make([]int, n*2)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
		a[i+n] = a[i]
	}
	var count, max float64 = 0, 0
	for i := 0; i < 2*n; i++ {
		if a[i] == 1 {
			count += 1
			max = math.Max(max, count)
		} else {
			count = 0
		}
	}
	fmt.Print(max)
}

// Author: sighduck
// URL: https://codeforces.com/contest/1141/problem/B

package main

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

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

func _Solve(a []int, i int, n int, currentRun int, maxRun int) int {
	if i == 2*n {
		return maxRun
	}
	if a[i%n] == 1 {
		return _Solve(a, i+1, n, currentRun+1, max(currentRun+1, maxRun))
	}
	return _Solve(a, i+1, n, 0, max(currentRun, maxRun))
}

func Solve(n int, a []int) int {
	return _Solve(a, 0, n, 0, 0)
}

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

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

	fmt.Fprintf(writer, "%d\n", Solve(n, a))
}

package main

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

func getMaxRestingHours(a []bool) int {
	var max, current int

	// Process every element of the slice
	for _, b := range a {
		if b {
			current++
		} else if current != 0 {
			if current > max {
				max = current
			}
			current = 0
		}
	}

	// If we ended on a streak
	if current != 0 {
		// Continue on the beginning of the array until we hit a false
		for _, b := range a {
			if b {
				current++
			} else {
				break
			}
		}
		// Update max
		if current > max {
			max = current
		}
	}

	return max
}

func main() {
	// Read input array
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan() // Ignore first line
	scanner.Scan()
	astr := strings.Fields(scanner.Text())
	a := make([]bool, len(astr))
	for i, s := range astr {
		a[i] = (s == "1")
	}

	// Do the thing
	m := getMaxRestingHours(a)
	fmt.Println(m)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(reader, &n)
	arr := make([]int, n)

	var bk []int
	var lm bool
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &arr[i])
		if arr[i] == 0 && !lm {
			bk = append(bk, arr[:i]...)
		}
	}

	arr = append(arr, bk...)

	var mx int
	var count int
	for _, vl := range arr {
		if vl == 1 {
			count++
		} else {
			mx = max(mx, count)
			count = 0
		}
	}

	fmt.Println(mx)
}

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