package main

import "fmt"

func main() {
	var n, k int
	start := 0
	fmt.Scan(&n, &k)
	a := make([]int, n)
	state := make([]int, n)
	tmp := make([]int, 5000000)
	tmp[0] = 0
	loopLength := 0

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

	for i := 0; i < k; i++ {
		start = a[start] - 1
		tmp[i+1] = start
		if state[start] == 1 {
			for j := 0; j < len(tmp); j++ {
				if tmp[j] == start {
					tmp = tmp[j : i+1]
					loopLength = len(tmp)
					break
				}
			}
			fmt.Println(tmp[(k-i-1)%loopLength] + 1)
			return
		} else {
			state[start] = 1
		}
	}
	println(start + 1)
}


package main

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

func main() {
	io := NewIo()
	defer io.Flush()

	// PARSE HELPER SESSION

	// STR := io.Next()
	// Log("string", STR)

	// F := io.NextFloat()
	// Log("float", F)

	// parsing int array
	N := io.NextInt()
	Logf("%v\n", N)
	K := io.NextInt()
	Logf("%v\n", K)
	var A [200000]int
	for i := 0 ; i < N; i++ {
		A[i] = io.NextInt()-1
	}
	Logf("A %v\n", A[0:10])
	// sort.Sort(sort.Reverse(sort.IntSlice(A[:])))
	// sort.Sort(sort.IntSlice(A[:]))

	// find loop
	enterloop:=0
	loop:=0
	place:=0
	var visited [200000]int
	cache := []int{0}
	for i:=0;i<N;i++{
		if visited[place] == 0 {
			loop++
			visited[place] = loop
			place = A[place]
			cache = append(cache, place)
		} else {
			enterloop = loop - visited[place]
			loop = loop - enterloop
			Logf("found loop %d %d %d\n", enterloop, place, loop)
			break
		}
	}
	Logf("loop %v\n", enterloop)
	Logf("loop %v\n", loop)
	Logf("cache %v\n", cache)
	if K < len(cache) {
		fmt.Printf("%v\n", cache[K]+1)
	} else {
		Logf("%v\n", (K-enterloop)%loop)
		fmt.Printf("%v\n", cache[enterloop+(K-enterloop)%loop]+1)
	}
	os.Exit(0)

	place=0
	if K > enterloop {
		for i:=0;i< enterloop + ((K-enterloop) % loop) ;i++ {
			place = A[place]
		}
	} else {
		Logf("a \n")
		for i:=0;i< K ;i++ {
			place = A[place]
		}
	}
	fmt.Printf("%v\n",place+1)

	// parsing string as byte array
	// var s [10000]byte
	// var si [10000]int
	// str := io.Next()
	// for i := 0; i < len(str); i++ {
	// 	s[i] = str[i]
	//  // "0" = 48, "A" = 65, "a" = 97
	//  si[i] = int(str[i]) - 48
	// }
	// Log("byte array", s[0:10])

	// OUTPUT GENERATION PART
	// ans := 0
	// fmt.Printf("%v\n", ans)

	// if ans > 0 {
	//   fmt.Printf("Yes\n")
	// } else {
	//   fmt.Printf("No\n")
	// }

	// BFS/DFS PART
	// visited := []int{}
	// bfs/dfs(1, neighbor, func(node int) {
	// 	visited = append(visited, node)
	// })
	// fmt.Println(visited)

	// DFS 2
	// var dp [2000000]int
	// nei := make(map[int][]int)
	// nei[0] = []int{1, 2}
	// nei[1] = []int{0}
	// nei[2] = []int{0, 3}
	// nei[3] = []int{2}
	// dfs2(0, nei, func(n, p int) {
	// 	Logf("%v -> %v\n", p, n)
	// 	dp[n] = p
	// }, func(n, p int) {
	// 	Logf("%v -> %v\n", n, p)
	// })
	// Logf("%v\n", dp[0:5])

	// COMBINATION
	// fmt.Printf("%d %d %d\n", N, M, intMax(N, M))
	// fmt.Printf("Lucas %d %d\n", combMod(N, M, 13), combination(N, M))
}

// Libraries

// Io helps parsing inputs from standard input for programming contest.
type Io struct {
	reader    *bufio.Reader
	writer    *bufio.Writer
	tokens    []string
	nextToken int
}

// NewIo generates Io instance.
func NewIo() *Io {
	return &Io{
		reader: bufio.NewReader(os.Stdin),
		writer: bufio.NewWriter(os.Stdout),
	}
}

// Flush flushes buffer. Don't forget to do this when you call Io.Printf/Io.PrintLn for final output.
func (io *Io) Flush() {
	err := io.writer.Flush()
	if err != nil {
		panic(err)
	}
}

// NextLine parses line as string.
func (io *Io) NextLine() string {
	var buffer []byte
	for {
		line, isPrefix, err := io.reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer = append(buffer, line...)
		if !isPrefix {
			break
		}
	}
	return string(buffer)
}

// Next parse next word as string.
func (io *Io) Next() string {
	for io.nextToken >= len(io.tokens) {
		line := io.NextLine()
		io.tokens = strings.Fields(line)
		io.nextToken = 0
	}
	r := io.tokens[io.nextToken]
	io.nextToken++
	return r
}

// NextInt parse next word as Int.
func (io *Io) NextInt() int {
	i, err := strconv.Atoi(io.Next())
	if err != nil {
		panic(err)
	}
	return i
}

// NextFloat parses next word as float64.
func (io *Io) NextFloat() float64 {
	i, err := strconv.ParseFloat(io.Next(), 64)
	if err != nil {
		panic(err)
	}
	return i
}

// PrintLn does buffer write with linefeed.
func (io *Io) PrintLn(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}

// Printf does formatted buffer write.
func (io *Io) Printf(format string, a ...interface{}) {
	fmt.Fprintf(io.writer, format, a...)
}

// PrintIntLn prints Int array in a single line.
func (io *Io) PrintIntLn(a []int) {
	b := []interface{}{}
	for _, x := range a {
		b = append(b, x)
	}
	io.PrintLn(b...)
}

// PrintStringLn prints string array in a single line.
func (io *Io) PrintStringLn(a []string) {
	b := []interface{}{}
	for _, x := range a {
		b = append(b, x)
	}
	io.PrintLn(b...)
}

// Log print single value to standard output (contest server ignores this so you don't have to remove when finishing)
func Log(name string, value interface{}) {
	fmt.Fprintf(os.Stderr, "%s=%+v\n", name, value)
}

// Logf print formatted output to standard output (contest server ignores this so you don't have to remove when finishing)
func Logf(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

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

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

// direct calculation of combination
// n, m should be "small"
func combination(n, m int) int {
	if m > n {
		return 0
	} else if m == n || m == 0 {
		return 1
	} else {
		res := 1
		for i := 0; i < m; i++ {
			res *= (n - i)
		}
		for i := 1; i <= m; i++ {
			res /= i
		}
		return res
	}
}

// caluclate combination modulo based on Lucas theorem
func lucas(n, m, p int) int {
	ntemp := n
	mtemp := m
	res := 1
	for i := 0; i < 100; i++ {
		// fmt.Printf("ntemp: %d\n", ntemp)
		nreminder := ntemp % p
		ntemp = ntemp / p
		mreminder := mtemp % p
		mtemp = mtemp / p
		res = res * (combination(nreminder, mreminder) % p)
		if ntemp == 0 {
			break
		}
	}
	return res % p
}

func combMod(n, m, p int) int {
	return lucas(n, m, p)
}

func bfs(start int, nodes map[int][]int, fn func(int)) {
	frontier := []int{start}
	visited := map[int]bool{}
	next := []int{}

	for 0 < len(frontier) {
		next = []int{}
		for _, node := range frontier {
			visited[node] = true
			fn(node)
			for _, n := range bfsFrontier(node, nodes, visited) {
				next = append(next, n)
			}
		}
		frontier = next
	}
}

func bfsFrontier(node int, nodes map[int][]int, visited map[int]bool) []int {
	next := []int{}
	iter := func(n int) bool { _, ok := visited[n]; return !ok }
	for _, n := range nodes[node] {
		if iter(n) {
			next = append(next, n)
		}
	}
	return next
}

func dfs(node int, nodes map[int][]int, fn func(int)) {
	dfsRecur(node, nodes, map[int]bool{}, fn)
}

func dfsRecur(node int, nodes map[int][]int, v map[int]bool, fn func(int)) {
	v[node] = true
	fn(node)
	for _, n := range nodes[node] {
		if _, ok := v[n]; !ok {
			dfsRecur(n, nodes, v, fn)
		}
	}
}

// handles 2 function, one is before entering child tree, and another is
// after entering child tree.
func dfs2(node int, nodes map[int][]int, fn1, fn2 func(int, int)) {
	dfs2Recur(node, -1, nodes, map[int]bool{}, fn1, fn2)
}

func dfs2Recur(node, parent int, nodes map[int][]int, v map[int]bool, fn1, fn2 func(int, int)) {
	v[node] = true
	if fn1 != nil {
		fn1(node, parent)
	}
	for _, n := range nodes[node] {
		if _, ok := v[n]; !ok {
			dfs2Recur(n, node, nodes, v, fn1, fn2)
		}
	}
	if fn2 != nil {
		fn2(node, parent)
	}
}

// Stack data structure
type Stack struct {
	top  *Element
	size int
}

// Element is a struct for stack element
type Element struct {
	value interface{}
	next  *Element
}

// Len returns stack height
func (s *Stack) Len() int {
	return s.size
}

// Push put a element on the stack.
func (s *Stack) Push(value interface{}) {
	s.top = &Element{value, s.top}
	s.size++
}

// Pop picks out the last element from the stack.
func (s *Stack) Pop() (value interface{}) {
	if s.size > 0 {
		value, s.top = s.top.value, s.top.next
		s.size--
		return
	}
	return nil
}

// powerInt (use math.Pow() for float parameters)
func powerInt(n, p int) int {
	tmp := 1
	for i := 0; i < n; i++ {
		tmp *= p
	}
	return tmp
}

func findDivisors(n int, a *[]int) {
	if n == 1 {
		return
	}

	sqrt := int(math.Sqrt(float64(n)))
	for i := 2; i <= sqrt; i++ {
		if n%i == 0 {
			*a = append(*a, i)
			*a = append(*a, n/i)
		}
	}
	*a = append(*a, n)
}

func removeDuplicate(a []int) []int {
	m := make(map[int]bool)
	for i := 0; i < len(a); i++ {
		m[a[i]] = true
	}
	res := []int{}
	for i := range m {
		res = append(res, i)
	}
	return res
}

// var gcdmap map[int](map[int]int)
// func gcd(a, b int) int {
// 	ina := a
// 	inb := b
// 	if _, ok := gcdmap[a]; !ok {
// 		gcdmap[a] = make(map[int]int)
// 	}
// 	if _, ok := gcdmap[ina][inb]; ok {
// 		return gcdmap[ina][inb]
// 	}
// 	for b != 0 {
// 		t := b
// 		b = a % b
// 		a = t
// 	}
// 	gcdmap[ina][inb] = a
// 	return a
// }

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score: 400 points

Problem Statement

The Kingdom of Takahashi has N towns, numbered 1 through N.

There is one teleporter in each town. The teleporter in Town i (1 \leq i \leq N) sends you to Town A_i.

Takahashi, the king, loves the positive integer K. The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Help the king by writing a program that answers this question.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq N

1 \leq K \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

Print the integer representing the town the king will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Sample Input 1

4 5
3 2 4 1

Sample Output 1

4

If we start at Town 1 and use the teleporter 5 times, our travel will be as follows: 1 \to 3 \to 4 \to 1 \to 3 \to 4.

Sample Input 2

6 727202214173249351
6 5 2 5 3 2

Sample Output 2

2

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"math"
	"os"
	"strconv"
)

const (
	initialBufSize = 10000
	maxBufSize     = 1000000
	mod            = 1e9 + 7
)

var (
	sc *bufio.Scanner = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, initialBufSize)
		sc.Buffer(buf, maxBufSize)
		sc.Split(bufio.ScanWords)
		return sc
	}()
)

