Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once. Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.

The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house. The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.

Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.

NoteIn the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6. In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer

var n int
var s string
var cnt []int

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()

	fmt.Fscan(bufin, &n, &s)

	cnt = make([]int, 128)
	for i := range cnt {
		cnt[i] = 0
	}

	i := 0
	result := 0

	for j := 0; j < n; j++ {
		cnt[s[j]]++
		isNewChar := cnt[s[j]] == 1

		for cnt[s[i]] > 1 {
			cnt[s[i]]--
			i++
		}

		len := j - i + 1
		if isNewChar || (len < result) {
			result = len
		}
	}

	fmt.Fprintln(bufout, result)
}

package main

import "fmt"

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

	s := make([]byte, n)
	fmt.Scan(&s)

	a := make([]int32, 128)
	for i := range a {
		a[i] = 0
	}

	maxDiff := 0
	for i := 0; i < n; i++ {
		c := s[i]
		a[c]++
		if a[c] == 1 {
			maxDiff++
		}
	}

	for i := range a {
		a[i] = 0
	}

	minFlats := n
	diff := 0
	i := 0
	j := -1

	for (i < n) && (j < n) {
		for (diff < maxDiff) && (j+1 < n) {
			j++
			c := s[j]
			a[c]++
			if a[c] == 1 {
				diff++
			}
		}

		if diff == maxDiff {
			flats := j - i + 1
			if flats < minFlats {
				minFlats = flats
			}
		}

		c := s[i]
		a[c]--
		if a[c] == 0 {
			diff--
		}
		i++
	}

	fmt.Println(minFlats)
}

package main

import "fmt"

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

	s := make([]byte, n)
	fmt.Scan(&s)

	cnt := make([]int32, 128)
	for i := range cnt {
		cnt[i] = 0
	}

	result := 0
	i := 0

	for j := 0; j < n; j++ {
		cnt[s[j]]++
		isNew := cnt[s[j]] == 1

		for cnt[s[i]] > 1 {
			cnt[s[i]]--
			i++
		}

		len := j - i + 1
		if isNew || len < result {
			result = len
		}
	}

	fmt.Println(result)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	s := make([]byte, n)
	fmt.Scan(&s)

	cnt := make([]int64, 128)
	for i := range cnt {
		cnt[i] = 0
	}

	ans := 0
	i := 0
	for j := 0; j < n; j++ {
		cnt[s[j]]++
		is_new := cnt[s[j]] == 1

		for cnt[s[i]] > 1 {
			cnt[s[i]]--
			i++
		}

		len := j - i + 1
		if is_new || len < ans {
			ans = len
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
	"os"
)

const dic = 127

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	str := make([]byte, n)
	if _, err := os.Stdin.Read(str); err != nil {
		panic(err)
	}

	// Build next tracker.
	next := make([][128]int, n)
	for i := range next[n-1] {
		next[n-1][i] = n
	}
	for i := n - 2; i >= 0; i-- {
		copy(next[i][:], next[i+1][:])
		next[i][str[i+1]] = i + 1
	}

	// Count pokemons
	var cur [dic]bool
	for _, ch := range str {
		cur[ch] = true
	}
	var total int
	for i, one := range cur {
		if one {
			total++
		}
		cur[i] = false
	}

	// Compute min span.
	var sum, minSpan, from, to int
	for {
		if sum == total {
			if minSpan == 0 || to-from < minSpan {
				minSpan = to - from
			}
			ch := str[from]
			if next[from][ch] >= to {
				cur[ch] = false
				sum--
			}
			from++
		} else {
			if to == n {
				fmt.Println(minSpan)
				return
			}
			ch := str[to]
			if !cur[ch] {
				cur[ch] = true
				sum++
			}
			to++
		}
	}
}

package main

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

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

	used := make(map[rune]bool)
	for _, vl := range appt {
		if !used[vl] {
			count++
			used[vl] = true
		}
	}

	pokemons := make(map[byte]int)

	var s, r int
	mn := n

	for i := 0; i < n; i++ {
		for s < count && r < n {
			add(&r, &s, pokemons, appt)
		}
		if s == count {
			mn = min(mn, r-i)
		}
		del(&i, &s, pokemons, appt)

	}

	fmt.Println(mn)
}

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

func add(r, s *int, poke map[byte]int, appt string) {
	if poke[appt[*r]] == 0 {
		*s++
	}
	poke[appt[*r]]++
	*r++
}

func del(i, s *int, poke map[byte]int, appt string) {
	if poke[appt[*i]] == 1 {
		*s--
	}
	poke[appt[*i]]--
}

package main

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

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

	used := make(map[rune]bool)

	var count int
	var appt string
	fmt.Fscan(reader, &appt)

	for _, vl := range appt {
		if !used[vl] {
			count++
			used[vl] = true
		}
	}

	pokemons := make(map[byte]int)

	var mn int = n
	var s, r int

	for i := 0; i < n; i++ {
		for s < count && r < n {
			if pokemons[appt[r]] == 0 {
				s++
			}
			pokemons[appt[r]]++

			r++
		}
		if s == count {
			mn = min(mn, r-i)
		}

		if pokemons[appt[i]] == 1 {
			s--
		}

		pokemons[appt[i]]--
	}

	fmt.Println(mn)
}

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

package main

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

type poke struct {
	pos []int
	v   byte
	j   int
	max int
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	//	s := strings.Split(text, " ")

	//	c, _ := strconv.Atoi(s[0])

	text, _ = reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")

	v := map[byte]poke{}

	for i := range text {
		val, ok := v[text[i]]
		if ok == false {
			val = poke{make([]int, len(text)), text[i], 0, 0}
		}
		val.pos[val.max] = i
		val.max += 1
		v[text[i]] = val
	}
	m := len(text)

	for i := range text {
		curpos := i
		if i < (len(text) - 1) {
			if text[i+1] == text[i] {
				continue
			}
		}
		found := false
		for k, pok := range v {
			found = false
			for j := pok.j; j < pok.max; j++ {
				//for j, vv := range pok.pos[pok.j:pok.max] {
				vv := pok.pos[j]
				if vv >= i {
					if vv > curpos {
						curpos = vv
					}
					pok.j = j
					v[k] = pok
					found = true
					break
				}
			}
			if found == false {
				break
			}
		}
		if found {
			c := (curpos - i) + 1
			if c < m {
				m = c
			}
		}
	}

	fmt.Println(m)
}

package main

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

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

	used := make(map[rune]bool)

	var count int
	var appt string
	fmt.Fscan(reader, &appt)

	for _, vl := range appt {
		if !used[vl] {
			count++
			used[vl] = true
		}
	}

	pokemons := make(map[byte]int)

	var mn int = n
	var s, r int

	for i := 0; i < n; i++ {
		for r < n {
			if pokemons[appt[r]] == 0 {
				s++
			}
			pokemons[appt[r]]++

			if s == count {
				mn = min(mn, r-i+1)
				break
			}
			r++
		}

		if r != n-1 {
			r++
		}

		if pokemons[appt[i]] == 1 {
			s--
		}

		pokemons[appt[i]]--
	}

	fmt.Println(mn)
}

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