func main() {
	N := getInt()
	K := getInt()

	g := NewGraph(N)

	for i := 0; i < N; i++ {
		a := getInt() - 1
		g.AddEdge(i, a)
	}

	visited := make(map[int]struct{})
	var route []int

	dfs(0, g.edges, visited, &route)

	loopStart := g.edges[route[len(route) - 1]][0]

	onceCnt := 0
	loopCnt := 0
	for i, v := range route {
		if v == loopStart {
			onceCnt = i
			loopCnt = len(route) - i
			break
		}
	}

	result := 0

	if onceCnt == len(route) - 1{
		result = route[K] + 1
	} else {
		if K < onceCnt {
			result = route[K] + 1
		} else {
			rest := (K - onceCnt) % loopCnt
			result = route[onceCnt + rest] + 1
		}
	}

	fmt.Println(result)
}

type Graph struct {
	n         int
	edges     [][]int
	distances []int
}

func NewGraph(n int) *Graph {
	g := &Graph{
		n:         n,
		edges:     make([][]int, n),
		distances: make([]int, n),
	}
	return g
}

func (g *Graph) AddEdge(u, v int) {
	//g.edges[v] = append(g.edges[v], u)
	g.edges[u] = append(g.edges[u], v)
}

func dfs(c int, edges [][]int, visited map[int]struct{}, route *[]int) {
	visited[c] = struct{}{}
	*route = append(*route, c)

	for _, v := range edges[c] {
		_, flag := visited[v]
		if flag {
			continue
		}
		dfs(v, edges, visited, route)
	}
}

func bfs(c int, graph *Graph) {
	next := make([]int, 0)
	next = append(next, c)
	visited := make(map[int]struct{})

	for ; len(next) != 0; {
		u := next[0]
		next = next[1:]
		visited[u] = struct{}{}

		for _, v := range graph.edges[u] {
			_, flag := visited[v]
			if flag {
				continue
			}

			next = append(next, v)
		}
	}
}

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getIntArray(n int) []int {
	array := make([]int, n)
	for i := 0; i < n; i++ {
		array[i] = getInt()
	}
	return array
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

func getStringArray(n int) []string {
	array := make([]string, n)
	for i := 0; i < n; i++ {
		array[i] = getString()
	}
	return array
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func powMod(n, p int) int {
	if p == 0 {
		return 1
	} else if p%2 == 0 {
		t := powMod(n, p/2)
		return calcMod(t * t)
	} else {
		return calcMod(n * powMod(n, p-1))
	}
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func printIntArray(array []int) {
	strArray := fmt.Sprint(array)
	fmt.Println(strArray[1 : len(strArray)-1])
}

func calcMod(x int) int {
	return x % mod
}

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

func isPrime(n int) bool {
	if n < 2 {
		return false
	} else if n == 2 {
		return true
	} else if n%2 == 0 {
		return false
	}

	sqrtN := int(math.Sqrt(float64(n)))
	for i := 3; i <= sqrtN; i += 2 {
		if n%i == 0 {
			return false
		}
	}

	return true
}

func contains(s []int, e int) bool {
	for _, v := range s {
		if e == v {
			return true
		}
	}
	return false
}

func makeRange(min, max int) []int {
	a := make([]int, max-min+1)
	for i := range a {
		a[i] = min + i
	}
	return a
}

func powerset2(nums []int) [][]int {
	length := int(math.Pow(2, float64(len(nums))))
	result := make([][]int, length)

	index := 0
	result[index] = []int{}
	index++

	for _, n := range nums {
		max := index
		for i := 0; i < max; i++ {
			result[index] = copyAndAppend(result[i], n)
			index++
		}
	}

	return result
}

func copyAndAppend(nums []int, n int) []int {
	dst := make([]int, len(nums)+1)
	copy(dst, nums)
	dst[len(nums)] = n
	return dst
}

func calcGcd(x, y int) int {
	if y == 0 {
		return x
	} else if x >= y {
		return calcGcd(y, x%y)
	} else {
		return calcGcd(x, y%x)
	}
}

func getDivisor(n int) []int {
	divisor := make(map[int]struct{})
	divisor[1] = struct{}{}
	if n != 1 {
		divisor[n] = struct{}{}
	}

	sqrt := int(math.Sqrt(float64(n)))
	for i := 2; i <= sqrt; i++ {
		if n%i == 0 {
			divisor[i] = struct{}{}
			divisor[n/i] = struct{}{}
		}
	}

	var divisorArray []int
	for d := range divisor {
		divisorArray = append(divisorArray, d)
	}
	return divisorArray
}

type intHeap []int

func (h intHeap) Len() int {
	return len(h)
}

func (h intHeap) Less(i, j int) bool {
	return h[i] > h[j]
}

func (h intHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *intHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *intHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func initHeap() *intHeap {
	ih := &intHeap{}
	heap.Init(ih)
	return ih
}

func (h *intHeap) pushHeap(n int) {
	heap.Push(h, n)
}

func (h *intHeap) popHeap() int {
	return heap.Pop(h).(int)
}

func factMod(n int) int {
	value := 1
	for ; n > 1; n-- {
		value = calcMod(value * n)
	}
	return value
}

func combinationMod(n, k int) int {
	factN := factMod(n)
	factK := factMod(k)
	factNK := factMod(n - k)
	factKR := powMod(factK, mod-2)
	factNKR := powMod(factNK, mod-2)
	return calcMod(factN * calcMod(factKR*factNKR))
}

func primeFactors(n int) []int {
	factors := make([]int, 0)
	i := 2
	for i*i <= n {
		r := n % i
		if r != 0 {
			i += 1
		} else if r == 0 {
			n /= i
			factors = append(factors, i)
		}
	}
	if n > 1 {
		factors = append(factors, n)
	}
	return factors
}


package main

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

type town struct {
	a int
	b int
}

func main() {
	n := readi()
	k := readi()
	aa := make([]town, n)
	for i := range aa {
		fmt.Scan(&aa[i].a)
	}
	var t, t2, t3, i int
	for ; i < k; i++ {
		if t2 == 0 && aa[t].b == 2 {
			t2 = i
		}
		if aa[t].b == 3 {
			t3 = i
			m := (k - t2) % (t3-t2)
			for i = 0; i < m; i++ {
				t = aa[t].a-1
			}
			fmt.Println(t+1)
			return
		}
		aa[t].b++
		t = aa[t].a-1
	}
	fmt.Println(t+1)
}

// IO---------------------------------------------------

func readi() (n int) {
	fmt.Scan(&n)
	return
}

func readf() (n float64) {
	fmt.Scan(&n)
	return
}

func reads() (n string) {
	fmt.Scan(&n)
	return
}

var rdr = bufio.NewReaderSize(os.Stdin, 1000000)

func readLine() string {
	buf := make([]byte, 0, 1000000)
	for {
		l, p, e := rdr.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}

func readSlice() []string {
	return strings.Split(readLine(), " ")
}

func atoi(a []string) (b []int) {
	b = make([]int, len(a))
	for i := range a {
		b[i], _ = strconv.Atoi(a[i])
	}
	return
}

func atof(a []string) (b []float64) {
	b = make([]float64, len(a))
	for i := range a {
		b[i], _ = strconv.ParseFloat(a[i], 64)
	}
	return
}

func readSlice2(n int) (a []int, b []int) {
	a = make([]int, n)
	b = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i], &b[i])
	}
	return
}

func readFloatSlice2(n int) (a []float64, b []float64) {
	a = make([]float64, n)
	b = make([]float64, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i], &b[i])
	}
	return
}

func yesOrNo(b bool) {
	if b {
		fmt.Println("Yes")
		return
	}
	fmt.Println("No")
}

func yesorNO(b bool) {
	if b {
		fmt.Println("YES")
		return
	}
	fmt.Println("NO")
}

func yesorno(b bool) {
	if b {
		fmt.Println("yes")
		return
	}
	fmt.Println("no")
}

// calc---------------------------------------------------

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

func ave(a []int) (ave int) {
	for i := 0; i < len(a); i++ {
		ave += a[i]
	}
	ave /= len(a)
	return
}

func eq(a []string, b []string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}

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

func max(a ...int) int {
	max := a[0]
	for i := 1; i < len(a); i++ {
		if max < a[i] {
			max = a[i]
		}
	}
	return max
}

func min(a ...int) int {
	min := a[0]
	for i := 1; i < len(a); i++ {
		if min > a[i] {
			min = a[i]
		}
	}
	return min
}

func mid(a []int) int {
	sort.Ints(a)
	return a[len(a)/2]
}

func sum(a []int) (ans int) {
	for i := range a {
		ans += a[i]
	}
	return
}


package main

import "fmt"

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

	as := make([]int, n+1)
	for i := 1; i <= n; i++ {
		fmt.Scan(&as[i])
	}

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

	cur := 1
	for i := 1; i <= k; i++ {
		cur = as[cur]
		if ds[cur] == 0 {
			ds[cur] = i
			continue
		}

		d := i - ds[cur]
		if d <= k-i {
			i += (k - i) / d * d
		}
	}

	fmt.Println(cur)
}


package main

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

func main() {
	io := NewIo()
	defer io.Flush()

	// PARSE HELPER SESSION

	// STR := io.Next()
	// Log("string", STR)

	// F := io.NextFloat()
	// Log("float", F)

	// parsing int array
	N := io.NextInt()
	Logf("%v\n", N)
	K := io.NextInt()
	Logf("%v\n", K)
	var A [200000]int
	for i := 0 ; i < N; i++ {
		A[i] = io.NextInt()-1
	}
	Logf("A %v\n", A[0:10])
	// sort.Sort(sort.Reverse(sort.IntSlice(A[:])))
	// sort.Sort(sort.IntSlice(A[:]))

	// find loop
	enterloop:=0
	loop:=1
	place:=0
	var visited [200000]int
	for i:=0;i<N;i++{
		if visited[place] == 0 {
			visited[place] = loop
			place = A[place]
			loop++
		} else {
			enterloop = loop - visited[place] - 1
			loop = loop - enterloop - 1
			Logf("found loop %d %d %d\n", enterloop, place, loop)
			break
		}
	}
	Logf("loop %v\n", enterloop)
	Logf("loop %v\n", loop)

	place=0
	for i:=0;i< enterloop + ((K-enterloop) % loop) ;i++ {
		place = A[place]
	}
	fmt.Printf("%v\n",place+1)

	// parsing string as byte array
	// var s [10000]byte
	// var si [10000]int
	// str := io.Next()
	// for i := 0; i < len(str); i++ {
	// 	s[i] = str[i]
	//  // "0" = 48, "A" = 65, "a" = 97
	//  si[i] = int(str[i]) - 48
	// }
	// Log("byte array", s[0:10])

	// OUTPUT GENERATION PART
	// ans := 0
	// fmt.Printf("%v\n", ans)

	// if ans > 0 {
	//   fmt.Printf("Yes\n")
	// } else {
	//   fmt.Printf("No\n")
	// }

	// BFS/DFS PART
	// visited := []int{}
	// bfs/dfs(1, neighbor, func(node int) {
	// 	visited = append(visited, node)
	// })
	// fmt.Println(visited)

	// DFS 2
	// var dp [2000000]int
	// nei := make(map[int][]int)
	// nei[0] = []int{1, 2}
	// nei[1] = []int{0}
	// nei[2] = []int{0, 3}
	// nei[3] = []int{2}
	// dfs2(0, nei, func(n, p int) {
	// 	Logf("%v -> %v\n", p, n)
	// 	dp[n] = p
	// }, func(n, p int) {
	// 	Logf("%v -> %v\n", n, p)
	// })
	// Logf("%v\n", dp[0:5])

	// COMBINATION
	// fmt.Printf("%d %d %d\n", N, M, intMax(N, M))
	// fmt.Printf("Lucas %d %d\n", combMod(N, M, 13), combination(N, M))
}

// Libraries

// Io helps parsing inputs from standard input for programming contest.
type Io struct {
	reader    *bufio.Reader
	writer    *bufio.Writer
	tokens    []string
	nextToken int
}

// NewIo generates Io instance.
func NewIo() *Io {
	return &Io{
		reader: bufio.NewReader(os.Stdin),
		writer: bufio.NewWriter(os.Stdout),
	}
}

// Flush flushes buffer. Don't forget to do this when you call Io.Printf/Io.PrintLn for final output.
func (io *Io) Flush() {
	err := io.writer.Flush()
	if err != nil {
		panic(err)
	}
}

// NextLine parses line as string.
func (io *Io) NextLine() string {
	var buffer []byte
	for {
		line, isPrefix, err := io.reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer = append(buffer, line...)
		if !isPrefix {
			break
		}
	}
	return string(buffer)
}

// Next parse next word as string.
func (io *Io) Next() string {
	for io.nextToken >= len(io.tokens) {
		line := io.NextLine()
		io.tokens = strings.Fields(line)
		io.nextToken = 0
	}
	r := io.tokens[io.nextToken]
	io.nextToken++
	return r
}

// NextInt parse next word as Int.
func (io *Io) NextInt() int {
	i, err := strconv.Atoi(io.Next())
	if err != nil {
		panic(err)
	}
	return i
}

// NextFloat parses next word as float64.
func (io *Io) NextFloat() float64 {
	i, err := strconv.ParseFloat(io.Next(), 64)
	if err != nil {
		panic(err)
	}
	return i
}

// PrintLn does buffer write with linefeed.
func (io *Io) PrintLn(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}

// Printf does formatted buffer write.
func (io *Io) Printf(format string, a ...interface{}) {
	fmt.Fprintf(io.writer, format, a...)
}

// PrintIntLn prints Int array in a single line.
func (io *Io) PrintIntLn(a []int) {
	b := []interface{}{}
	for _, x := range a {
		b = append(b, x)
	}
	io.PrintLn(b...)
}

// PrintStringLn prints string array in a single line.
func (io *Io) PrintStringLn(a []string) {
	b := []interface{}{}
	for _, x := range a {
		b = append(b, x)
	}
	io.PrintLn(b...)
}

// Log print single value to standard output (contest server ignores this so you don't have to remove when finishing)
func Log(name string, value interface{}) {
	fmt.Fprintf(os.Stderr, "%s=%+v\n", name, value)
}

// Logf print formatted output to standard output (contest server ignores this so you don't have to remove when finishing)
func Logf(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

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

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

// direct calculation of combination
// n, m should be "small"
func combination(n, m int) int {
	if m > n {
		return 0
	} else if m == n || m == 0 {
		return 1
	} else {
		res := 1
		for i := 0; i < m; i++ {
			res *= (n - i)
		}
		for i := 1; i <= m; i++ {
			res /= i
		}
		return res
	}
}

// caluclate combination modulo based on Lucas theorem
func lucas(n, m, p int) int {
	ntemp := n
	mtemp := m
	res := 1
	for i := 0; i < 100; i++ {
		// fmt.Printf("ntemp: %d\n", ntemp)
		nreminder := ntemp % p
		ntemp = ntemp / p
		mreminder := mtemp % p
		mtemp = mtemp / p
		res = res * (combination(nreminder, mreminder) % p)
		if ntemp == 0 {
			break
		}
	}
	return res % p
}

func combMod(n, m, p int) int {
	return lucas(n, m, p)
}

func bfs(start int, nodes map[int][]int, fn func(int)) {
	frontier := []int{start}
	visited := map[int]bool{}
	next := []int{}

	for 0 < len(frontier) {
		next = []int{}
		for _, node := range frontier {
			visited[node] = true
			fn(node)
			for _, n := range bfsFrontier(node, nodes, visited) {
				next = append(next, n)
			}
		}
		frontier = next
	}
}

func bfsFrontier(node int, nodes map[int][]int, visited map[int]bool) []int {
	next := []int{}
	iter := func(n int) bool { _, ok := visited[n]; return !ok }
	for _, n := range nodes[node] {
		if iter(n) {
			next = append(next, n)
		}
	}
	return next
}

func dfs(node int, nodes map[int][]int, fn func(int)) {
	dfsRecur(node, nodes, map[int]bool{}, fn)
}

func dfsRecur(node int, nodes map[int][]int, v map[int]bool, fn func(int)) {
	v[node] = true
	fn(node)
	for _, n := range nodes[node] {
		if _, ok := v[n]; !ok {
			dfsRecur(n, nodes, v, fn)
		}
	}
}

// handles 2 function, one is before entering child tree, and another is
// after entering child tree.
func dfs2(node int, nodes map[int][]int, fn1, fn2 func(int, int)) {
	dfs2Recur(node, -1, nodes, map[int]bool{}, fn1, fn2)
}

func dfs2Recur(node, parent int, nodes map[int][]int, v map[int]bool, fn1, fn2 func(int, int)) {
	v[node] = true
	if fn1 != nil {
		fn1(node, parent)
	}
	for _, n := range nodes[node] {
		if _, ok := v[n]; !ok {
			dfs2Recur(n, node, nodes, v, fn1, fn2)
		}
	}
	if fn2 != nil {
		fn2(node, parent)
	}
}

// Stack data structure
type Stack struct {
	top  *Element
	size int
}

// Element is a struct for stack element
type Element struct {
	value interface{}
	next  *Element
}

// Len returns stack height
func (s *Stack) Len() int {
	return s.size
}

// Push put a element on the stack.
func (s *Stack) Push(value interface{}) {
	s.top = &Element{value, s.top}
	s.size++
}

// Pop picks out the last element from the stack.
func (s *Stack) Pop() (value interface{}) {
	if s.size > 0 {
		value, s.top = s.top.value, s.top.next
		s.size--
		return
	}
	return nil
}

// powerInt (use math.Pow() for float parameters)
func powerInt(n, p int) int {
	tmp := 1
	for i := 0; i < n; i++ {
		tmp *= p
	}
	return tmp
}

func findDivisors(n int, a *[]int) {
	if n == 1 {
		return
	}

	sqrt := int(math.Sqrt(float64(n)))
	for i := 2; i <= sqrt; i++ {
		if n%i == 0 {
			*a = append(*a, i)
			*a = append(*a, n/i)
		}
	}
	*a = append(*a, n)
}

func removeDuplicate(a []int) []int {
	m := make(map[int]bool)
	for i := 0; i < len(a); i++ {
		m[a[i]] = true
	}
	res := []int{}
	for i := range m {
		res = append(res, i)
	}
	return res
}

// var gcdmap map[int](map[int]int)
// func gcd(a, b int) int {
// 	ina := a
// 	inb := b
// 	if _, ok := gcdmap[a]; !ok {
// 		gcdmap[a] = make(map[int]int)
// 	}
// 	if _, ok := gcdmap[ina][inb]; ok {
// 		return gcdmap[ina][inb]
// 	}
// 	for b != 0 {
// 		t := b
// 		b = a % b
// 		a = t
// 	}
// 	gcdmap[ina][inb] = a
// 	return a
// }


package main

import "fmt"

func main() {
	var a, b, c, d int
	fmt.Scan(&a, &b, &c, &d)

	for {
		if c <= 0 {
			fmt.Println("Yes")
			break
		} else {
			c -= b
		}

		if a <= 0 {
			fmt.Println("No")
			break
		} else {
			a -= d
		}
	}
}

Score : 200 points

Problem Statement

Takahashi and Aoki will have a battle using their monsters.

The health and strength of Takahashi's monster are A and B, respectively, and those of Aoki's monster are C and D, respectively.

The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ...
Here, an attack decreases the opponent's health by the value equal to the attacker's strength.
The monsters keep attacking until the health of one monster becomes 0 or below. The person with the monster whose health becomes 0 or below loses, and the other person wins.

If Takahashi will win, print Yes; if he will lose, print No.

Constraints

1 \leq A,B,C,D \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

If Takahashi will win, print Yes; if he will lose, print No.

Sample Input 1

10 9 10 10

Sample Output 1

No

First, Takahashi's monster attacks Aoki's monster, whose health is now 10-9=1.

Next, Aoki's monster attacks Takahashi's monster, whose health is now 10-10=0.

Takahashi's monster is the first to have 0 or less health, so Takahashi loses.

Sample Input 2

46 4 40 5

Sample Output 2

Yes


package main

import "fmt"

func main(){
	var A, B int
	var C, D int
	var f = 0

	fmt.Scan(&A, &B);
	fmt.Scan(&C, &D);

	for {
		C -= B
		if C <= 0 {
			f = 1;
			break;
		}
		A -= D
		if A <= 0 {
			f = 2;
			break;
		}
	}
	if f == 1 {
		fmt.Println("Yes");
	}else{
		fmt.Println("No");
	}
}


package main

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

func main() {
	sc.Split(bufio.ScanWords)
	var A, B, C, D int
	nextInt(&A, &B, &C, &D)
	var step int
	for A > 0 && C > 0 {
		if step % 2 == 0 {
			C-=B
		} else {
			A-=D
		}
		step++
	}
	if A <= 0 {
		fmt.Printf("No")
	} else {
		fmt.Printf("Yes")
	}
}

const MAX_INT int = 1_000_000_000

var sc = bufio.NewScanner(os.Stdin)

var reader = bufio.NewReaderSize(os.Stdin, 1000000)
var writer = bufio.NewWriter(os.Stdout)

func nextLine() string {
	buffer := make([]byte, 0)
	for true {
		line, isPrefix, err := reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer = append(buffer, line...)
		if !isPrefix {
			break
		}
	}
	return string(buffer)
}

func nextInt(A ...*int) {
	L := strings.Split(nextLine(), " ")
	for i, a := range A {
		*a, _ = strconv.Atoi(L[i])
	}
}
func nextInts(A *[]int) {
	L := strings.Split(nextLine(), " ")
	(*A) = make([]int, len(L))
	for i, l := range L {
		(*A)[i], _ = strconv.Atoi(l)
	}
}

func nextInt64(A ...*int64) {
	L := strings.Split(nextLine(), " ")
	for i, a := range A {
		*a, _ = strconv.ParseInt(L[i], 0, 64)
	}
}

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


package main

import (
	"fmt"
)

func main() {
	var A, B, C, D int

	fmt.Scan(&A, &B, &C, &D)

	HT := A / D
	CheckHT := A % D
	HA := C / B

	if HT > HA {
		fmt.Println("Yes")
	} else if HT == HA {
		if CheckHT == 0 {
			fmt.Println("No")
		} else {
			fmt.Println("Yes")
		}
	} else {
		if (HA - HT) == 1 {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}
}


package main

import (
  "fmt"
  "math"
)

func main() {
  var a, b, c, d float64
  fmt.Scanf("%f %f %f %f", &a, &b, &c, &d)
  if math.Ceil(c / b) > math.Ceil(a / d) {
    fmt.Println("No")
  } else {
    fmt.Println("Yes")
  }
}


package main

import (
    "fmt"
)

type Monster struct {
    Hp  int
    Atk int
}

func battle(o, d *Monster) {
    d.Hp -= o.Atk
}

func main() {
    t := new(Monster)
    a := new(Monster)
    fmt.Scanf("%d %d %d %d", &t.Hp, &t.Atk, &a.Hp, &a.Atk)
    //fmt.Printf("t(%d:%d), a(%d:%d)", t.Hp, t.Atk, a.Hp, a.Atk)

    for {
        battle(t, a)
        if t.Hp < 1 {
            fmt.Print("NO\n")
            return
        }

        battle(a, t)
        if a.Hp < 1 {
            fmt.Print("YES\n")
            return
        }
    }
}


package main

import (
    "fmt"
)

type Monster struct {
    Hp  int
    Atk int
}

func battle(o, d *Monster) {
    d.Hp -= o.Atk
}

func main() {
    t := new(Monster)
    a := new(Monster)
    fmt.Scanf("%d %d %d %d", &t.Hp, &t.Atk, &a.Hp, &a.Atk)
    //fmt.Printf("t(%d:%d), a(%d:%d)", t.Hp, t.Atk, a.Hp, a.Atk)

    for {
        battle(t, a)
        if t.Hp < 1 {
            fmt.Print("NO")
            return
        }

        battle(a, t)
        if a.Hp < 1 {
            fmt.Print("YES")
            return
        }
    }
}


package main

import "fmt"

func main() {
	var TakahashiHp, TakahashiForce, AokiHp, AokiForce int
	fmt.Scan(&TakahashiHp, &TakahashiForce, &AokiHp, &AokiForce)

	for {
		AokiHp = AokiHp - TakahashiForce

		if AokiHp <= 0 {
			fmt.Println("Yes")
			return
		}

		TakahashiHp = TakahashiHp - AokiForce

		if TakahashiHp <= 0 {
			fmt.Println("No")
			return
		}
	}
}


package main

import "fmt"

func main() {
	var a, b, c, d int
	fmt.Scan(&a)
	fmt.Scan(&b)
	fmt.Scan(&c)
	fmt.Scan(&d)

	for {
		c -= b
		if c <= 0 {
			fmt.Println("Yes")
			break
		}

		a -= d
		if a <= 0 {
			fmt.Println("No")
			break
		}
	}
}


package main

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

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

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

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

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

func main() {
	sc.Split(bufio.ScanWords)

	A, B, C, D := getInt(), getInt(), getInt(), getInt()

	for {
		C -= B
		if C <= 0 {
			out("Yes")
			return
		}
		A -= D
		if A <= 0 {
			out("No")
			return
		}
	}
}


package main

import (
	"fmt"
	"math"
)

func main() {
	var a, b, c, d float64
	fmt.Scan(&a, &b, &c, &d)

	n := math.Ceil(a / d)
	m := math.Ceil(c / b)
	if n == m {
		fmt.Println("Yes")
	} else if n > m {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}


package main

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

const (
	initialBufSize = 1024
	maxBufSize     = 1e6
)

var (
	scanner = bufio.NewScanner(os.Stdin)
	// writer  = bufio.NewWriterSize(os.Stdout, 1000000)
)

func main() {
	scanner.Split(bufio.ScanWords)
	// scanner.Buffer(make([]byte, initialBufSize), maxBufSize)
	// defer writer.Flush()
	a, b, c, d := scanInt(), scanInt(), scanInt(), scanInt()

	ta := true
	for {
		if ta {
			c = c - b
			if c <= 0 {
				fmt.Println("Yes")
				return
			}
			ta = !ta
		} else {
			a = a - d
			if a <= 0 {
				fmt.Println("No")
				return
			}
			ta = !ta
		}
	}

}

func scanInt() int {
	i, _ := strconv.Atoi(scanString())
	return i
}

func scanInts(size int) []int {
	ints := make([]int, size)
	for i := 0; i < size; i++ {
		ints[i] = scanInt()
	}
	return ints
}

func scanFloat64() float64 {
	f, _ := strconv.ParseFloat(scanString(), 64)
	return f
}

func scanFloat64s(size int) []float64 {
	f := make([]float64, size)
	for i := 0; i < size; i++ {
		f[i] = scanFloat64()
	}
	return f
}

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

func scanStrings(size int) []string {
	s := make([]string, size)
	for i := 0; i < size; i++ {
		s[i] = scanString()
	}
	return s
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func nextString() string {
	sc.Scan()
	return sc.Text()
}

func dfs(s string) int {
	ans := 0
	for i := 0; i < len(s); i++ {
		for j := i + 3; j <= len(s); j++ {
			// fmt.Println(s[i:j])
			num, _ := strconv.Atoi(s[i:j])
			if num%2019 == 0 {
				ans++
			}
		}
	}
	return ans
}

func main() {
	sc.Split(bufio.ScanWords)
	ss := nextString()

	fmt.Println(dfs(ss))
}

Score : 400 points

Problem Statement

Given is a string S consisting of digits from 1 through 9.

Find the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the following condition:

Condition: In base ten, the i-th through j-th characters of S form an integer that is a multiple of 2019.

Constraints

1 ≤ |S| ≤ 200000

S is a string consisting of digits from 1 through 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the condition.

Sample Input 1

1817181712114

Sample Output 1

3

Three pairs - (1,5), (5,9), and (9,13) - satisfy the condition.

Sample Input 2

14282668646

Sample Output 2

2

Sample Input 3

2119

Sample Output 3

0

No pairs satisfy the condition.


package main

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

func main() {
	scanInit()
	s := scan()
	// 1817181712114
	n := len(s)
	Split := strings.Split(s,"")
	m := 2019
	cnt := map[int]int{}
	total := 0
	x := 1
	ans := 0
	for i:= n-1; i>=0; i-- {
		if _,ok := cnt[total]; !ok {
			cnt[total] = 0
		}
		cnt[total] += 1 //S_r ≡ S_l (r,lは任意)なら+1なのでこうなってる　a_0も入ってないもの(s_0)が0なので最初に0に+1
		//　理解が普通にクソムズ　数学的な素養と簡単な累積和的知識が必要
		val,_ := strconv.Atoi(Split[i])
		total += val*x //累積和
		total %= m
		ans += cnt[total]
		x *= 10
	}
	fmt.Println(ans)
}

var sc = bufio.NewScanner(os.Stdin)
func scanInit () {
	sc.Split(bufio.ScanWords)
}
// func scanInt () int{
// sc.Scan()
//	i,_ := strconv.Atoi(sc.Text())
//	return i
//}
func scan () string{
 sc.Scan()
	return sc.Text()
}


package main

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

func scanText() string {
	sc.Buffer([]byte{}, math.MaxInt64)
	sc.Scan()
	return sc.Text()
}

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 sc = bufio.NewScanner(os.Stdin)

func main() {
	N := 2019
	s := reverse(scanText())
	m := map[int]int{}
	total := 0
	d := 1
	m[0] = 1
	for _, c := range s {
		n, _ := strconv.Atoi(string(c))
		total += n * d
		total %= 2019
		d = (d * 10) % N
		m[total]++
	}
	sum := 0
	for _, v := range m {
		sum += v * (v - 1) / 2
	}
	fmt.Println(sum)
}


package main

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

func scanText() string {
	sc.Scan()
	return sc.Text()
}

func reverse(s string) (result string) {
	for _, v := range s {
		result = string(v) + result
	}
	return
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	s := reverse(scanText())
	cnts := map[int]int{}
	sum := 0
	d := 1

	for _, c := range s {
		cn, _ := strconv.Atoi(string(c))
		sum += (cn * d) % 2019
		d = (10 * d) % 2019
		cnts[sum%2019]++
	}

	ans := cnts[0]
	for _, cnt := range cnts {
		ans += cnt * (cnt - 1) / 2
	}
	fmt.Println(ans)
}


package main

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

func scanText() string {
	sc.Scan()
	return sc.Text()
}

func reverse(s string) (result string) {
	for _, v := range s {
		result = string(v) + result
	}
	return
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	s := reverse(scanText())
	cnts := map[int]int{}
	sum := 0
	d := 1

	cnts[0] = 1
	for _, c := range s {
		cn, _ := strconv.Atoi(string(c))
		cn *= d
		sum += cn
		sum %= 2019
		d *= 10
		d %= 2019
		cnts[sum]++
	}

	ans := 0
	for _, cnt := range cnts {
		ans += cnt * (cnt - 1) / 2
	}
	fmt.Println(ans)
}


package main

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

func scanInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}

func scanInt64() int64 {
	sc.Scan()
	i, _ := strconv.ParseInt(sc.Text(), 10, 64)
	return i
}

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

func scanInts64(n int) []int64 {
	res := make([]int64, n)
	for i := range res {
		res[i] = scanInt64()
	}
	return res
}

func scanText() string {
	sc.Scan()
	return sc.Text()
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	var ans int
	s := []rune(scanText())
	for i := 0; i < len(s)-3; i++ {
		for j := i + 4; j < len(s)+1; j++ {
			num, _ := strconv.Atoi(string(s[i:j]))
			if num%2019 == 0 {
				ans++
			}
		}
	}
	fmt.Println(ans)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func nextString() string {
	var s string
	if sc.Scan() {
		s = sc.Text()
	}
	return s
}

func isMultipleOf2019(i int) bool {
	if i%2019 == 0 {
		return true
	} else {
		return false
	}
}

func dfs(s string, start int) {
	if (len(s) - start) <= 0 {
		return
	}
	lastIndex := start + 4
	for ; lastIndex <= len(s); lastIndex++ {
		v := s[start:lastIndex]
		num, _ := strconv.Atoi(v)
		if isMultipleOf2019(num) {
			multipleOf2019++
		}
	}
	dfs(s, start+1)
}

var multipleOf2019 int

func main() {
	sc.Split(bufio.ScanWords)
	s := nextString()
	if len(s) < 4 {
		fmt.Println(0)
		return
	}
	dfs(s, 0)
	fmt.Println(multipleOf2019)
}


package main

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

func main() {
	scanner := makeScanner(20000000)
	str := String(eGetLine(scanner))
	s := str.revese()
	n := 0
	d := 1
	var counts [2019]int
	counts[0] = 1
	for i := 0; i < len(s); i++ {
		c := eAtoi(string(s[i]))
		n = n + c*d
		counts[n%2019]++
		d *= 10
	}
	sum := 0
	for _, v := range counts {
		if v != 0 {
			sum += v * (v - 1) / 2
		}
	}
	fmt.Println(sum)
}

////////////////////////////////////////////////////////////////////////////////
// ライブラリ
////////////////////////////////////////////////////////////////////////////////
const (
	TooLarge = math.MaxInt64
	TooSmall = math.MinInt64
)

func makeScanner(maxByte int) *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]uint8, 0, 8192), maxByte)
	return scanner
}
func makeCharScanner() *bufio.Scanner {
	scanner := makeScanner(8192)
	scanner.Split(bufio.ScanRunes)
	return scanner
}
func makeWordScanner() *bufio.Scanner {
	scanner := makeScanner(8192)
	scanner.Split(bufio.ScanWords)
	return scanner
}
func eGetLine(r *bufio.Scanner) string {
	if r.Scan() {
		return r.Text()
	}
	err := r.Err()
	if err != nil {
		log.Fatal(err)
	}
	// EOF
	return ""
}
func eGetInt(r *bufio.Scanner) int {
	line := eGetLine(r)
	return eAtoi(line)
}
func eGetInt64(r *bufio.Scanner) int64 {
	line := eGetLine(r)
	return eAtoInt64(line)
}
func eGetFields(r *bufio.Scanner) []string {
	line := eGetLine(r)
	return strings.Fields(line)
}
func eGetInts(r *bufio.Scanner) []int {
	fields := eGetFields(r)
	ints := make([]int, len(fields))
	for i := 0; i < len(ints); i++ {
		ints[i] = eAtoi(fields[i])
	}
	return ints
}
func eGetInt64s(r *bufio.Scanner) []int64 {
	fields := eGetFields(r)
	ints := make([]int64, len(fields))
	for i := 0; i < len(ints); i++ {
		ints[i] = eAtoInt64(fields[i])
	}
	return ints
}
func eGetChars(r *bufio.Scanner) []string {
	line := eGetLine(r)
	return strings.Split(line, "")
}
func eAtoi(s string) int {
	n, err := strconv.Atoi(s)
	if err != nil {
		log.Fatal(err)
	}
	return n
}
func eAtoInt64(s string) int64 {
	n, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		log.Fatal(err)
	}
	return n
}
func pow(a, n int) int {
	if n == 0 {
		return 1
	}
	if n == 1 {
		return a
	}
	if n%2 == 1 {
		return pow((a*a), n/2) * a
	}
	return pow((a * a), n/2)
}
func powMod(a, n, mod int) int {
	if n == 0 {
		return 1 % mod
	}
	if n == 1 {
		return a % mod
	}
	if n%2 == 1 {
		return powMod((a*a)%mod, n/2, mod) * a % mod
	}
	return powMod((a*a)%mod, n/2, mod)
}