package main

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

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

	used := make(map[rune]bool)

	var count int
	var appt string
	fmt.Fscan(reader, &appt)

	for _, vl := range appt {
		if !used[vl] {
			count++
			used[vl] = true
		}
	}

	pokemons := make(map[byte]int)

	var mn int = n
	var s, r int

	for i := 0; i < n; i++ {
		for s < count && r < n {
			if pokemons[appt[r]] == 0 {
				s++
			}
			pokemons[appt[r]]++

			r++
		}
		if s == count {
			fmt.Println(i, r)
			mn = min(mn, r-i)
		}

		if pokemons[appt[i]] == 1 {
			s--
		}

		pokemons[appt[i]]--
	}

	fmt.Println(mn)
}

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

package main

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

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

	used := make(map[rune]bool)

	var count int
	var appt string
	fmt.Fscan(reader, &appt)

	for _, vl := range appt {
		if !used[vl] {
			count++
			used[vl] = true
		}
	}

	pokemons := make(map[byte]int)

	var mn int = n
	var s, r int

	for i := 0; i < n; i++ {
		for r < n {
			pokemons[appt[r]]++
			if pokemons[appt[r]] == 1 {
				s++
			}
			if s == count {
				mn = min(mn, r-i+1)

				break
			}
			r++
		}
		if r+1 != n {
			r++
		}
		if pokemons[appt[i]] == 1 {
			s--
		}

		pokemons[appt[i]]--
	}

	fmt.Println(mn)
}

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

package main

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

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

	used := make(map[rune]bool)

	var count int
	var appt string
	fmt.Fscan(reader, &appt)

	for _, vl := range appt {
		if !used[vl] {
			count++
			used[vl] = true
		}
	}

	pokemons := make(map[byte]int)

	var mn int = n
	var s, r int

	for i := 0; i < n; i++ {
		for r < n {
			pokemons[appt[r]]++
			if pokemons[appt[r]] == 1 {
				s++
			}
			if s == count {
				mn = min(mn, r-i+1)

				break
			}
			r++
		}
		if r != n-1 {
			r++
		}
		if pokemons[appt[i]] == 1 {
			s--
		}

		pokemons[appt[i]]--
	}

	fmt.Println(mn)
}

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

package main

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

type poke struct {
	pos []int
	v   byte
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	//	s := strings.Split(text, " ")

	//	c, _ := strconv.Atoi(s[0])

	text, _ = reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")

	v := map[byte]poke{}

	for i := range text {
		val, ok := v[text[i]]
		if ok == false {
			val = poke{[]int{}, text[i]}
		}
		val.pos = append(val.pos, i)
		v[text[i]] = val
	}
	m := len(text)

	for i := range text {
		curpos := i

		found := false
		for _, v := range v {
			found = false
			for _, vv := range v.pos {
				if vv >= curpos {
					curpos = vv
					found = true
					break
				}
			}
			if found == false {
				break
			}

		}
		if found {
			c := (curpos - i) + 1
			if c < m {
				m = c
			}
		}
	}

	fmt.Println(m)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	//	s := strings.Split(text, " ")

	//	c, _ := strconv.Atoi(s[0])

	text, _ = reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")

	v := map[byte]int{}

	for i := range text {
		v[text[i]]++
	}

	mv := len(text)
	mi := byte(0)

	for i, v := range v {
		if v < mv {
			mv = v
			mi = i
		}
	}

	m := len(text)
	lv := len(v)
	index := 0
	for i := 0; i < len(text); i++ {
		if text[i] == mi {
			index = i
			end := index
			start := index
			x := map[byte]bool{}
			for start > 0 {
				x[text[start]] = true
				if len(x) == lv {
					break
				}
				start--
			}

			for i := start; i <= end; i++ {
				x := map[byte]bool{}
				for j := i; j < len(text); j++ {
					x[text[j]] = true
					if len(x) == len(v) {
						c := j - i + 1
						if c < m {
							m = c
						}
					}
				}
			}
		}
	}

	fmt.Println(m)
}


Andi and Budi were given an assignment to tidy up their bookshelf of $$$n$$$ books. Each book is represented by the book title — a string $$$s_i$$$ numbered from $$$1$$$ to $$$n$$$, each with length $$$m$$$. Andi really wants to sort the book lexicographically ascending, while Budi wants to sort it lexicographically descending.Settling their fight, they decided to combine their idea and sort it asc-desc-endingly, where the odd-indexed characters will be compared ascendingly, and the even-indexed characters will be compared descendingly.A string $$$a$$$ occurs before a string $$$b$$$ in asc-desc-ending order if and only if in the first position where $$$a$$$ and $$$b$$$ differ, the following holds:  if it is an odd position, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$;  if it is an even position, the string $$$a$$$ has a letter that appears later in the alphabet than the corresponding letter in $$$b$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \cdot m \leq 10^6$$$). The $$$i$$$-th of the next $$$n$$$ lines contains a string $$$s_i$$$ consisting of $$$m$$$ uppercase Latin letters — the book title. The strings are pairwise distinct.

Output $$$n$$$ integers — the indices of the strings after they are sorted asc-desc-endingly.

NoteThe following illustrates the first example.

package main

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

type Book struct {
	name  string
	index int
}

type BookSorter struct {
	books []Book
}

func (sorter *BookSorter) Len() int {
	return len(sorter.books)
}

func (sorter *BookSorter) Less(i, j int) bool {
	for k := range sorter.books[i].name {
		if sorter.books[i].name[k] != sorter.books[j].name[k] {
			a := k%2 == 0
			b := sorter.books[i].name[k] < sorter.books[j].name[k]
			return (a && b) || (!a && !b)
		}
	}
	return false
}

func (sorter *BookSorter) Swap(i, j int) {
	sorter.books[i], sorter.books[j] = sorter.books[j], sorter.books[i]
}

var (
	reader = bufio.NewReader(os.Stdin)
	n, m   int
)

func main() {
	fmt.Fscan(reader, &n, &m)
	var (
		r []Book
		s string
	)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &s)
		r = append(r, Book{s, i + 1})
	}
	sort.Sort(&BookSorter{r})
	for _, book := range r {
		fmt.Print(book.index, " ")
	}
	fmt.Println()
}