func factoricalMod(n, count, mod int) int {
	if count == 1 {
		return n % mod
	}
	return (n % mod) * (factoricalMod(n-1, count-1, mod)) % mod
}

func combinationMod(n, a, mod int) int {
	x := factoricalMod(n, a, mod)
	y := factoricalMod(a, a, mod)
	y = powMod(y, mod-2, mod)
	return ((x % mod) * (y % mod)) % mod
}
func countBitOfOn(i, numbits int) int {
	count := 0
	var bit uint64
	for bit = 0; bit < uint64(numbits); bit++ {
		t := 1 << bit
		if i&t > 0 {
			count++
		}
	}
	return count
}

type ints []int

func ToString(slice []int) string {
	format := fmt.Sprint(slice)
	return fmt.Sprint(format[1 : len(format)-1])
}

type String string

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


package main

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

func main() {
	scanner := makeScanner(2000000)
	str := String(eGetLine(scanner))
	s := str.revese()
	n := 0
	d := 1
	var counts [2019]int
	counts[0] = 1
	for i := 0; i < len(s); i++ {
		c := eAtoi(string(s[i]))
		n = n + c*d
		counts[n%2019]++
		d *= 10
	}
	sum := 0
	for _, v := range counts {
		if v != 0 {
			sum += v * (v - 1) / 2
		}
	}
	fmt.Println(sum)
}

////////////////////////////////////////////////////////////////////////////////
// ライブラリ
////////////////////////////////////////////////////////////////////////////////
const (
	TooLarge = math.MaxInt64
	TooSmall = math.MinInt64
)

func makeScanner(maxByte int) *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]uint8, 0, 8192), maxByte)
	return scanner
}
func makeCharScanner() *bufio.Scanner {
	scanner := makeScanner(8192)
	scanner.Split(bufio.ScanRunes)
	return scanner
}
func makeWordScanner() *bufio.Scanner {
	scanner := makeScanner(8192)
	scanner.Split(bufio.ScanWords)
	return scanner
}
func eGetLine(r *bufio.Scanner) string {
	if r.Scan() {
		return r.Text()
	}
	err := r.Err()
	if err != nil {
		log.Fatal(err)
	}
	// EOF
	return ""
}
func eGetInt(r *bufio.Scanner) int {
	line := eGetLine(r)
	return eAtoi(line)
}
func eGetInt64(r *bufio.Scanner) int64 {
	line := eGetLine(r)
	return eAtoInt64(line)
}
func eGetFields(r *bufio.Scanner) []string {
	line := eGetLine(r)
	return strings.Fields(line)
}
func eGetInts(r *bufio.Scanner) []int {
	fields := eGetFields(r)
	ints := make([]int, len(fields))
	for i := 0; i < len(ints); i++ {
		ints[i] = eAtoi(fields[i])
	}
	return ints
}
func eGetInt64s(r *bufio.Scanner) []int64 {
	fields := eGetFields(r)
	ints := make([]int64, len(fields))
	for i := 0; i < len(ints); i++ {
		ints[i] = eAtoInt64(fields[i])
	}
	return ints
}
func eGetChars(r *bufio.Scanner) []string {
	line := eGetLine(r)
	return strings.Split(line, "")
}
func eAtoi(s string) int {
	n, err := strconv.Atoi(s)
	if err != nil {
		log.Fatal(err)
	}
	return n
}
func eAtoInt64(s string) int64 {
	n, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		log.Fatal(err)
	}
	return n
}
func pow(a, n int) int {
	if n == 0 {
		return 1
	}
	if n == 1 {
		return a
	}
	if n%2 == 1 {
		return pow((a*a), n/2) * a
	}
	return pow((a * a), n/2)
}
func powMod(a, n, mod int) int {
	if n == 0 {
		return 1 % mod
	}
	if n == 1 {
		return a % mod
	}
	if n%2 == 1 {
		return powMod((a*a)%mod, n/2, mod) * a % mod
	}
	return powMod((a*a)%mod, n/2, mod)
}

func factoricalMod(n, count, mod int) int {
	if count == 1 {
		return n % mod
	}
	return (n % mod) * (factoricalMod(n-1, count-1, mod)) % mod
}

func combinationMod(n, a, mod int) int {
	x := factoricalMod(n, a, mod)
	y := factoricalMod(a, a, mod)
	y = powMod(y, mod-2, mod)
	return ((x % mod) * (y % mod)) % mod
}
func countBitOfOn(i, numbits int) int {
	count := 0
	var bit uint64
	for bit = 0; bit < uint64(numbits); bit++ {
		t := 1 << bit
		if i&t > 0 {
			count++
		}
	}
	return count
}

type ints []int

func ToString(slice []int) string {
	format := fmt.Sprint(slice)
	return fmt.Sprint(format[1 : len(format)-1])
}

type String string

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


package main

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

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

func main() {
	var sc = bufio.NewScanner(os.Stdin)
	sc.Buffer([]byte{}, math.MaxInt64)
	sc.Scan()
	S := sc.Text()
	S = reverse(S)
	N := 2019
	var m = make([]int, N)
	// 10と2019は「互いに素」なので、累積和同士の剰余が等しいとき定数倍した累積和同士の剰余も等しい
	// x===y (mod 2019) <=> 10x===10y (mod 2019)
	m[0]++ // s0=0 (何も累積していない)
	total := 0
	ten := 1
	for x := 0; x < len(S); x++ {
		tmp, _ := strconv.Atoi(S[x : x+1])
		total += (tmp * ten) % N
		// 10^x (xが十分大きい) を剰余するとオーバーフローするのでNで剰余取りながら累積和をとる
		ten = (ten * 10) % N
		m[total%N]++
	}
	cnt := 0
	for _, v := range m {
		// 剰余の計算結果から2組ずつ選ぶパターン数を足す
		// ex) 2C2=1, 3C2=3
		cnt += v * (v - 1) / 2
	}
	fmt.Println(cnt)
}


package main

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

func main() {
	var scanner = bufio.NewScanner(os.Stdin)
	var p string
	if scanner.Scan() {
		p = scanner.Text()
	}
	slice := strings.Split(p, "")
	s := 0
	s2 := 1
	m := map[int]int{}
	m[0]++
	for i := len(slice) - 1; i >= 0; i-- {
		q, _ := strconv.Atoi(slice[i])
		s += s2 * q
		m[s%2019]++
		s2 *= 10
		s2 %= 2019
	}
	ans := 0
	for _, v := range m {
		ans += v * (v - 1) / 2
	}
	fmt.Println(ans)

}


package main

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

func main() {
	var scanner = bufio.NewScanner(os.Stdin)
	var p string
	if scanner.Scan() {
		p = scanner.Text()
	}
	slice := strings.Split(p, "")
	s := 0
	s2 := 1
	m := map[int]int{}
	m[0]++
	for i := len(slice) - 1; i >= 0; i-- {
		q, _ := strconv.Atoi(slice[i])
		s += s2 * q
		m[s%2019]++
		s2 *= 10
	}
	ans := 0
	for _, v := range m {
		ans += v * (v - 1) / 2
	}
	fmt.Println(ans)

}


package main

import (
	"fmt"
)

func countMod(str string) map[int]int {
	const div = 2019
	prev := 0
	l := len(str)
	digit := 1
	count := make(map[int]int)
	count[0] = 1
	for i := l - 1; i >= 0; i-- {
		n := int(rune(str[i]) - '0')
		mod := (n*digit + prev) % div
		count[mod]++
		prev = mod
		digit *= 10
	}
	return count
}

func solve(str string) int {
	count := countMod(str)
	ans := 0
	for _, v := range count {
		ans += v * (v - 1) / 2
	}
	return ans
}

func main() {
	var str string
	fmt.Scan(&str)

	ans := solve(str)
	fmt.Println(ans)
}


package main

import (
	"fmt"
	"strconv"
)

func main() {
	var s string
	fmt.Scan(&s)
	n := len(s)
	m := make([]int, 2019)
	c := 0
	m[0] = 1
	for i := n - 1; i >= 0; i-- {
		t, _ := strconv.Atoi((s[i:]))
		m[t%2019]++
	}
	for i := 0; i < 2019; i++ {
		c += m[i] * (m[i] - 1) / 2
	}
	fmt.Println(c)
}


package main

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

const (
	initialBufSize = 100000
	maxBufSize     = 10000000
)

var (
	sc = bufio.NewScanner(os.Stdin)
	wt = bufio.NewWriter(os.Stdout)
)

func next() string {
	sc.Scan()
	return sc.Text()
}

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

func nextInts(n int) []int {
	slice := make([]int, n)
	for i := 0; i < n; i++ {
		slice[i] = nextInt()
	}
	return slice
}

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

func nextFloat64s(n int) []float64 {
	slice := make([]float64, n)
	for i := 0; i < n; i++ {
		slice[i] = nextFloat64()
	}
	return slice
}

func putf(format string, a ...interface{}) {
	fmt.Fprintf(wt, format, a...)
}

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, initialBufSize), maxBufSize)
	defer wt.Flush()

	s := next()
	n := len(s)

	dp := make([]int, n+1)
	dp[n] = 0
	for i, tens := n-1, 1; i >= 0; i-- {
		dp[i] = (dp[i+1] + int(s[i]-'0')*tens) % 2019
		tens = (tens * 10) % 2019
	}
	// puts(dp)

	mod := map[int]int{}
	for i := range dp {
		mod[dp[i]]++
	}
	// puts(mod)

	ans := 0
	for _, v := range mod {
		ans += v - 1
	}
	puts(ans)
}


package main

import (
	"fmt"
	"strconv"
)

var S string

func main() {
	fmt.Scan(&S)
	a := make([]int, len(S))
	for i, v := range S {
		a[i], _ = strconv.Atoi(string(v))
	}
	b := map[int]int{
		len(S): 0,
	}
	c := 1
	d := map[int]int{}
	res := 0
	for i := len(S) - 1; i >= 0; i-- {
		b[i] = (a[i]*c + b[i+1]) % 2019
		c *= 10
		if d[b[i]] >= 1 {
			res += d[b[i]]
		}
		d[b[i]]++
	}

	fmt.Println(res + d[0])
}


package main

import (
	"fmt"
	"strconv"
)

var S string

func main() {
	fmt.Scan(&S)
	a := make([]int, len(S))
	for i, v := range S {
		a[i], _ = strconv.Atoi(string(v))
	}
	b := map[int]int{
		len(S): 0,
	}
	c := 1
	d := map[int]bool{
		0: true,
	}
	res := 0
	for i := len(S) - 1; i >= 0; i-- {
		b[i] = (a[i]*c + b[i+1]) % 2019
		c *= 10
		if d[b[i]] {
			res++
			continue
		}
		d[b[i]] = true
	}

	fmt.Printf("%d",res)
}


package main

import (
	"fmt"
	"index/suffixarray"
	"strconv"
)

func main() {
	// Code for D - Multiple of 2019
	var s string
	fmt.Scanf("%s", &s)
	index := suffixarray.New([]byte(s))

	edges := map[int]int{}
	for i := 1; i <= 9999; i++ {
		b := strconv.Itoa(i * 2019)
		lookup := index.Lookup([]byte(b), -1)
		if len(lookup) > 0 {
			for _, start := range lookup {
				edges[start] = start + len(b)
			}
		}
	}

	total := 0
	for i := 0; i < len(s); i++ {
		var ok bool
		end := i
		for {
			end, ok = edges[end]
			if !ok {
				break
			}
			total += 1
		}
	}

	fmt.Printf("%d", total)
}


package main

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

var rdr = bufio.NewReaderSize(os.Stdin, 10000000)