A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly $$$n$$$ minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of $$$n$$$ numbers: $$$d_1, d_2, \dots, d_n$$$ ($$$-10^6 \le d_i \le 10^6$$$). The $$$i$$$-th element means that monster's hp (hit points) changes by the value $$$d_i$$$ during the $$$i$$$-th minute of each round. Formally, if before the $$$i$$$-th minute of a round the monster's hp is $$$h$$$, then after the $$$i$$$-th minute it changes to $$$h := h + d_i$$$.The monster's initial hp is $$$H$$$. It means that before the battle the monster has $$$H$$$ hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to $$$0$$$. Print -1 if the battle continues infinitely.

The first line contains two integers $$$H$$$ and $$$n$$$ ($$$1 \le H \le 10^{12}$$$, $$$1 \le n \le 2\cdot10^5$$$). The second line contains the sequence of integers $$$d_1, d_2, \dots, d_n$$$ ($$$-10^6 \le d_i \le 10^6$$$), where $$$d_i$$$ is the value to change monster's hp in the $$$i$$$-th minute of a round.

Print -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer $$$k$$$ such that $$$k$$$ is the first minute after which the monster is dead.

package main

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

func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int
	var h int64
	fmt.Fscanf(buf, "%d %d\n", &h, &n)
	mat := make([]int64, n+1)
	mat[0] = 0
	minn := int64(0)
	for i := 1; i <= n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i])
		mat[i] += mat[i-1]
		if i == 1 || mat[i] < minn {
			minn = mat[i]
		}
	}
	for i := 1; i <= n; i++ {
		if mat[i] + h <=0 {
			fmt.Printf("%d\n", i)
			return
		}
	}
	if mat[n] >= 0 {
		fmt.Printf("-1\n")
		return
	}
	hh := h + minn
	ans := 1 + (hh-1)/(0-mat[n])
	h += ans * mat[n]
	ans = ans * int64(n)
	//fmt.Printf("h=%d ans=%d\n", h,ans)

	for i := 1; h>0&&i <= n; i++ {
		ans++
		if mat[i]+h <= 0 {
			break
		}
	}
	fmt.Printf("%d\n", ans)

}

/*
1 10
10
1 1 2 1 1 1 2 1 1 1
1 1 1 1 1 1 1 1 1 1
1
1 1
*/

package main

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

type int = int64

type breakPoint struct {
	hours int
	sum   int
}

func solve(h int, a []int32) int {
	var r, sum int64

	L := len(a)

	j, t, k := -1, int64(0), -1
	bpts := make([]breakPoint, L+1)

	for i, n := range a {
		sum += int64(n)

		t += int64(n)

		if t < 0 || i == L-1 {
			k++
			bpts[k] = breakPoint{
				hours: int64(i - j),
				sum:   t,
			}

			t = 0
			j = i
		}

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	bpts = bpts[:k+1]

	c := h / -sum

	r += c * int64(len(a))

	ans := r

	winCondition := func(h int) (bool, int) {
		var r int64

		for _, point := range bpts {
			if h <= 0 {
				return true, r
			}
			r += point.hours
			h += point.sum
		}

		return h <= 0, r
	}

	left, right := int64(0), r-1

	for left < right-1 {
		//	fmt.Println(left, right)
		mid := (left + right) >> 1
		condition, res := winCondition(h + sum*mid)

		if condition {
			ans = res + mid*int64(len(a))
			right = mid
		} else {
			left = mid
		}
	}

	return ans
}

func toInt(buf []byte) int32 {
	n, mul := int32(0), int32(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int32(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int32, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

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

package main

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

func sum(d []int64) int64 {
	sum := int64(0)
	for _, elem := range d {
		sum += elem
	}
	return sum
}

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

func ceilDiv(x int64, y int64) int64 {
	return (x + y - 1) / y
}

func Solve(H int64, n int64, d []int64) int64 {
	prefix := int64(0)
	for i := int64(0); i < n; i++ {
		prefix += d[i]
		if H+prefix <= 0 {
			return i + 1
		}
	}
	sum := sum(d)
	if sum >= 0 {
		return -1
	}
	prefix = int64(0)
	minutes := int64(math.MaxInt64)
	for i := int64(0); i < n; i++ {
		prefix += d[i]
		cycles := ceilDiv(H+prefix, -sum)
		minutes = min(minutes, cycles*n+i+1)
	}
	return minutes
}

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

	var H, n int64
	fmt.Fscanf(reader, "%d %d\n", &H, &n)
	d := make([]int64, n)
	for i := int64(0); i < n; i++ {
		fmt.Fscanf(reader, "%d", &d[i])
	}
	fmt.Fprintf(writer, "%d\n", Solve(H, n, d))
}

package main

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

func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int
	var h int64
	fmt.Fscanf(buf, "%d %d\n", &h, &n)
	mat := make([]int64, n+1)
	mat[0] = 0
	minn := int64(0)
	for i := 1; i <= n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i])
		mat[i] += mat[i-1]
		if i == 1 || mat[i] < minn {
			minn = mat[i]
		}
	}
	for i := 1; i <= n; i++ {
		if mat[i] >= h {
			fmt.Printf("%d\n", i)
			return
		}
	}
	if mat[n] >= 0 {
		fmt.Printf("-1\n")
		return
	}
	hh := h + minn
	ans := 1 + (hh-1)/(0-mat[n])
	h += ans * mat[n]
	ans = ans * int64(n)
	//fmt.Printf("h=%d ans=%d\n", h,ans)

	for i := 1; h>0&&i <= n; i++ {
		ans++
		if mat[i]+h <= 0 {
			break
		}
	}
	fmt.Printf("%d\n", ans)

}

/*
1 10
10
1 1 2 1 1 1 2 1 1 1
1 1 1 1 1 1 1 1 1 1
1
1 1
*/

package main

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

type int = int64

type breakPoint struct {
	hours int
	sum   int
}