func readLine() string {
	buf := make([]byte, 0, 10000000)
	for {
		l, p, err := rdr.ReadLine()
		if err != nil {
			panic(err)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}

func main() {
	str := readLine()
	count := 0
	targetLen := 5
	if len(str) > 4 {
		for targetLen <= len(str) {
			for i := 0; i < len(str)-targetLen+1; i++ {
				slice := str[i : i+targetLen]
				num, _ := strconv.Atoi(slice)
				if num%2019 == 0 {
					count++
				}
			}
			targetLen++
		}
	}

	fmt.Println(count)
}


package main

import (
	"fmt"
 	"strconv"
	"math"
)

func main() {
	var s string
	fmt.Scan(&s)

	snum := make([]int, len(s))

	for i := 0; i < len(s); i++ {
      snum[i],_ = strconv.Atoi(string(s[i]))
	}

	cnt := 0;
	for i := 0; i < len(s)-1; i++ {
		for j := i+3; j < len(s); j++ {
          if digits(snum[i:j+1]) % 2019 == 0 {
          	cnt++
          }
		}
	}
	fmt.Println(cnt)
}

func digits(num []int) int {
	ans := 0
	for i := 0; i < len(num); i++ {
      ans += int(math.Pow(10,float64(len(num)-1-i))) * num[i]
	}
	return ans
}


package main

import (
	"fmt"
	"strconv"
)

func main() {
	var s string
	fmt.Scanf("%s", &s)
	answer := countPairs(s)
	fmt.Println(answer)
}

func countPairs(s string) int {
	if len(s) < 5 {
		return 0
	}
	count := 0
	countMap := make(map[string]int)
	for i := 0; i < len(s)-4; i++ {
		for j := i + 5; j <= len(s); j++ {
			rawStr := s[i:j]
			if countMap[rawStr] != 0 {
				count += countMap[rawStr]
			} else {
				num, _ := strconv.Atoi(rawStr)
				if num%2019 == 0 {
					count++
					countMap[rawStr] = 1
				} else {
					countMap[rawStr] = -1
				}
			}
			if countMap[rawStr] == 1 {
				break // go to next loop of i
			}
		}
	}
	return count
}


package main

import (
	"fmt"
	"strconv"
)

func main() {
	var s string
	fmt.Scan(&s)

	ans := 0
	for i := 1; i <= 100; i++ {
		t := strconv.Itoa(2019 * i)
		lt := len(t)
		for j := 0; j+lt <= len(s); j++ {
			if t == s[j:j+lt] {
				ans++
			}
		}
	}
	fmt.Println(ans)
}


package main

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

func main() {
	r := bufio.NewReader(os.Stdin)
	var s string
	fmt.Fscan(r, &s)
	nums := make([]int, len(s))
	for i := 0; i < len(s); i++ {
		num, _ := strconv.Atoi(string(s[i]))
		nums[i] = num
	}

	// 2019 = 3 * 673
	c := make([]int, len(s)+2)
	c[1] = nums[0]
	for i := 1; i < len(s); i++ {
		c[i+1] = c[i] + nums[i]
	}

	ans := 0
	for i := 0; i < len(s)-4; i++ {
		for j := i + 4; j < len(s); j++ {
			tmp := c[j+1] - c[i]
			if tmp%3 == 0 {
				mul := 1
				num := 0
				for k := j; k >= i; k-- {
					num += nums[k] * mul
					mul *= 10
				}
				if num%673 == 0 {
					ans++
				}
			}
		}
	}

	fmt.Println(ans)
}

// mod combination
func modpow(a, n, mod int) int {
	res := 1
	for n > 0 {
		if n%2 != 0 {
			res = res * a % mod
		}
		a = a * a % mod
		n = n / 2
	}
	return res
}

func modcomb(n, a, mod int) int {
	x := 1
	y := 1
	for i := 0; i < a; i++ {
		x = x * (n - i)
		x %= mod
		y = y * (i + 1)
		y %= mod
	}
	return x * modpow(y, mod-2, mod) % mod
}

func modfactorial(n, mod int) int {
	result := 1
	for i := 1; i <= n; i++ {
		result = (result * i) % mod
	}
	return result
}

// Utility

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

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

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

func primeFactor(x int) map[int]int {
	res := make(map[int]int)
	for i := 2; i*i <= x; i++ {
		for x%i == 0 {
			res[i]++
			x = x / i
		}
	}
	if x != 1 {
		res[x] = 1
	}
	return res
}

func divisor(x int) []int {
	res := make([]int, 0)
	for i := 1; i*i <= x; i++ {
		if x%i == 0 {
			res = append(res, i)
			if i != x/i {
				res = append(res, x/i)
			}
		}
	}
	return res
}

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

func lcm(x, y int) int {
	return x / gcd(x, y) * y
}

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

// Queue ...
type Queue []int

// pop ...
func (q *Queue) empty() bool {
	return len(*q) == 0
}

// push ...
func (q *Queue) push(i int) {
	*q = append(*q, i)
}

// pop ...
func (q *Queue) pop() (int, bool) {
	if q.empty() {
		return 0, false
	} else {
		res := (*q)[0]
		*q = (*q)[1:]
		return res, true
	}
}

// Stack ...
type Stack []int

// pop ...
func (s *Stack) empty() bool {
	return len(*s) == 0
}

// push ...
func (s *Stack) push(i int) {
	*s = append(*s, i)
}

// pop ...
func (s *Stack) pop() (int, bool) {
	if s.empty() {
		return 0, false
	} else {
		index := len(*s) - 1
		res := (*s)[index]
		*s = (*s)[:index]
		return res, true
	}
}


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

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

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

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

type item struct {
	priority, value, index int
}

type pQ []*item

func (pq pQ) Len() int {
	return len(pq)
}

func (pq pQ) Less(i, j int) bool {
	return pq[i].priority < pq[j].priority
}

func (pq pQ) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *pQ) Push(x interface{}) {
	n := len(*pq)
	it := x.(*item)
	it.index = n
	*pq = append(*pq, it)
}

func (pq *pQ) Pop() interface{} {
	old := *pq
	n := len(old)
	it := old[n-1]
	it.index = -1
	*pq = old[0 : n-1]
	return it
}

// End Priority Queue
type link struct {
	u, v, a, b int
}

type edge struct {
	to, cost int
}

type node struct {
	e []edge
}

const inf = 1001001001001001

func dijkstra(s, N int, n []node) []int {
	pq := make(pQ, 0)
	heap.Init(&pq)
	dist := make([]int, N)
	for i := 0; i < N; i++ {
		dist[i] = inf
	}
	dist[s] = 0
	heap.Push(&pq, &item{0, s, 0})
	for pq.Len() > 0 {
		it := heap.Pop(&pq).(*item)
		v := it.value
		if dist[v] < it.priority {
			continue
		}
		for _, e := range n[v].e {
			if dist[e.to] > dist[v]+e.cost {
				// out(v, e)
				dist[e.to] = dist[v] + e.cost
				heap.Push(&pq, &item{dist[e.to], e.to, 0})
			}
		}
	}
	return dist
}

func pos(n, c, m int) int {
	return n*m + c
}

func main() {
	sc.Split(bufio.ScanWords)

	N, M, S := getInt(), getInt(), getInt()
	ma := 0
	l := make([]link, M*2)
	for i := 0; i < M; i++ {
		u, v, a, b := getInt()-1, getInt()-1, getInt(), getInt()
		l[i*2] = link{u, v, a, b}
		l[i*2+1] = link{v, u, a, b}
		ma = max(ma, a)
	}

	c := make([]int, N)
	d := make([]int, N)
	for i := 0; i < N; i++ {
		c[i], d[i] = getInt(), getInt()
	}

	// make nodes
	ma *= N
	n := make([]node, ma*N)
	for i := 0; i < N; i++ {
		// out("---", ma)
		for j := 0; j <= ma; j++ {
			to := j + c[i]
			cost := d[i]
			if to >= ma {
				break
			}
			f := pos(i, j, ma)
			t := pos(i, to, ma)
			// out(f, "->", t, cost)
			n[f].e = append(n[f].e, edge{t, cost})
		}
	}
	for i := 0; i < M*2; i++ {
		from := l[i].u
		to := l[i].v
		coin := l[i].a
		cost := l[i].b
		for j := 0; j < ma; j++ {
			if j-coin < 0 {
				continue
			}
			f := pos(from, j, ma)
			t := pos(to, j-coin, ma)
			// out(from, to, "f,t", f, t, cost, len(n))
			n[f].e = append(n[f].e, edge{t, cost})
		}
	}

	S = min(S, ma-1)
	dist := dijkstra(S, ma*N, n)

	for i := 1; i < N; i++ {
		m := inf
		for j := 0; j < ma; j++ {
			m = min(m, dist[i*ma+j])
		}
		// out(dist[i*ma : (i+1)*ma])
		out(m)
	}
	//out("dist=", dist)
}

Score : 500 points

Problem Statement

There are N cities numbered 1 to N, connected by M railroads.

You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.

The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes.
You cannot use gold coins to pay the fare.

There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin.
The transaction takes D_i minutes for each gold coin you give.
You can exchange any number of gold coins at each exchange counter.

For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.

Constraints

2 \leq N \leq 50

N-1 \leq M \leq 100

0 \leq S \leq 10^9

1 \leq A_i \leq 50

1 \leq B_i,C_i,D_i \leq 10^9

1 \leq U_i < V_i \leq N

There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).

Each city t=2,...,N can be reached from City 1 with some number of railroads.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N

Output

For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.

Sample Input 1

3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5

Sample Output 1

2
14

The railway network in this input is shown in the figure below.

In this figure, each city is labeled as follows:

The first line: the ID number i of the city (i for City i)

The second line: C_i / D_i

Similarly, each railroad is labeled as follows:

The first line: the ID number i of the railroad (i for the i-th railroad in input)

The second line: A_i / B_i

You can travel from City 1 to City 2 in 2 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.

You can travel from City 1 to City 3 in 14 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.

At the exchange counter in City 2, exchange 3 gold coins for 3 silver coins in 6 minutes.

Use the 1-st railroad to move from City 2 to City 1 in 2 minutes.

Use the 2-nd railroad to move from City 1 to City 3 in 4 minutes.

Sample Input 2

4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4

Sample Output 2

5
5
7

The railway network in this input is shown in the figure below:

You can travel from City 1 to City 4 in 7 minutes, as follows:

At the exchange counter in City 1, exchange 2 gold coins for 6 silver coins in 2 minutes.

Use the 2-nd railroad to move from City 1 to City 3 in 4 minutes.

Use the 4-th railroad to move from City 3 to City 4 in 1 minutes.

Sample Input 3

6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1

Sample Output 3

1
9003
14606
16510
16576

The railway network in this input is shown in the figure below:

You can travel from City 1 to City 6 in 16576 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.

At the exchange counter in City 2, exchange 3 gold coins for 3 silver coins in 9000 minutes.

Use the 1-st railroad to move from City 2 to City 1 in 1 minute.

Use the 2-nd railroad to move from City 1 to City 3 in 1 minute.

At the exchange counter in City 3, exchange 8 gold coins for 8 silver coins in 5600 minutes.

Use the 2-nd railroad to move from City 3 to City 1 in 1 minute.

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.

Use the 3-rd railroad to move from City 2 to City 4 in 1 minute.

At the exchange counter in City 4, exchange 19 gold coins for 19 silver coins in 1900 minutes.

Use the 3-rd railroad to move from City 4 to City 2 in 1 minute.

Use the 1-st railroad to move from City 2 to City 1 in 1 minute.

Use the 2-nd railroad to move from City 1 to City 3 in 1 minute.

Use the 4-th railroad to move from City 3 to City 5 in 1 minute.

At the exchange counter in City 5, exchange 63 gold coins for 63 silver coins in 63 minutes.

Use the 4-th railroad to move from City 5 to City 3 in 1 minute.

Use the 2-nd railroad to move from City 3 to City 1 in 1 minute.

Use the 5-th railroad to move from City 1 to City 6 in 1 minute.

Sample Input 4

4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7

Sample Output 4

1
3
5

The railway network in this input is shown in the figure below:

Sample Input 5

2 1 0
1 2 1 1
1 1000000000
1 1

Sample Output 5

1000000001

The railway network in this input is shown in the figure below:

You can travel from City 1 to City 2 in 1000000001 minutes, as follows:

At the exchange counter in City 1, exchange 1 gold coin for 1 silver coin in 1000000000 minutes.

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.


package main

import (
	"fmt"
	"math"
)

func main() {
	var r float64
	fmt.Scan(&r)
	fmt.Println(math.Pi * (2 * r))
}

Score : 100 points

Problem Statement

Print the circumference of a circle of radius R.

Constraints

1 \leq R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R

Output

Print the circumference of the circle.
Your output is considered correct if and only if its absolute or relative error from our answer is at most 10^{-2}.

Sample Input 1

1

Sample Output 1

6.28318530717958623200

Since we accept an absolute or relative error of at most 10^{-2}, 6.28 is also an acceptable output, but 6 is not.

Sample Input 2

73

Sample Output 2

458.67252742410977361942


package main

import (
	"fmt"
	"math"
)

func main() {
	var r float64
	fmt.Scan(&r)
	fmt.Println(2*r*math.Pi)

}


package main

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

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		log.Fatal(e)
	}
	return i
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

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

func main() {
	sc.Split(bufio.ScanWords)

	r := getInt()
	out(math.Pi * 2 * float64(r))
}


package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	if scanner.Scan() {
		a, _ := strconv.Atoi(scanner.Text())
		b := float64(a)
		c := b * float64(2) * 3.1415
		fmt.Println(c)
	}
}


package main

import "fmt"
import "math"

func main(){
	var R float64

	fmt.Scan(&R)
	ans := R * 2. * math.Pi
	fmt.Println(ans)
}


package main

import "fmt"

func main() {
	var R float64
	fmt.Scan(&R)

	res := R * 2 * 3.14

	fmt.Println(res)

}


package main

import "fmt"
import "math"

func main(){
	var R float64

	fmt.Scan(&R)

	fmt.Println(R * 2. * math.Pi)
}


package main

import (
	"fmt"
	"math"
)

func main() {
	var r int
	fmt.Scan(&r)
	fmt.Println(float64(2) * float64(r) * math.Pi)
}


package main

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

const mod = 998244353
const facNum = 300001

func main() {
	sc := newScanner(os.Stdin)
	N := sc.s()
	for _, r := range N {
		if r == '7' {
			fmt.Println("Yes")
			return
		}
	}
	fmt.Println("No")
}

// fmt.Println("Yes")
// fmt.Println("No")

// I/O
type scanner struct {
	sc *bufio.Scanner
}

func newScanner(input io.Reader) *scanner {
	sc := bufio.NewScanner(input)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024), int(1e+9))
	return &scanner{sc}
}

func (s *scanner) s() string {
	s.sc.Scan()
	return s.sc.Text()
}

func (s *scanner) i() int {
	i, e := strconv.Atoi(s.s())
	if e != nil {
		panic(e)
	}
	return i
}

func (s *scanner) f() float64 {
	f, e := strconv.ParseFloat(s.s(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func (s *scanner) bs() []byte {
	return []byte(s.s())
}

func (s *scanner) is(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = s.i()
	}
	return res
}

func (s *scanner) fs(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = s.f()
	}
	return res
}

//const factorial = new
func Pow(a, n int) int {
	ans := 1
	for n > 0 {
		if (n & 1) == 1 {
			ans = ans * a % mod
		}
		a = a * a % mod
		n = n >> 1
	}
	return ans
}

func Gcd(a, b int) int {
	if a < b {
		return Gcd(b, a)
	}
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

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

func combination(n, k int, fac, ifac []int) int {
	if n < k || n < 0 {
		return 0
	}
	if k == 0 {
		return 1
	}
	//while n != 0
	ans := ifac[k] * ifac[n-k] % mod
	return ans * fac[n] % mod
}

// 階乗: factorial
// コンビネーションを計算する際に前もって計算しておく
// fac[k] => k! (mod M)
// ifac[k] => k!^(M-2) (mod M)
// n: ex. 2 * 10^5 => 200001
// fac, ifac := factorial()
func factorial() (fac []int, ifac []int) {
	fac = make([]int, facNum)
	fac[0] = 1
	ifac = make([]int, facNum)
	ifac[0] = 1
	for i := 1; i < facNum; i++ {
		fac[i] = fac[i-1] * i % mod
		ifac[i] = ifac[i-1] * Pow(i, mod-2) % mod
	}
	return
}

// vs: sorted slice int value
func lowerBound(vs []int, v int) (index int) {
	n := len(vs) / 2
	m := len(vs)
	for m != n {
		if vs[n] < v {
			n = (m-n+1)/2 + n
			//m = m
		} else {
			m = n
			n = n / 2
		}
	}
	return n
}

func IntSlice(n, init int) []int {
	r := make([]int, n)
	for i := range r {
		r[i] = init
	}
	return r
}

Score : 100 points

Problem Statement

Given is a three-digit integer N. Does N contain the digit 7?

If so, print Yes; otherwise, print No.

Constraints

100 \leq N \leq 999

Input

Input is given from Standard Input in the following format:

N

Output

If N contains the digit 7, print Yes; otherwise, print No.

Sample Input 1

117

Sample Output 1

Yes

117 contains 7 as its last digit.

Sample Input 2

123

Sample Output 2

No

123 does not contain the digit 7.

Sample Input 3

777

Sample Output 3

Yes


package main

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

func scanInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}

func scanInt64() int64 {
	sc.Scan()
	i, _ := strconv.ParseInt(sc.Text(), 10, 64)
	return i
}

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

func scanInts64(n int) []int64 {
	res := make([]int64, n)
	for i := range res {
		res[i] = scanInt64()
	}
	return res
}

func scanText() string {
	sc.Buffer([]byte{}, math.MaxInt64)
	sc.Scan()
	return sc.Text()
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	n := scanText()
	for _, c := range n {
		if c == '7'	 {
			fmt.Println("Yes")
			return
		}
	}
	fmt.Println("No")
}


package main

import (
	"fmt"
)

func main()  {
	var str string

	_, _ = fmt.Scan(&str)

	if IsSevenExistingIn(str) {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

func IsSevenExistingIn(str string) bool{
	for i := 0; i < len(str); i++{
		if str[i] == '7'{
			return true
		}
	}
	return false
}


package main

import (
	"fmt"
)

func main() {

	var n string
	fmt.Scan(&n)

	result := "No"
	if n[0] == '7' || n[1] == '7' || n[2] == '7' {
		result = "Yes"
	}
	fmt.Println(result)
}


package main

import "fmt"

func main() {
	var a, c int
	var ans int = 0
	fmt.Scan(&a)
	for i := 0; i < 3; i++ {
		c = a % 10
		if c == 7 {
			ans++
		}
		a = a / 10
	}

	if ans > 0 {
		fmt.Printf("Yes\n")
	} else {
		fmt.Printf("No")
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

/*
func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	str := strconv.Itoa(n)
	arr := strings.Split(str, "")
	for i := 0; i < len(arr); i++ {
		if arr[i] == "7" {
			fmt.Println("Yes")
			return
		}
	}
	fmt.Println("No")
}
*/

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	str := strconv.Itoa(n)
	if strings.Index(str, "7") != -1 {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}


package main

import (
	"fmt"
)

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

	x := 100
	counter := 0
	for i:=0; i<3; i++ {
		res := S / x
		if res == 7 {
			counter = 1
			fmt.Println("Yes")
			break
		}
		y := res * x
		S -= y
		x /= 10
	}
	if counter == 0 {
		fmt.Println("No")
	}

}


package main

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

var sc = bufio.NewScanner(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func main() {
	sc.Split(bufio.ScanWords)
	defer out.Flush() // !!!!coution!!!! you must use Fprint(out, ) not Print()
	/* --- code --- */
	a := next()

	if strings.Contains(a, "7") {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

// -*-*-*-*-*-*-*-*-
// * I/O utilities *
// -*-*-*-*-*-*-*-*-

func next() string {
	sc.Scan()
	return sc.Text()
}

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

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

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}
func nextFloats(n int) []float64 {
	ret := make([]float64, n)
	for i := 0; i < n; i++ {
		ret[i] = nextFloat64()
	}
	return ret
}
func nextStrings(n int) []string {
	ret := make([]string, n)
	for i := 0; i < n; i++ {
		ret[i] = next()
	}
	return ret
}

func split(s string) []string {
	ret := make([]string, len([]rune(s)))
	for i, v := range []rune(s) {
		ret[i] = string(v)
	}
	return ret
}

func PrintOut(src interface{}, joinner string) {
	switch reflect.TypeOf(src).Kind() {
	case reflect.Slice:
		s := reflect.ValueOf(src)
		for idx := 0; idx < s.Len(); idx++ {
			fmt.Fprintf(out, "%v", s.Index(idx))
			if idx < s.Len()-1 {
				fmt.Fprintf(out, "%s", joinner)
			} else {
				fmt.Fprintln(out)
			}
		}
	default:
		fmt.Fprintln(out, "fuck")
	}
}

// -*-*-*-*-*-*-*-*-
// * tool snippets *
// -*-*-*-*-*-*-*-*-
func duplicate2Int(base [][]int) (ret [][]int) {
	ret = make([][]int, len(base))
	for i, v := range base {
		ret[i] = append([]int{}, v...)
	}
	return
}

// -*-*-*-*-*-*-*-*-*-*-*-*-*-
// * Algorithms Utility Zone *
// -*-*-*-*-*-*-*-*-*-*-*-*-*-

// -*-*-*-*-*-*-*-
// * 1. nibutan  *
// -*-*-*-*-*-*-*-
func lower_bound(arr []int, target int) int {
	l, r := 0, len(arr)
	for l < r {
		mid := (l + r) / 2
		if arr[mid] < target {
			l = mid + 1
		} else {
			r = mid
		}
	}
	return l
}

func upper_bound(arr []int, target int) int {
	l, r := 0, len(arr)
	for l < r {
		mid := (l + r) / 2
		if target < arr[mid] {
			r = mid
		} else {
			l = mid + 1
		}
	}
	return l
}

// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// * math flavor typical theories *
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
func gcd(a, b int) int {
	if a > b {
		return gcd(b, a)
	}
	for a != 0 {
		a, b = b%a, a
	}
	return b
}

func pow(a, b int) (ret int) {
	ret = a
	// 10^2 = 100ってことは10に10を1回掛けることだね
	// なので初期値を含めると上限b-1未満
	for i := 0; i < b-1; i++ {
		ret *= a
	}
	return
}

func powMod(n, m, mod int) (ret int) {
	ret = 1
	for m > 0 {
		if m&1 == 1 {
			ret *= n
			ret %= mod
		}
		n *= n
		n %= mod
		m >>= 1
	}
	return ret
}


package main

import "fmt"

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

	for i := 0; i < 3; i++ {
		if n%10 == 7 {
			fmt.Println("Yes")
			return
		}
	}
	fmt.Println("No")
}


package main

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

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

func solve(in io.Reader, out io.Writer) {
	bs := NewBufScanner(in)
	bw := NewBufWriter(out)
	defer bw.w.Flush()
	ans := "No"
	if strings.Index(bs.Scan(), "7") > 0 {
		ans = "Yes"
	}
	bw.Printf(ans)
}

// BufScanner original scanner
type BufScanner struct {
	s *bufio.Scanner
}

// NewBufScanner constructer
func NewBufScanner(in io.Reader) *BufScanner {
	s := bufio.NewScanner(in)
	s.Buffer(make([]byte, 1024), 1e+9)
	s.Split(bufio.ScanWords)
	return &BufScanner{
		s: s,
	}
}

// Scan Scan Data
func (b *BufScanner) Scan() string {
	b.s.Scan()
	return b.s.Text()
}

// IntScan Scan Data
func (b *BufScanner) IntScan() int {
	v, err := strconv.Atoi(b.Scan())
	if err != nil {
		panic(err)
	}
	return v
}

// BufWriter original writer
type BufWriter struct {
	w *bufio.Writer
}

// NewBufWriter constructer
func NewBufWriter(out io.Writer) *BufWriter {
	w := bufio.NewWriter(out)
	return &BufWriter{
		w: w,
	}
}

// Printf Output file
func (b *BufWriter) Printf(format string, a ...interface{}) {
	fmt.Fprintf(b.w, format, a...)
}


package main

import (
	"bufio"
	_ "container/heap"
	"fmt"
	"os"
	_ "sort"
	"strconv"
)

// I/O
type Scanner struct {
	sc *bufio.Scanner
}

func NewScanner() *Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024), int(1e+9))
	return &Scanner{sc}
}

func (s *Scanner) nextStr() string {
	s.sc.Scan()
	return s.sc.Text()
}

func (s *Scanner) nextInt() int {
	i, e := strconv.Atoi(s.nextStr())
	if e != nil {
		panic(e)
	}
	return i
}

func (s *Scanner) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func (s *Scanner) nextRuneSlice() []rune {
	return []rune(s.nextStr())
}

func (s *Scanner) nextIntSlice(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextInt()
	}
	return res
}

func (s *Scanner) nextFloatSlice(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextFloat()
	}
	return res
}

// Arithmetic
func max(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m < i {
			m = i
		}
	}
	return m
}

func min(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m > i {
			m = i
		}
	}
	return m
}

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

func pow(x, y int) int {
	res := 1
	for i := 0; i < y; i++ {
		res *= x
	}
	return res
}

func ceil(a, b int) int {
	if a%b == 0 {
		return a / b
	} else {
		return a/b + 1
	}
}

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

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

// Sort
type RuneSlice []rune

func (a RuneSlice) Len() int           { return len(a) }
func (a RuneSlice) Less(i, j int) bool { return a[i] < a[j] }
func (a RuneSlice) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

// Main
const MOD = int(1e+9) + 7
const INF = 1 << 60

func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	defer wtr.Flush()
	N := sc.nextStr()
	if N[0] == '7' || N[1] == '7' || N[2] == '7' {
		fmt.Fprintln(wtr, "Yes")
	} else {
		fmt.Fprintln(wtr, "No")
	}
}


package main

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

func main() {
	sc := NewScanner()
	S := sc.Next()

	if strings.Contains(S,"7"){
		fmt.Println("Yes")
	}else{
		fmt.Println("No")
	}

}

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]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

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


package main

import (
	"fmt"
)

func main() {
	// gcd(a, b, c) = gcd(gcd(a, b), c)
	var K int
	fmt.Scanf("%d", &K)

	sum := 0
	for i := 1; i <= K; i++ {
		for j := 1; j <= K; j++ {
			for k := 1; k <= K; k++ {
				sum += gcd(gcd(i, j), k)
			}
		}
	}
	fmt.Println(sum)
}

func gcd(a, b int) int {
	if a > b {
		b, a = a, b
	} else if a == b {
		return a
	}
	// b > a
	for a != 0 {
		a, b = b%a, a
	}
	return b
}

Score : 300 points

Problem Statement

Find \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}.

Here \gcd(a,b,c) denotes the greatest common divisor of a, b, and c.

Constraints

1 \leq K \leq 200

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the value of \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}.

Sample Input 1

2

Sample Output 1

9

\gcd(1,1,1)+\gcd(1,1,2)+\gcd(1,2,1)+\gcd(1,2,2)
+\gcd(2,1,1)+\gcd(2,1,2)+\gcd(2,2,1)+\gcd(2,2,2)
=1+1+1+1+1+1+1+2=9