func solve(h int, a []int32) int {
	var r, sum int64

	L := len(a)

	j, t, k := -1, int64(0), -1
	bpts := make([]breakPoint, L+1)

	max := int32(-1)

	for i, n := range a {
		sum += int64(n)

		t += int64(n)

		if t < 0 || i == L-1 {
			k++
			bpts[k] = breakPoint{
				hours: int64(i - j),
				sum:   t,
			}

			t = 0
			j = i
		}

		if n > max {
			max = n
		}

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	bpts = bpts[:k+1]

	c := h / -sum
	if max > 0 && c >= int64(max>>1) {
		c -= int64(max >> 1)
	}

	r += c * int64(len(a))

	h += c * sum

	//	fmt.Println(max>>1, h/-sum, c)

	ans := r

	k = 0
	for ok := true; ok; {
		k++

		ok = false
		for i := len(bpts) - 1; i >= 0; i-- {
			r -= bpts[i].hours
			h -= bpts[i].sum

			if h <= 0 {
				ok = true
				ans = r
			}
		}
	}
	//fmt.Println(k)

	return ans
}

func toInt(buf []byte) int32 {
	n, mul := int32(0), int32(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int32(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int32, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

package main

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

func solve(h int, a []int) int {
	r := 0
	sum := 0
	//t := h
	for i, n := range a {
		sum += n

		//		t += n
		//1fmt.Println(t)

		if sum >= h {
			return i + 1
		}
	}

	if sum >= 0 {
		return -1
	}

	c := h/-sum - 1
	r += c * len(a)

	h += c * sum

	for i := 0; h > 0; i++ {
		h += a[i]
		r++
	}

	return r
}

func toInt(buf []byte) int {
	n, mul := 0, 1
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int(v-'0')
	}

	return mul * n
}

func main() {
	h, r := 0, 0
	fmt.Scan(&h, &r)

	a := make([]int, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

package main

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

type int = int64

func solve(h int, a []int) int {
	var r, sum int64
	//t := h
	for i, n := range a {
		sum += n

		//		t += n
		//1fmt.Println(t)

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	c := h/-sum - 1
	r += c * int64(len(a))

	h += c * sum

	//fmt.Println(h)

	for i := 0; h > 0; i++ {
		h += a[i]
		r++
	}

	return r
}

func toInt(buf []byte) int {
	n, mul := int64(0), int64(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int64(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

package main

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

type int = int64

type breakPoint struct {
	hours int
	sum   int
}

func solve(h int, a []int32) int {
	var r, sum int64

	L := len(a)

	j, t, k := -1, int64(0), -1
	bpts := make([]breakPoint, L+1)

	for i, n := range a {
		sum += int64(n)

		t += int64(n)

		if t < 0 || i == L-1 {
			k++
			bpts[k] = breakPoint{
				hours: int64(i - j),
				sum:   t,
			}

			t = 0
			j = i
		}

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	bpts = bpts[:k+1]

	c := h / -sum
	r += c * int64(len(a))

	h += c * sum

	var ans int

	k = 0
	for ok := true; ok; {
		k++
		if k > 50 {
			fmt.Println(bpts)
			return h
		}

		ok = false
		for i := len(bpts) - 1; i >= 0; i-- {
			r -= bpts[i].hours
			h -= bpts[i].sum

			if h <= 0 {
				ok = true
				ans = r
			}
		}
	}

	return ans
}

func toInt(buf []byte) int32 {
	n, mul := int32(0), int32(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int32(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int32, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

package main

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

type int = int64

type breakPoint struct {
	hours int
	sum   int
}

func solve(h int, a []int32) int {
	var r, sum int64

	L := len(a)

	j, t, k := -1, int64(0), -1
	bpts := make([]breakPoint, L+1)

	max := int64(-1)

	for i, n := range a {
		sum += int64(n)

		t += int64(n)

		if t < 0 || i == L-1 {
			k++
			bpts[k] = breakPoint{
				hours: int64(i - j),
				sum:   t,
			}

			t = 0
			j = i
		}

		if t > max {
			max = t
		}

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	bpts = bpts[:k+1]

	c := h / -sum
	if max > 0 && len(a) > 100000 {
		c -= int64(max)
	}

	r += c * int64(len(a))

	h += c * sum

	//	fmt.Println(max>>1, h/-sum, c)

	ans := r

	k = 0
	for ok := true; ok; {
		k++

		ok = false
		for i := len(bpts) - 1; i >= 0; i-- {
			r -= bpts[i].hours
			h -= bpts[i].sum

			if h <= 0 {
				ok = true
				ans = r
			}
		}
	}
	//fmt.Println(k)

	return ans
}

func toInt(buf []byte) int32 {
	n, mul := int32(0), int32(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int32(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int32, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

package main

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

type int = int64

type breakPoint struct {
	hours int
	sum   int
}

func solve(h int, a []int32) int {
	var r, sum int64

	L := len(a)

	j, t, k := -1, int64(0), -1
	bpts := make([]breakPoint, L+1)

	for i, n := range a {
		sum += int64(n)

		t += int64(n)

		if t < 0 || i == L-1 {
			k++
			bpts[k] = breakPoint{
				hours: int64(i - j),
				sum:   t,
			}

			t = 0
			j = i
		}

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	bpts = bpts[:k+1]

	c := h / -sum
	r += c * int64(len(a))

	h += c * sum

	var ans int

	k = 0
	for ok := true; ok; {
		k++
		if k > 5 {
			fmt.Println(bpts)
			return h
		}

		ok = false
		for i := len(bpts) - 1; i >= 0; i-- {
			r -= bpts[i].hours
			h -= bpts[i].sum

			if h <= 0 {
				ok = true
				ans = r
			}
		}
	}

	return ans
}

func toInt(buf []byte) int32 {
	n, mul := int32(0), int32(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int32(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int32, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

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

package main

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

func sum(d []int64) int64 {
	sum := int64(0)
	for _, elem := range d {
		sum += elem
	}
	return sum
}

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

func ceilDiv(x int64, y int64) int64 {
	return (x + y - 1) / y
}

func Solve(H int64, n int64, d []int64) int64 {
	sum := sum(d)
	if sum >= 0 {
		return -1
	}
	prefix := int64(0)
	for i := int64(0); i < n; i++ {
		prefix += d[i]
		if H+prefix <= 0 {
			return i + 1
		}
	}
	prefix = int64(0)
	minutes := int64(math.MaxInt64)
	for i := int64(0); i < n; i++ {
		prefix += d[i]
		cycles := ceilDiv(H+prefix, -sum)
		minutes = min(minutes, cycles*n+i+1)
	}
	return minutes
}

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

	var H, n int64
	fmt.Fscanf(reader, "%d %d\n", &H, &n)
	d := make([]int64, n)
	for i := int64(0); i < n; i++ {
		fmt.Fscanf(reader, "%d", &d[i])
	}
	fmt.Fprintf(writer, "%d\n", Solve(H, n, d))
}


Let's call the string beautiful if it does not contain a substring of length at least $$$2$$$, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not.Let's define cost of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first $$$3$$$ letters of the Latin alphabet (in lowercase).You are given a string $$$s$$$ of length $$$n$$$, each character of the string is one of the first $$$3$$$ letters of the Latin alphabet (in lowercase).You have to answer $$$m$$$ queries — calculate the cost of the substring of the string $$$s$$$ from $$$l_i$$$-th to $$$r_i$$$-th position, inclusive.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$ and the number of queries. The second line contains the string $$$s$$$, it consists of $$$n$$$ characters, each character one of the first $$$3$$$ Latin letters. The following $$$m$$$ lines contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — parameters of the $$$i$$$-th query.

For each query, print a single integer — the cost of the substring of the string $$$s$$$ from $$$l_i$$$-th to $$$r_i$$$-th position, inclusive.

NoteConsider the queries of the example test.  in the first query, the substring is baa, which can be changed to bac in one operation;  in the second query, the substring is baacb, which can be changed to cbacb in two operations;  in the third query, the substring is cb, which can be left unchanged;  in the fourth query, the substring is aa, which can be changed to ba in one operation.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var n, m int
	fmt.Fscan(in,&n,&m)
	var b []byte
	fmt.Fscan(in,&b)
	var f1 []byte
	f1 = []byte("abc")

	var cst [7][300005]int
	for i:=1;i<=6;i++{
		if i==1{
			f1 = []byte("abc")
		}
		if i==2{
			f1 = []byte("cba")
		}
		if i==3{
			f1 = []byte("bca")
		}
		if i==4{
			f1 = []byte("cab")
		}
		if i==5{
			f1 = []byte("bac")
		}
		if i==6{
			f1 = []byte("acb")
		}
		for j:=0;j<n;j++{
			v:=0
			if f1[j%3] != b[j]{
				v=1
			}
			cst[i][j+1]=cst[i][j] + v
		}
	}
	for i:=1;i<=m;i++{
		var l, r int
		fmt.Fscan(in,&l,&r)
		ans := 999999999
		for j:=1;j<=6;j++{
			if ans > cst[j][r]-cst[j][l-1]{
				ans = cst[j][r]-cst[j][l-1]
			}
		}
		fmt.Fprintln(out,ans)
	}
}

package main

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

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

func minWithin(c [6]int) int {
	result := c[0]
	for i := 1; i < 6; i++ {
		if result > c[i] {
			result = c[i]
		}
	}
	return result
}

func main() {
	defer out.Flush()

	var n, m int
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)

	var s string
	fmt.Fscan(in, &s)

	seeds := []string{
		"abc",
		"acb",
		"bac",
		"bca",
		"cab",
		"cba",
	}

	costs := make([][6]int, n)
	for i, seed := range seeds {
		acc := 0
		for j := 0; j < n; j++ {
			if seed[j%3] != s[j] {
				acc++
			}
			costs[j][i] = acc
		}
	}

	for i := 0; i < m; i++ {
		var l, r int
		fmt.Fscan(in, &l)
		fmt.Fscan(in, &r)
		l--
		r--

		var candi [6]int
		for j := 0; j < 6; j++ {
			left := 0
			if l > 0 {
				left = costs[l-1][j]
			}
			candi[j] = costs[r][j] - left
		}
		fmt.Fprintln(out, minWithin(candi))
	}
}

package main

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

var in = bufio.NewReader(os.Stdin)

func minWithin(c [6]int) int {
	result := c[0]
	for i := 1; i < 6; i++ {
		if result > c[i] {
			result = c[i]
		}
	}
	return result
}

func main() {
	var n, m int
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)

	var s string
	fmt.Fscan(in, &s)

	seeds := []string{
		"abc",
		"acb",
		"bac",
		"bca",
		"cab",
		"cba",
	}

	costs := make([][6]int, n)
	for i, seed := range seeds {
		acc := 0
		for j := 0; j < n; j++ {
			if seed[j%3] != s[j] {
				acc++
			}
			costs[j][i] = acc
		}
	}

	for i := 0; i < m; i++ {
		var l, r int
		fmt.Fscan(in, &l)
		fmt.Fscan(in, &r)
		l--
		r--

		var candi [6]int
		for j := 0; j < 6; j++ {
			left := 0
			if l > 0 {
				left = costs[l-1][j]
			}
			candi[j] = costs[r][j] - left
		}
		fmt.Println(minWithin(candi))
	}
}

package main

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

func CF1555D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	perm3 := []string{"abc", "acb", "bac", "bca", "cab", "cba"}

	var n,q,l,r int
	var s []byte
	fmt.Fscan(in, &n, &q, &s)
	sum := [6][]int{}

	for i,p := range perm3 {
		sum[i] = make([]int, n+1)
		for j,b := range s{
			sum[i][j+1] = sum[i][j]
			if b != p[j%3] {
				sum[i][j+1] ++
			}
		}
	}
	for ; q>0; q-- {
		fmt.Fscan(in, &l, &r)
		ans :=n
		for _,s := range sum {
			if c:= s[r] - s[l-1]; c<ans {
				ans =c
			}
		}
		fmt.Println(ans)
	}

}

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

package main
import (
    "fmt"
    "bufio"
    "io"
    "os"
)
const N int = 2e5+10
var n, m int
var s string
var rules = [6]string{"abc", "acb", "bac", "bca", "cab", "cba"}
var dp [N][6]int
func main() {
    var input io.Reader = bufio.NewReader(os.Stdin)
    fmt.Fscan(input, &n)
    fmt.Fscan(input, &m)
    fmt.Fscan(input, &s)
    for i := 0; i < n; i++ {
        for j := 0; j < 6; j++ {
            var value int = 0
            if s[i] != rules[j][i%3] {
                value = 1
            }
            dp[i][j] = value
            if i > 0 {
                dp[i][j] += dp[i-1][j]
            }
        }
    }
    var l, r int
    for ; m > 0; m-- {
        fmt.Fscan(input, &l)
        fmt.Fscan(input, &r)
        var ans int = 1e9
        for i := 0; i < 6; i++ {
            var value int = dp[r-1][i]
            if l > 1 {
                value -= dp[l-2][i]
            }
            if value < ans {
                ans = value
            }
        }
        fmt.Println(ans)
    }
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1555D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	perm3 := []string{"abc", "acb", "bac", "bca", "cab", "cba"}

	var n, q, l, r int
	var s []byte
	Fscan(in, &n, &q, &s)
	sum := [6][]int{}
	for i, p := range perm3 {
		sum[i] = make([]int, n+1)
		for j, b := range s {
			sum[i][j+1] = sum[i][j]
			if b != p[j%3] {
				sum[i][j+1]++
			}
		}
	}
	for ; q > 0; q-- {
		Fscan(in, &l, &r)
		ans := n
		for _, s := range sum {
			if c := s[r] - s[l-1]; c < ans {
				ans = c
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	var n, m int
	fmt.Fscan(in,&n,&m)
	var b []byte
	fmt.Fscan(in,&b)
	var f1 []byte
	f1 = []byte("abc")

	var cst [7][300005]int
	for i:=1;i<=6;i++{
		if i==1{
			f1 = []byte("abc")
		}
		if i==2{
			f1 = []byte("cba")
		}
		if i==3{
			f1 = []byte("bca")
		}
		if i==4{
			f1 = []byte("cab")
		}
		if i==5{
			f1 = []byte("bac")
		}
		if i==6{
			f1 = []byte("acb")
		}
		for j:=0;j<n;j++{
			v:=0
			if f1[j%3] != b[j]{
				v=1
			}
			cst[i][j+1]=cst[i][j] + v
		}
	}
	for i:=1;i<=m;i++{
		var l, r int
		fmt.Fscan(in,&l,&r)
		ans := 999999999
		for j:=1;j<=6;j++{
			if ans > cst[j][r]-cst[j][l-1]{
				ans = cst[j][r]-cst[j][l-1]
			}
		}
		fmt.Fprintln(out,ans)
	}
}


A tree is an undirected connected graph without cycles.Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).    For this rooted tree the array p is [2, 3, 3, 2]. Given a sequence p1, p2, ..., pn, one is able to restore a tree:  There must be exactly one index r that pr = r. A vertex r is a root of the tree.  For all other n - 1 vertices i, there is an edge between vertex i and vertex pi. A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.

The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).

In the first line print the minimum number of elements to change, in order to get a valid sequence. In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.

NoteIn the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.  In the second sample, the given sequence is already valid.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	skipOne := true
	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			w := e.to
			if t := vis[w]; t == 0 {
				f(w)
			} else if t == 2 || w == v {
				if t == 2 && !hasRoot {
					hasRoot = true
					a[e.i] = e.i
					continue
				}
				if w == v && skipOne {
					skipOne = false
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				a[e.i], vs = vs[0], vs[1:]
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	skipOne := true
	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				f(w)
			} else if vis[w] == 2 {
				if len(vs) > 1 || !hasRoot {
					if !hasRoot {
						hasRoot = true
						a[e.i] = e.i
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0]) // todo  remove this line
					a[e.i], vs = vs[0], vs[1:]
				}
			} else if w == v {
				if skipOne {
					skipOne = false
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0]) // todo  remove this line
				a[e.i], vs = vs[0], vs[1:]
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

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

func readInt() (result int) {
	var negative, started bool
READER_LOOP:
	for {
		char, err := stdReader.ReadByte()
		switch {
		case err != nil:
			break READER_LOOP
		case char == '-':
			negative = true
		case unicode.IsDigit(rune(char)):
			started = true
			result = result*10 + int(char&0xf)
		case started:
			break READER_LOOP
		}
	}
	if negative {
		result = -result
	}
	return
}

var maj, level []int

var cycles, loops []int

func dfs(node int) {
	level[node] = 1
	p := maj[node]
	switch level[p] {
	case 0:
		dfs(p)
	case 1:
		cycles = append(cycles, node)
	}
	level[node] = 2
}

func main() {
	n := readInt()
	maj = make([]int, n)
	level = make([]int, n)

	for i := range maj {
		maj[i] = readInt() - 1
		if maj[i] == i {
			loops = append(loops, i)
			level[i] = 2
		}
	}

	for i := 0; i < n; i++ {
		if level[i] == 0 {
			dfs(i)
		}
	}

	root, answer := -1, 0

	if len(loops) != 0 {
		root = loops[0]
		loops = loops[1:]
	} else {
		if len(cycles) != 0 {
			root = cycles[0]
			cycles = cycles[1:]
		} else {
			root = 0
		}
		maj[root] = root
		answer++
	}

	for _, n := range cycles {
		maj[n] = root
		answer++
	}

	for _, l := range loops {
		maj[l] = root
		answer++
	}

	fmt.Println(answer)
	for _, p := range maj {
		fmt.Printf("%d ", p+1)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	if hasRoot {
		Fprintln(out, len(vs)-1)
	} else {
		Fprintln(out, len(vs))
	}

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p && w <= v && (len(vs) > 1 || !hasRoot) {
				if !hasRoot {
					hasRoot = true
					a[e.i] = e.i
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				a[e.i], vs = vs[0], vs[1:]
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	cnt1, cnt2 := 0, 0
	cnt3 := 0

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p  {
				cnt3++
				if w <= v && (len(vs) > 1 || !hasRoot) {
					if !hasRoot {
						hasRoot = true
						//if a[e.i] == e.i {
						//	panic(Sprintln(1, e.i))
						//}
						a[e.i] = e.i
						//if modified[e.i] {
						//	panic(Sprintln(1, e.i))
						//}
						//modified[e.i]=true
						cnt1++
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0])
					//if a[e.i] == vs[0] {
					//	panic(Sprintln(2, e.i))
					//}
					a[e.i], vs = vs[0], vs[1:]
					cnt2++
					//if modified[e.i] {
					//	panic(Sprintln(2, e.i))
					//}
					//modified[e.i]=true
				}
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	if cnt1+cnt2 != ans {
		Fprintln(out, cnt1, cnt2, cnt3)
		//panic(Sprintln(cnt1, cnt2, ans))
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	if hasRoot {
		Fprintln(out, len(vs)-1)
	} else {
		Fprintln(out, len(vs))
	}

	modified := make([]bool, n+1)

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p && w <= v && (len(vs) > 1 || !hasRoot) {
				if !hasRoot {
					hasRoot = true
					//if a[e.i] == e.i {
					//	panic(Sprintln(1, e.i))
					//}
					a[e.i] = e.i
					if modified[e.i] {
						panic(Sprintln(1, e.i))
					}
					modified[e.i]=true
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				//if a[e.i] == vs[0] {
				//	panic(Sprintln(2, e.i))
				//}
				a[e.i], vs = vs[0], vs[1:]

				if modified[e.i] {
					panic(Sprintln(2, e.i))
				}
				modified[e.i]=true
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	if hasRoot {
		Fprintln(out, len(vs)-1)
	} else {
		Fprintln(out, len(vs))
	}

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p && w <= v && (len(vs) > 1 || !hasRoot) {
				if !hasRoot {
					hasRoot = true
					if a[e.i] == e.i {
						panic(Sprintln(1, e.i))
					}
					a[e.i] = e.i
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				if a[e.i] == vs[0] {
					panic(Sprintln(2, e.i))
				}
				a[e.i], vs = vs[0], vs[1:]
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	//cnt1, cnt2 := 0, 0
	//cnt3 := 0
	//c1, c2, c3 := 0, 0, 0

	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				f(w)
			} else if w == v || vis[w] == 2 {
				//cnt3++
				//if w < v {
				//	c1++
				//} else if w == v {
				//	c2++
				//} else {
				//	c3++
				//}
				if len(vs) > 1 || !hasRoot {
					if !hasRoot {
						hasRoot = true
						//if a[e.i] == e.i {
						//	panic(Sprintln(1, e.i))
						//}
						a[e.i] = e.i
						//if modified[e.i] {
						//	panic(Sprintln(1, e.i))
						//}
						//modified[e.i]=true
						//cnt1++
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0])
					//if a[e.i] == vs[0] {
					//	panic(Sprintln(2, e.i))
					//}
					a[e.i], vs = vs[0], vs[1:]
					//cnt2++
					//if modified[e.i] {
					//	panic(Sprintln(2, e.i))
					//}
					//modified[e.i]=true
				}
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	//println( c1, c2, c3)
	//if cnt1+cnt2 != ans {
	//	Fprintln(out, cnt1, cnt2, cnt3)
	//
	//	//panic(Sprintln(cnt1, cnt2, ans))
	//}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	cnt1, cnt2 := 0, 0

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p && w <= v && (len(vs) > 1 || !hasRoot) {
				if !hasRoot {
					hasRoot = true
					//if a[e.i] == e.i {
					//	panic(Sprintln(1, e.i))
					//}
					a[e.i] = e.i
					//if modified[e.i] {
					//	panic(Sprintln(1, e.i))
					//}
					//modified[e.i]=true
					cnt1++
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				//if a[e.i] == vs[0] {
				//	panic(Sprintln(2, e.i))
				//}
				a[e.i], vs = vs[0], vs[1:]
				cnt2++
				//if modified[e.i] {
				//	panic(Sprintln(2, e.i))
				//}
				//modified[e.i]=true
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	if cnt1+cnt2 != ans {
		Fprintln(out, cnt1, cnt2, ans)
		//panic(Sprintln(cnt1, cnt2, ans))
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	skipOne := true
	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				f(w)
			} else if vis[w] == 2 {
				if len(vs) > 1 || !hasRoot {
					if !hasRoot {
						hasRoot = true
						a[e.i] = e.i
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					a[e.i], vs = vs[0], vs[1:]
				}
			} else if w == v {
				if skipOne {
					skipOne = false
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				a[e.i], vs = vs[0], vs[1:]
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false

	debug := false

	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == 1 && w == 8276 {
			debug = true
		}
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	cnt1, cnt2 := 0, 0
	cnt3 := 0
	//c1, c2, c3 := 0, 0, 0

	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				f(w)
			} else if w == v || vis[w] == 2 {
				cnt3++
				if len(vs) > 1 || !hasRoot {
					if !hasRoot {
						hasRoot = true
						a[e.i] = e.i
						cnt1++
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0])
					a[e.i], vs = vs[0], vs[1:]
					cnt2++
				}
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	if debug {
		Fprintln(out, hasRoot, cnt1,cnt2,cnt3)
	}

	//println( c1, c2, c3)
	//if cnt1+cnt2 != ans {
	//	Fprintln(out, cnt1, cnt2, cnt3)
	//
	//	//panic(Sprintln(cnt1, cnt2, ans))
	//}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	skipOne := true
	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			w := e.to
			if t := vis[w]; t == 0 {
				f(w)
			} else if t == 2 || w == v {
				if t == 2 && !hasRoot {
					hasRoot = true
					a[e.i] = e.i
					continue
				}
				if w == v && skipOne {
					skipOne = false
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				a[e.i], vs = vs[0], vs[1:]
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			g[i] = append(g[i], edge{i, i})
		} else {
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
			merge(i, w)
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	Fprintln(out, len(vs)-1)

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p && w <= v && len(vs) > 1 {
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				a[e.i], vs = vs[0], vs[1:]
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	//cnt1, cnt2 := 0, 0
	//cnt3 := 0
	//c1, c2, c3 := 0, 0, 0

	vis := make([]int8, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				f(w, v)
			} else if w != p && (w == v || vis[w] == 2) {
				//cnt3++
				//if w < v {
				//	c1++
				//} else if w == v {
				//	c2++
				//} else {
				//	c3++
				//}
				if len(vs) > 1 || !hasRoot {
					if !hasRoot {
						hasRoot = true
						//if a[e.i] == e.i {
						//	panic(Sprintln(1, e.i))
						//}
						a[e.i] = e.i
						//if modified[e.i] {
						//	panic(Sprintln(1, e.i))
						//}
						//modified[e.i]=true
						//cnt1++
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0])
					//if a[e.i] == vs[0] {
					//	panic(Sprintln(2, e.i))
					//}
					a[e.i], vs = vs[0], vs[1:]
					//cnt2++
					//if modified[e.i] {
					//	panic(Sprintln(2, e.i))
					//}
					//modified[e.i]=true
				}
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] ==0 {
			f(i, 0)
		}
	}
	//println( c1, c2, c3)
	//if cnt1+cnt2 != ans {
	//	Fprintln(out, cnt1, cnt2, cnt3)
	//
	//	//panic(Sprintln(cnt1, cnt2, ans))
	//}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	rt := 1
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			rt = i
		} else {
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
			fa[find(i)] = find(w)
		}
		a[i] = w
	}
	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] && i != fa[find(rt)] {
			vs = append(vs, i)
		}
	}
	Fprintln(out, len(vs))

	vis := make([]bool, n+1)
	var f func(v, fa int)
	f = func(v, fa int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != fa && w == e.i {
				a[w], vs = vs[0], vs[1:]
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	for _, v := range vs {
		a[v] = rt
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	cnt1, cnt2 := 0, 0
	cnt3 := 0
	c1, c2, c3 := 0, 0, 0

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p {
				cnt3++
				if w < v {
					c1++
				} else if w == v {
					c2++
				} else {
					c3++
				}
				if w <= v && (len(vs) > 1 || !hasRoot) {
					if !hasRoot {
						hasRoot = true
						//if a[e.i] == e.i {
						//	panic(Sprintln(1, e.i))
						//}
						a[e.i] = e.i
						//if modified[e.i] {
						//	panic(Sprintln(1, e.i))
						//}
						//modified[e.i]=true
						cnt1++
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0])
					//if a[e.i] == vs[0] {
					//	panic(Sprintln(2, e.i))
					//}
					a[e.i], vs = vs[0], vs[1:]
					cnt2++
					//if modified[e.i] {
					//	panic(Sprintln(2, e.i))
					//}
					//modified[e.i]=true
				}
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	if cnt1+cnt2 != ans {
		Fprintln(out, cnt1, cnt2, cnt3)
		Fprintln(out, c1, c2, c3)
		//panic(Sprintln(cnt1, cnt2, ans))
	}
	Fprint(out, a[1:]...)
}

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

package main

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

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

func readInt() (result int) {
	var negative, started bool
READER_LOOP:
	for {
		char, err := stdReader.ReadByte()
		switch {
		case err != nil:
			break READER_LOOP
		case char == '-':
			negative = true
		case unicode.IsDigit(rune(char)):
			started = true
			result = result*10 + int(char&0xf)
		case started:
			break READER_LOOP
		}
	}
	if negative {
		result = -result
	}
	return
}

var maj, level []int

var cycles, loops []int

func dfs(node int) {
	p := maj[node]
	switch level[p] {
	case 0:
		level[p] = 1
		dfs(p)
	case 1:
		cycles = append(cycles, node)
	}
	level[node] = 2
}

func main() {
	n := readInt()
	maj = make([]int, n)
	level = make([]int, n)

	for i := range maj {
		maj[i] = readInt() - 1
		if maj[i] == i {
			loops = append(loops, i)
			level[i] = 2
		}
	}

	for i := 0; i < n; i++ {
		if level[i] == 0 {
			dfs(i)
		}
	}

	if len(loops) == 0 {
		loops = []int{0}
	}

	for _, n := range cycles {
		maj[n] = loops[0]
	}

	for i := 1; i < len(loops); i++ {
		maj[loops[i]] = loops[0]
	}

	fmt.Println(len(cycles) + len(loops) - 1)
	for _, p := range maj {
		fmt.Printf("%d ", p+1)
	}
}

package main

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

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

func readInt() (result int) {
	var negative, started bool
READER_LOOP:
	for {
		char, err := stdReader.ReadByte()
		switch {
		case err != nil:
			break READER_LOOP
		case char == '-':
			negative = true
		case unicode.IsDigit(rune(char)):
			started = true
			result = result*10 + int(char&0xf)
		case started:
			break READER_LOOP
		}
	}
	if negative {
		result = -result
	}
	return
}

var maj, level []int

var cycles, loops []int

func dfs(node int) {
	p := maj[node]
	switch level[p] {
	case 0:
		level[p] = 1
		dfs(p)
	case 1:
		cycles = append(cycles, node)
	}
	level[node] = 2
}

func main() {
	n := readInt()
	maj = make([]int, n)
	level = make([]int, n)

	for i := range maj {
		maj[i] = readInt() - 1
		if maj[i] == i {
			loops = append(loops, i)
			level[i] = 2
		}
	}

	for i := 0; i < n; i++ {
		if level[i] == 0 {
			dfs(i)
		}
	}

	if len(loops) == 0 {
		loops = []int{1}
	}

	for _, n := range cycles {
		maj[n] = loops[0]
	}

	for i := 1; i < len(loops); i++ {
		maj[loops[i]] = loops[0]
	}

	fmt.Println(len(cycles) + len(loops) - 1)
	for _, p := range maj {
		fmt.Printf("%d ", p+1)
	}
}

package main

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

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

func readInt() (result int) {
	var negative, started bool
READER_LOOP:
	for {
		char, err := stdReader.ReadByte()
		switch {
		case err != nil:
			break READER_LOOP
		case char == '-':
			negative = true
		case unicode.IsDigit(rune(char)):
			started = true
			result = result*10 + int(char&0xf)
		case started:
			break READER_LOOP
		}
	}
	if negative {
		result = -result
	}
	return
}

var maj, level []int

var cycles, loops []int

func dfs(node int) {
	p := maj[node]
	switch level[p] {
	case 0:
		level[p] = 1
		dfs(p)
	case 1:
		cycles = append(cycles, node)
	}
	level[node] = 2
}

func main() {
	n := readInt()
	maj = make([]int, n)
	level = make([]int, n)

	for i := range maj {
		maj[i] = readInt() - 1
		if maj[i] == i {
			loops = append(loops, i)
			level[i] = 2
		}
	}

	for i := 0; i < n; i++ {
		if level[i] == 0 {
			dfs(i)
		}
	}

	if len(loops) == 0 {
		if len(cycles) != 0 {
			loops = []int{cycles[0]}
			cycles = cycles[1:]
		} else {
			loops = []int{0}
		}
	}

	for _, n := range cycles {
		maj[n] = loops[0]
	}

	for i := 1; i < len(loops); i++ {
		maj[loops[i]] = loops[0]
	}

	fmt.Println(len(cycles) + len(loops) - 1)
	for _, p := range maj {
		fmt.Printf("%d ", p+1)
	}
}

package main

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

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

func readInt() (result int) {
	var negative, started bool
READER_LOOP:
	for {
		char, err := stdReader.ReadByte()
		switch {
		case err != nil:
			break READER_LOOP
		case char == '-':
			negative = true
		case unicode.IsDigit(rune(char)):
			started = true
			result = result*10 + int(char&0xf)
		case started:
			break READER_LOOP
		}
	}
	if negative {
		result = -result
	}
	return
}

var maj, level []int

var cycles, loops []int

func dfs(node int) {
	p := maj[node]
	switch level[p] {
	case 0:
		level[p] = 1
		dfs(p)
	case 1:
		cycles = append(cycles, node)
	}
	level[node] = 2
}

func main() {
	n := readInt()
	maj = make([]int, n)
	level = make([]int, n)

	for i := range maj {
		maj[i] = readInt() - 1
		if maj[i] == i {
			loops = append(loops, i)
			level[i] = 2
		}
	}

	for i := 0; i < n; i++ {
		if level[i] == 0 {
			dfs(i)
		}
	}

	if len(loops) == 0 {
		loops = []int{0}
	}

	for _, n := range cycles {
		maj[n] = loops[0]
	}

	fmt.Println("loops")
	fmt.Println(loops)
	fmt.Println("cycles")
	fmt.Println(cycles)

	for i := 1; i < len(loops); i++ {
		maj[loops[i]] = loops[0]
	}

	fmt.Println(len(cycles) + len(loops) - 1)
	for _, p := range maj {
		fmt.Printf("%d ", p+1)
	}
}


Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.

The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items.

Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.

NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one.

package main

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

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

const MAX = 100001

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

	n := nextInt()
	a := make([]int, n)
	haveNums := make([]bool, n+1)
	used := make([]bool, n+1)

	for i := 0; i < n; i++ {
		a[i] = nextInt()
		if a[i] <= n {
			haveNums[a[i]] = true
		}
	}

	nextA := 1

	for i := 0; i < n; i++ {
		if a[i] > n || used[a[i]] {
			for haveNums[nextA] || used[nextA] {
				nextA++
			}
			used[nextA] = true
			print(nextA, " ")
		} else {
			used[a[i]] = true
			print(a[i], " ")
		}
	}
	println()
}

func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}

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

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

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

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

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

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

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

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

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

	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d ", &arr[i])
		if arr[i] <= n {
			groups[arr[i]]++
		}
	}

	frees := make([]int, n+1)
	stackPointer := 0
	for i := 1; i <= n; i++ {
		if groups[i] == 0 {
			frees[stackPointer] = i
			stackPointer++
		}
	}

	for i, val := range arr {
		if val > n || groups[val] > 1 {
			stackPointer--
			firstPermute := frees[stackPointer]
			arr[i] = firstPermute
			groups[firstPermute]++
			if val <= n {
				groups[val]--
			}
		}
	}

	lastI := len(arr) - 1
	for i, val := range arr {
		if i < lastI {
			fmt.Printf("%d ", val)
		} else {
			fmt.Printf("%d", val)
		}
	}
	println()
}

func findFree(heystack []int) int {
	for i := range heystack {
		if heystack[i] == 0 {
			return i
		}
	}
	return 0
}