Thus, the answer is 9.

Sample Input 2

200

Sample Output 2

10813692


package main

import (
	"fmt"
)

// go run ./main.go < in
var num int

func main() {
	fmt.Scan(&num)

	sum := 0
	for i := 1; i <= num; i++ {
		for j := 1; j <= num; j++ {
			init := gcd(i, j)
			for k := 1; k <= num; k++ {
				sum += gcd(init, k)
			}
		}
	}
	fmt.Println(sum)
}

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


package main

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

func main() {
	nextReader = newScanner()
	k := nextInt()
	ans := 0
	for a := 1; a <= k; a++ {
		for b := 1; b <= k; b++ {
			for c := 1; c <= k; c++ {
				ans += gcd(a, gcd(b, c))
			}
		}
	}
	fmt.Println(ans)
}

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

// ---------------------------------------------------------------
// I/O
// ---------------------------------------------------------------
var nextReader func() string

func newScanner() func() string {
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 1024), int(1e11))
	sc.Split(bufio.ScanWords)
	return func() string {
		sc.Scan()
		return sc.Text()
	}
}

func nextString() string { return nextReader() }

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

func nextInts(size int) []int {
	ns := make([]int, size)
	for i := 0; i < size; i++ {
		ns[i] = nextInt()
	}
	return ns
}


package main

import (
  "fmt"
)

func main(){
  var N, ans int
  fmt.Scan(&N)

  for i := 1; i<=N; i++ {
    for j := 1; j<=N; j++ {
      for k := 1; k<=N; k++ {
        ans += gcd(i,gcd(j,k))
      }
    }
  }
  fmt.Println(ans)
}

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


package main

import "fmt"

func main() {
	var K, sum int
	fmt.Scan(&K)
	w := make([][]int, K+1)
	for i := 0; i < len(w); i++ {
		w[i] = make([]int, K+1)
		for j := 0; j < len(w[i]); j++ {
			w[i][j] = gcd(i, j)
		}
	}
	for a := 1; a <= K; a++ {
		for b := 1; b <= K; b++ {
			for c := 1; c <= K; c++ {
				sum += gcd(w[a][b], c)
			}
		}
	}
	fmt.Println(sum)
}
func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

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

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	sum := 0
	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			for k := 1; k <= n; k++ {
				sum += gcd(gcd(i, j), k)
			}
		}
	}
	fmt.Println(sum)
}


package main
import "fmt"
func main(){
    // Your code here!
    var k int64
    fmt.Scan(&k)

    var x,y,z,sum int64
    sum = 0
    for x = 1; x <= k; x++{
        for y = 1; y <= k; y++{
            for z = 1; z <= k; z++{
                sum = sum + gcd(gcd(z,y),x)
            }
        }
    }
    fmt.Println(sum)
}

func gcd(a int64, b int64) int64{
    var t int64
    if a < b{
        t = b
        b = a
        a = t
    }
    for ;;{
        if a % b == 0{
            return b
        }else{
            t = a
            a = b
            b = t % b
        }
    }
}


package main

import "fmt"

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

func main() {
	var K int
	fmt.Scan(&K)
	sum := 0
	for i := 1; i <= K; i++ {
		for j := 1; j <= K; j++ {
			for l := 1; l <= K; l++ {
				sum += gcd(gcd(i, j), l)
			}
		}
	}
	fmt.Println(sum)
}


package main

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

const (
	initialBufSize = 1e4
	maxBufSize     = 1e6 + 7
)

var buf []byte = make([]byte, maxBufSize)
var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(buf, maxBufSize)
}

func main() {
	K := nextInt()
	ans := 0
	for a := 1; a <= K; a++ {
		for b := 1; b <= K; b++ {
			for c := 1; c <= K; c++ {
				ans += gcdof2numbers(a, gcdof2numbers(b, c))
			}
		}
	}
	fmt.Println(ans)
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

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


package main

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

const INFINITY = math.MaxInt64/2 - 1

func exec(stdin *Stdin, stdout *Stdout) {
	k := stdin.ReadInt()
	sum := 0
	for a := 1; a <= k; a++ {
		for b := 1; b <= k; b++ {
			for c := 1; c <= k; c++ {
				sum += Gcd(a, Gcd(b, c))
			}
		}
	}
	stdout.Println(sum)
}

func Gcd(x, y int) int {
	if x < y {
		x, y = y, x
	}

	for y > 0 {
		x, y = y, x%y
	}

	return x
}

func main() {
	stdout := NewStdout()
	defer stdout.Flush()
	exec(NewStdin(bufio.ScanWords), stdout)
}

type Stdin struct {
	stdin *bufio.Scanner
}

func NewStdin(split bufio.SplitFunc) *Stdin {
	s := Stdin{bufio.NewScanner(os.Stdin)}
	s.stdin.Split(split)
	s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), INFINITY)
	return &s
}

func (s *Stdin) Read() string {
	s.stdin.Scan()
	return s.stdin.Text()
}

func (s *Stdin) ReadInt() int {
	n, _ := strconv.Atoi(s.Read())
	return n
}

func (s *Stdin) ReadFloat64() float64 {
	n, _ := strconv.ParseFloat(s.Read(), 64)
	return n
}

type Stdout struct {
	stdout *bufio.Writer
}

func NewStdout() *Stdout {
	return &Stdout{bufio.NewWriter(os.Stdout)}
}

func (s *Stdout) Flush() {
	s.stdout.Flush()
}

func (s *Stdout) Println(a ...interface{}) {
	fmt.Fprintln(s.stdout, a...)
}

func Min(a int, b ...int) int {
	for _, v := range b {
		if v < a {
			a = v
		}
	}
	return a
}

func Max(a int, b ...int) int {
	for _, v := range b {
		if a < v {
			a = v
		}
	}
	return a
}

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

func Pow(x, y int) int {
	z := 1
	for y > 0 {
		if y%2 == 0 {
			x *= x
			y /= 2
		} else {
			z *= x
			y -= 1
		}
	}
	return z
}

func CreateMatrix(x, y int) [][]int {
	matrix := make([][]int, x)
	for i := 0; i < x; i++ {
		matrix[i] = make([]int, y)
	}
	return matrix
}


package main

import (
	"fmt"
)

func GCD(a, b int) int {
	if b == 0 {
		return a
	}
	return GCD(b, a%b)
}
func main() {
	var N int
	fmt.Scanf("%d\n", &N)

	sum := 0
	for i := 1; i <= N; i++ {
		for j := 1; j <= N; j++ {
			for k := 1; k <= N; k++ {
				sum += GCD(GCD(i, j), k)
			}
		}
	}
	fmt.Println(sum)

}


package main

import (
	"fmt"
)

func main() {
	var k int
	fmt.Scan(&k)
	var sum int
	for a := 1; a <= k; a++ {
		for b := 1; b <= k; b++ {
			for c := 1; c <= k; c++ {
				sum += gcd(gcd(a, b), c)
			}
		}
	}
	fmt.Println(sum)
}

func gcd(a, b int) int {
	if a < b {
		a, b = b, a
	}
	r := a % b
	for r != 0 {
		a = b
		b = r
		r = a % b
	}
	return b
}


package main

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

var DEBUG = true

func main() {
	defer Flush()
	K := readi()

	var ans int
	for a := 1; a <= K; a++ {
		for b := 1; b <= K; b++ {
			for c := 1; c <= K; c++ {
				ans += gcd(a, gcd(b, c))
			}
		}
	}
	println(ans)

}

// -----------------------------------------------------------------------------

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

// -----------------------------------------------------------------------------

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

func dbgf(f string, args ...interface{}) {
	if !DEBUG {
		return
	}
	fmt.Fprintf(os.Stderr, f, args...)
}

func dbg(args ...interface{}) {
	if !DEBUG {
		return
	}
	fmt.Fprintln(os.Stderr, args...)
}

// -----------------------------------------------------------------------------

// Utilities

func sumSlice(a []int) int {
	var res int
	for _, v := range a {
		res += v
	}
	return res
}

func sumSlicell(a []int64) int64 {
	var res int64
	for _, v := range a {
		res += v
	}
	return res
}

func readInts(N int) (int, []int) {
	if N == 0 {
		N = readi()
	}
	a := make([]int, N)
	for i := range a {
		a[i] = readi()
	}
	return N, a
}

func readIntsll(N int) (int, []int64) {
	if N == 0 {
		N = readi()
	}
	a := make([]int64, N)
	for i := range a {
		a[i] = readll()
	}
	return N, a
}

// -----------------------------------------------------------------------------

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

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

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

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

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

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

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

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

func absll(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

func absf(a float64) float64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}


package main

import "fmt"

func main() {

	var N int
	var S string

	fmt.Scanf("%d", &N)
	fmt.Scanf("%v", &S)

	num := 0
	for a := 0; a < len(S); a++ {
		A := S[a]
		for b := a+1; b < len(S); b++ {
			B := S[b]
			if A == B {
				continue
			}
			for c := b+1; c < len(S); c++ {
				C := S[c]
				if C == A || C == B {
					continue
				}
				if c - b == b - a {
					continue
				}
				num++
			}
		}
	}
	fmt.Printf("%v\n", num)
}

Score : 400 points

Problem Statement

We have a string S of length N consisting of R, G, and B.

Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:

S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.

j - i \neq k - j.

Constraints

1 \leq N \leq 4000

S is a string of length N consisting of R, G, and B.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of triplets in question.

Sample Input 1

4
RRGB

Sample Output 1

1

Only the triplet (1,~3,~4) satisfies both conditions. The triplet (2,~3,~4) satisfies the first condition but not the second, so it does not count.

Sample Input 2

39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB

Sample Output 2

1800


package main

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

func main() {
	nextReader = newScanner()
	_ = nextInt()
	s := nextString()

	m := make(map[rune][]int)
	for i, c := range s {
		m[c] = append(m[c], i)
	}
	ans := 0
	for i, c := range s {
		if c == 'R' {
			ans += solve('G', 'B', m, i)
		}
		if c == 'G' {
			ans += solve('B', 'R', m, i)
		}
		if c == 'B' {
			ans += solve('R', 'G', m, i)
		}
	}
	fmt.Println(ans)
}

func solve(r1, r2 rune, m map[rune][]int, i int) int {
	ans := 0
	for _, j := range m[r1] {
		if i > j {
			continue
		}
		for _, k := range m[r2] {
			if j > k {
				continue
			}
			if j-i != k-j {
				ans++
			}
		}
	}
	for _, j := range m[r2] {
		if i > j {
			continue
		}
		for _, k := range m[r1] {
			if j > k {
				continue
			}
			if j-i != k-j {
				ans++
			}
		}
	}
	return ans
}

// ---------------------------------------------------------------
// I/O
// ---------------------------------------------------------------
var nextReader func() string

func newScanner() func() string {
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 1024), int(1e11))
	sc.Split(bufio.ScanWords)
	return func() string {
		sc.Scan()
		return sc.Text()
	}
}

func nextString() string { return nextReader() }

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

func nextInts(size int) []int {
	ns := make([]int, size)
	for i := 0; i < size; i++ {
		ns[i] = nextInt()
	}
	return ns
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {

	var n int
	var s string

	if sc.Scan() {
		n, _ = strconv.Atoi(sc.Text())
	}

	if sc.Scan() {
		s = sc.Text()
	}

	var rgb, r, g, b int
	for i := 0; i < n; i++ {
		switch s[i] {
		case 'R':
			r++
		case 'G':
			g++
		case 'B':
			b++
		}
	}
	rgb = r * g * b

	for j := 0; j < n; j++ {
		for i := 0; i < j; i++ {
			k := j + (j - i)
			if k < n {
				if s[i] == s[j] {
					continue
				}
				if s[i] == s[k] {
					continue
				}
				if s[j] == s[k] {
					continue
				}
				rgb--
			}
		}
	}

	fmt.Print(rgb)
}


package main

import (
	"fmt"
)

func main() {
	var n int
	var s string
	fmt.Scan(&n, &s)
	var r, g, b int
	for i := 0; i < n; i++ {
		if s[i] == 'R' {
			r++
		} else if s[i] == 'G' {
			g++
		} else {
			b++
		}
	}

	ans := r * g * b
	for i := 0; i < n; i++ {
		for j := i+1; j < n; j++ {
			k := 2*j - i
			if k == j || k >= n {
				continue
			}
			if s[i] != s[j] && s[j] != s[k] && s[k] != s[i] {
				ans--
			}
		}
	}
	fmt.Println(ans)
}