This is an interactive problem.The jury has a permutation $$$p$$$ of length $$$n$$$ and wants you to guess it. For this, the jury created another permutation $$$q$$$ of length $$$n$$$. Initially, $$$q$$$ is an identity permutation ($$$q_i = i$$$ for all $$$i$$$).You can ask queries to get $$$q_i$$$ for any $$$i$$$ you want. After each query, the jury will change $$$q$$$ in the following way:   At first, the jury will create a new permutation $$$q'$$$ of length $$$n$$$ such that $$$q'_i = q_{p_i}$$$ for all $$$i$$$.  Then the jury will replace permutation $$$q$$$ with pemutation $$$q'$$$. You can make no more than $$$2n$$$ queries in order to quess $$$p$$$.

The first line of input contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases.

NoteIn the first test case the hidden permutation $$$p = [4, 2, 1, 3]$$$.Before the first query $$$q = [1, 2, 3, 4]$$$ so answer for the query will be $$$q_3 = 3$$$.Before the second query $$$q = [4, 2, 1, 3]$$$ so answer for the query will be $$$q_2 = 2$$$.Before the third query $$$q = [3, 2, 4, 1]$$$ so answer for the query will be $$$q_4 = 1$$$.In the second test case the hidden permutation $$$p = [1, 3, 4, 2]$$$.Empty strings are given only for better readability. There will be no empty lines in the testing system.

package main

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

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

func main() {
	defer out.Flush()

	var tc int
	fmt.Fscan(in, &tc)
	for ; tc > 0; tc-- {
		var n int
		fmt.Fscan(in, &n)

		fmt.Fprintln(out, "? 1")
		out.Flush()
		var k int
		fmt.Fscan(in, &k)

		ring := make([]int, 0, n)
		seen := make([]bool, n+1)
		perm := make([]int, n+1)
		pos := 1
		rots := 0

		ring = append(ring, 1)
		seen[1] = true

		for pos <= n {
			rots++
			fmt.Fprintln(out, "?", pos)
			out.Flush()
			fmt.Fscan(in, &k)
			if !seen[k] {
				seen[k] = true
				ring = append(ring, k)
				continue
			}
			i := (len(ring) - 1 + (rots-2)*(len(ring)-1)) % len(ring)
			for j := 0; j < len(ring); j++ {
				perm[pos] = ring[i]
				pos = ring[i]
				i = (i + 1) % len(ring)
			}
			ring = ring[0:0]
			for pos = 2; pos <= n && perm[pos] != 0; pos++ {
			}
		}
		out.WriteString("!")
		for _, p := range perm[1:] {
			fmt.Fprintf(out, " %d", p)
		}
		out.WriteString("\n")
		out.Flush()
	}
}

package main

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

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

	ask := func(x int) int {
		fmt.Printf("? %d\n", x+1)
		return readNum(reader) - 1
	}

	for tc > 0 {
		tc--
		n := readNum(reader)
		res := solve(n, ask)
		var buf bytes.Buffer
		buf.WriteString("!")
		for i := 0; i < n; i++ {
			buf.WriteString(fmt.Sprintf(" %d", res[i]))
		}
		buf.WriteByte('\n')
		fmt.Print(buf.String())
	}
}

func normalize(s string) string {

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

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(n int, ask func(int) int) []int {
	P := make([]int, n)
	for i := 0; i < n; i++ {
		P[i] = -1
	}
	for i := 0; i < n; i++ {
		if P[i] < 0 {
			var cycle []int
			ans := ask(i)
			x := ask(i)
			cycle = append(cycle, x)
			for x != ans {
				x = ask(i)
				cycle = append(cycle, x)
			}
			for j := 0; j < len(cycle); j++ {
				P[cycle[j]] = cycle[(j+1)%len(cycle)] + 1
			}
		}
	}
	return P
}

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	// defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)

	var (
		cnt  = 0
		used = make([]bool, n+1)
		p    = make([]int, n+1)
	)
	for i := 1; i <= n; i++ {
		if used[i] {
			continue
		}
		s := make([]int, 0)
		for {
			x := req(i)
			cnt++
			if len(s) == 0 || x != s[0] {
				s = append(s, x)
			} else {
				break
			}
		}
		j := (len(s) - (cnt % len(s))) % len(s)
		for range s {
			// printf("@@@ MY J: %v\n", j)
			// writer.Flush()
			if j == len(s)-1 {
				p[s[j]] = s[0]
			} else {
				p[s[j]] = s[j+1]
			}
			j = (j + 1) % len(s)
		}
		for _, e := range s {
			used[e] = true
		}
	}
	printf("! ")
	for i := 1; i <= n; i++ {
		printf("%v ", p[i])
	}
	printf("\n")
	writer.Flush()
}

func req(i int) (x int) {
	printf("? %v\n", i)
	writer.Flush()
	scan(&x)
	return
}

package main

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

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

func main() {
	defer out.Flush()

	var tc int
	fmt.Fscan(in, &tc)
	for ; tc > 0; tc-- {
		var n int
		fmt.Fscan(in, &n)

		fmt.Fprintln(out, "? 1")
		out.Flush()
		var k int
		fmt.Fscan(in, &k)

		ring := make([]int, 0, n)
		seen := make([]bool, n+1)
		perm := make([]int, n+1)
		pos := 1
		rots := 0

		for pos <= n {
			rots++
			fmt.Fprintln(out, "?", pos)
			out.Flush()
			fmt.Fscan(in, &k)
			if !seen[k] {
				seen[k] = true
				ring = append(ring, k)
				continue
			}
			i := (len(ring) - 1 + (rots-2)*(len(ring)-1)) % len(ring)
			for j := 0; j < len(ring); j++ {
				perm[pos] = ring[i]
				pos = ring[i]
				i = (i + 1) % len(ring)
			}
			ring = ring[0:0]
			for pos = 2; pos <= n && perm[pos] != 0; pos++ {
			}
		}
		out.WriteString("!")
		for _, p := range perm[1:] {
			fmt.Fprintf(out, " %d", p)
		}
		out.WriteString("\n")
		out.Flush()
	}
}

package main

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

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

func main() {
	defer out.Flush()

	var tc int
	fmt.Fscan(in, &tc)
	for ; tc > 0; tc-- {
		var n int
		fmt.Fscan(in, &n)

		fmt.Fprintln(out, "? 1")
		out.Flush()
		var k int
		fmt.Fscan(in, &k)

		ring := make([]int, 0, n)
		seen := make([]bool, n+1)
		perm := make([]int, n+1)
		pos := 1
		rots := 0

		for pos <= n {
			rots++
			fmt.Fprintln(out, "?", pos)
			out.Flush()
			fmt.Fscan(in, &k)
			if !seen[k] {
				seen[k] = true
				ring = append(ring, k)
				continue
			}
			i := (len(ring) - 1 + (rots-2)*(len(ring)-1)) % len(ring)
			for j := 0; j < len(ring); j++ {
				perm[pos] = ring[i]
				pos = ring[i]
				i = (i + 1) % len(ring)
			}
			ring = ring[0:0]
			for pos = 2; pos <= n && perm[pos] != 0; pos++ {
			}
		}
		fmt.Fprintln(out, "!", perm[1:])
		out.Flush()
	}
}

package main

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

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

	ask := func(x int) int {
		fmt.Printf("? %d\n", x+1)
		return readNum(reader) - 1
	}

	for tc > 0 {
		tc--
		n := readNum(reader)
		res := solve(n, ask)
		var buf bytes.Buffer
		buf.WriteString("!")
		for i := 0; i < n; i++ {
			buf.WriteString(fmt.Sprintf(" %d", res[i]))
		}
		buf.WriteByte('\n')
		fmt.Print(buf.String())
	}
}

func normalize(s string) string {

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

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(n int, ask func(int) int) []int {
	P := make([]int, n)
	for i := 0; i < n; i++ {
		P[i] = -1
	}
	for i := 0; i < n; i++ {
		if P[i] < 0 {
			var cycle []int
			ans := ask(i)
			x := ask(i)
			cycle = append(cycle, x)
			for x != ans {
				x = ask(i)
				cycle = append(cycle, x)
			}
			for j := 0; j < len(cycle); j++ {
				P[cycle[j]] = cycle[(j+1)%len(cycle)]
			}
		}
	}
	return P
}


Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).

The first input line contains four integer numbers n, t1, t2, k (1 ≤ n, t1, t2 ≤ 1000; 1 ≤ k ≤ 100) — the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly. Each of the following n lines contains two integers. The i-th (1 ≤ i ≤ n) line contains space-separated integers ai, bi (1 ≤ ai, bi ≤ 1000) — the speeds which the participant number i chose.

Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.

Note  First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2·3·0.5 + 4·3 > 4·3·0.5 + 2·3.

package main

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

func scanInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	x, _ := strconv.Atoi(scanner.Text())
	return x
}

type Contestant struct {
	mushroom float64;
	position int;
}
type Contestants []Contestant

func (arr Contestants) Len() int {
	return len(arr)
}
func (arr Contestants) Swap(i, j int) {
	arr[i], arr[j] = arr[j], arr[i]
}
func (arr Contestants) Less(i, j int) bool {
	if arr[i].mushroom != arr[j].mushroom {
		return arr[i].mushroom > arr[j].mushroom
	}
	return arr[i].position < arr[j].position
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n := scanInt(scanner)
	t1, t2 := float64(scanInt(scanner)), float64(scanInt(scanner))
	k := scanInt(scanner)
	contestants := make([]Contestant, n)
	for i := range contestants {
		a, b := float64(scanInt(scanner)), float64(scanInt(scanner))
		// x := a*t1 + float64(100-k)/100*b*t2
		// y := b*t1 + float64(100-k)/100*a*t2
		x := float64(100-k)/100*a*t1 + b*t2
		y := float64(100-k)/100*b*t1 + a*t2
		if x > y {
			contestants[i].mushroom = x
		} else {
			contestants[i].mushroom = y
		}
		contestants[i].position = i+1
	}
	sort.Sort(Contestants(contestants))
	for _, contestant := range contestants {
		writer.WriteString(fmt.Sprintf("%d %.2f\n",
				contestant.position, contestant.mushroom))
	}
}

package main

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

func scanInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	x, _ := strconv.Atoi(scanner.Text())
	return x
}

type Contestant struct {
	mushroom float64;
	position int;
}
type Contestants []Contestant

func (arr Contestants) Len() int {
	return len(arr)
}
func (arr Contestants) Swap(i, j int) {
	arr[i], arr[j] = arr[j], arr[i]
}
func (arr Contestants) Less(i, j int) bool {
	if arr[i].mushroom != arr[j].mushroom {
		return arr[i].mushroom > arr[j].mushroom
	}
	return arr[i].position < arr[j].position
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n := scanInt(scanner)
	t1, t2 := float64(scanInt(scanner)), float64(scanInt(scanner))
	k := scanInt(scanner)
	contestants := make([]Contestant, n)
	for i := range contestants {
		a, b := float64(scanInt(scanner)), float64(scanInt(scanner))
		x := a*t1 + float64(100-k)/100*b*t2
		y := b*t1 + float64(100-k)/100*a*t2
		if x > y {
			contestants[i].mushroom = x
		} else {
			contestants[i].mushroom = y
		}
		contestants[i].position = i+1
	}
	sort.Sort(Contestants(contestants))
	for _, contestant := range contestants {
		writer.WriteString(fmt.Sprintf("%d %.2f\n",
				contestant.position, contestant.mushroom))
	}
}


This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $$$s$$$).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters.

In the first line print one integer $$$res$$$ ($$$1 \le res \le n$$$) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps. In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array $$$c$$$ of length $$$n$$$, where $$$1 \le c_i \le res$$$ and $$$c_i$$$ means the color of the $$$i$$$-th character.

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n int
	var s string
	fmt.Scanf("%d\n%s\n", &n, &s)

	l := make([]int, 26)
	cols := make([]int, 0, n)
	req := 0
	for _, c := range s {
		m := 0
		for i := int(c-'a') + 1; i < 26; i++ {
			m = max(m, l[i])
		}
		cols = append(cols, m+1)
		l[int(c-'a')] = m + 1
		req = max(req, m+1)
	}

	fmt.Println(req)

	t := new(strings.Builder)
	for _, c := range cols {
		fmt.Fprintf(t, "%d ", c)
	}
	fmt.Println(t.String())
}

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

package main

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

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

func main () {
	in := bufio.NewReader(os.Stdin);
	out := bufio.NewWriter(os.Stdout);
	var n int;
	var s string;

	fmt.Fscanln(in, &n);
	fmt.Fscanln(in, &s);
	var maxs [26]int;
	d := make([]int, n);
	ans := 0;
	for i := 0; i < n; i++ {
		for j := s[i] + 1; j <= 'z'; j++ {
			d[i] = Max(d[i], maxs[j - 'a'] + 1);
		}
		if (d[i] == 0) {
			d[i] = 1;
		}
		if (d[i] > ans) {
			ans = d[i];
		}
		maxs[s[i] - 'a'] = Max(maxs[s[i] - 'a'], d[i]);
	}
	fmt.Fprintln(out, ans);
	for _, x := range d {
		fmt.Fprint(out, x, " ");
	}
	out.Flush();
}

package main

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

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

func main () {
	in := bufio.NewReader(os.Stdin);
	out := bufio.NewWriter(os.Stdout);
	var n int;
	var s string;

	fmt.Fscanln(in, &n);
	fmt.Fscanln(in, &s);
	var maxs [26]int;
	d := make([]int, n);
	ans := 0;
	for i := 0; i < n; i++ {

		for j := s[i] + 1; j <= 'z'; j++ {
			d[i] = Max(d[i], maxs[j - 'a'] + 1);
		}
		if (d[i] > ans) {
			ans = d[i];
		}
		maxs[s[i] - 'a'] = Max(maxs[s[i] - 'a'], d[i]);
	}
	fmt.Fprintln(out, ans);
	for _, x := range d {
		fmt.Fprint(out, x, " ");
	}
	out.Flush();
}

package main

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

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

func main () {
	in := bufio.NewReader(os.Stdin);
	out := bufio.NewWriter(os.Stdout);
	var n int;
	var s string;

	fmt.Fscanln(in, &n);
	fmt.Fscanln(in, &s);
	var maxs [26]int;
	d := make([]int, n);
	ans := 0;
	for i := 0; i < n; i++ {

		for j := s[i]; j <= 'z'; j++ {
			d[i] = Max(d[i], maxs[j - 'a'] + 1);
		}
		if (d[i] > ans) {
			ans = d[i];
		}
		maxs[s[i] - 'a'] = Max(maxs[s[i] - 'a'], d[i]);
	}
	for _, x := range d {
		fmt.Fprint(out, x, " ");
	}
	out.Flush();
}

package main

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

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

func main () {
	in := bufio.NewReader(os.Stdin);
	out := bufio.NewWriter(os.Stdout);
	var n int;
	var s string;

	fmt.Fscanln(in, &n);
	fmt.Fscanln(in, &s);
	var maxs [26]int;
	d := make([]int, n);
	ans := 0;
	for i := 0; i < n; i++ {

		for j := s[i]; j <= 'z'; j++ {
			d[i] = Max(d[i], maxs[j - 'a'] + 1);
		}
		if (d[i] > ans) {
			ans = d[i];
		}
		maxs[s[i] - 'a'] = Max(maxs[s[i] - 'a'], d[i]);
	}
	fmt.Fprintln(out, ans);
	for _, x := range d {
		fmt.Fprint(out, x, " ");
	}
	out.Flush();
}


Lee bought some food for dinner time, but Lee's friends eat dinner in a deadly way. Lee is so scared, he doesn't want to die, at least not before seeing Online IOI 2020...There are $$$n$$$ different types of food and $$$m$$$ Lee's best friends. Lee has $$$w_i$$$ plates of the $$$i$$$-th type of food and each friend has two different favorite types of food: the $$$i$$$-th friend's favorite types of food are $$$x_i$$$ and $$$y_i$$$ ($$$x_i \ne y_i$$$).Lee will start calling his friends one by one. Whoever is called will go to the kitchen and will try to eat one plate of each of his favorite food types. Each of the friends will go to the kitchen exactly once.The only problem is the following: if a friend will eat at least one plate of food (in total) then he will be harmless. But if there is nothing left for him to eat (neither $$$x_i$$$ nor $$$y_i$$$), he will eat Lee instead $$$\times\_\times$$$.Lee can choose the order of friends to call, so he'd like to determine if he can survive dinner or not. Also, he'd like to know the order itself.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5$$$; $$$1 \le m \le 2 \cdot 10^5$$$) — the number of different food types and the number of Lee's friends.  The second line contains $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^6$$$) — the number of plates of each food type. The $$$i$$$-th line of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$) — the favorite types of food of the $$$i$$$-th friend.

If Lee can survive the dinner then print ALIVE (case insensitive), otherwise print DEAD (case insensitive). Also, if he can survive the dinner, print the order Lee should call friends. If there are multiple valid orders, print any of them.

NoteIn the first example, any of the following orders of friends are correct : $$$[1, 3, 2]$$$, $$$[3, 1, 2]$$$, $$$[2, 3, 1]$$$, $$$[3, 2, 1]$$$.In the second example, Lee should call the second friend first (the friend will eat a plate of food $$$1$$$) and then call the first friend (the friend will eat a plate of food $$$2$$$). If he calls the first friend sooner than the second one, then the first friend will eat one plate of food $$$1$$$ and food $$$2$$$ and there will be no food left for the second friend to eat.

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n, m := readTwoNums(reader)
	W := readNNums(reader, n)
	F := make([][]int, m)
	for i := 0; i < m; i++ {
		F[i] = readNNums(reader, 2)
	}
	res := solve(W, F)
	if len(res) == 0 {
		fmt.Println("DEAD")
		return
	}
	fmt.Println("ALIVE")
	var buf bytes.Buffer
	for i := 0; i < len(res); i++ {
		buf.WriteString(fmt.Sprintf("%d ", res[i]))
	}
	fmt.Println(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(W []int, friends [][]int) []int {
	n := len(W)
	m := len(friends)

	freq := make([]int, n)
	adj := make([][]int, n)
	for i := 0; i < n; i++ {
		adj[i] = make([]int, 0, 3)
	}
	for i, f := range friends {
		f[0]--
		f[1]--
		x, y := f[0], f[1]
		freq[x]++
		freq[y]++
		adj[x] = append(adj[x], i)
		adj[y] = append(adj[y], i)
	}
	que := make([]int, n)
	vis := make([]bool, n)
	var end int
	for i := 0; i < n; i++ {
		if freq[i] <= W[i] {
			vis[i] = true
			que[end] = i
			end++
		}
	}

	ok := make([]bool, m)
	res := make([]int, 0, m)
	var front int

	for front < end {
		x := que[front]
		front++
		for _, i := range adj[x] {
			if !ok[i] {
				ok[i] = true
				res = append(res, i+1)
				f := friends[i]
				y := f[0] ^ f[1] ^ x
				freq[y]--
				if freq[y] <= W[y] && !vis[y] {
					que[end] = y
					end++
					vis[y] = true
				}
			}
		}
	}

	for i := 0; i < n; i++ {
		if !vis[i] {
			return nil
		}
	}
	reverse(res)
	return res
}

func reverse(arr []int) {
	for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
		arr[i], arr[j] = arr[j], arr[i]
	}
}


Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length ai.Mishka can put a box i into another box j if the following conditions are met:  i-th box is not put into another box;  j-th box doesn't contain any other boxes;  box i is smaller than box j (ai < aj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.Help Mishka to determine the minimum possible number of visible boxes!

The first line contains one integer n (1 ≤ n ≤ 5000) — the number of boxes Mishka has got. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the side length of i-th box.

Print the minimum possible number of visible boxes.

NoteIn the first example it is possible to put box 1 into box 2, and 2 into 3.In the second example Mishka can put box 2 into box 3, and box 4 into box 1.

package main

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

func solve() {
	n := readInt()
	m := make(map[int]int)
	max := -1
	for i := 0; i < n; i++ {
		a := readInt()
		m[a] += 1
		if m[a] > max {
			max = m[a]
		}
	}
	fmt.Println(max)
}

var scanner *bufio.Scanner

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

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

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

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

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	var ans, tmp int
	cnt := make(map[int]int, 5000)
	for ; n > 0; n-- {
		fmt.Scan(&tmp)
		cnt[tmp]++
		if cnt[tmp] > ans {
			ans = cnt[tmp]
		}
	}
	fmt.Println(ans)
}

package main

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

var a [5000]int32
var b [5000]bool
var reader SReader

func main() {
	reader.Init()
	n := reader.ReadInt()
	for i := int32(0); i < n; i++ {
		a[i] = reader.ReadInt()
		b[i] = true
	}

	a2 := Slice(a[:n])
	sort.Sort(a2)

	nLeft := n
	for x := int32(1); ; x++ {
		nSize := IntMax
		for i := n - 1; i >= 0; i-- {
			if !b[i] { continue }
			if a[i] >= nSize { continue }
			nSize = a[i]
			nLeft--
			b[i] = false
		}

		if nLeft == 0 {
			fmt.Println(x)
			break
		}
	}
}

const (
	IntMax = int32(^uint32(0) >> 1)
	IntMin = ^IntMax
)

// reader
type SReader struct {
	file *os.File
	scanner *bufio.Scanner
}

func (this *SReader) Init() {
	this.file = os.Stdin
	this.scanner = bufio.NewScanner(this.file)
	this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int32 {
	this.scanner.Scan()
	n, err:= strconv.ParseInt(this.scanner.Text(), 10, 32)
	if err != nil {
		panic(err)
	}
	return int32(n)
}

// sort
type Slice []int32

func (a Slice) Len() int {
	return len(a)
}

func (a Slice) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

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

package main

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

var a [5000]int64
var b [5000]bool
var reader SReader

type Int int64
type Uint uint64

func main() {
	reader.Init()
	n := reader.ReadInt()
	for i := int64(0); i < n; i++ {
		a[i] = reader.ReadInt()
		b[i] = true
	}

	a2 := Slice(a[:n])
	sort.Sort(a2)

	nLeft := n
	for x := int64(1); ; x++ {
		nSize := IntMax
		for i := n - 1; i >= 0; i-- {
			if !b[i] { continue }
			if a[i] >= nSize { continue }
			nSize = a[i]
			nLeft--
			b[i] = false
		}

		if nLeft == 0 {
			fmt.Println(x)
			break
		}
	}
}

const (
	IntMax = int64(^uint64(0) >> 1)
	IntMin = ^IntMax
)

// reader
type SReader struct {
	file *os.File
	scanner *bufio.Scanner
}

func (this *SReader) Init() {
	this.file = os.Stdin
	this.scanner = bufio.NewScanner(this.file)
	this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int64 {
	this.scanner.Scan()
	n, err:= strconv.ParseInt(this.scanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return n
}

// sort
type Slice []int64

func (a Slice) Len() int {
	return len(a)
}

func (a Slice) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

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

package main

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

var a [5000]int32
var b [5000]bool
var reader SReader

func main() {
	reader.Init()
	n := reader.ReadInt()
	for i := int32(0); i < n; i++ {
		a[i] = reader.ReadInt()
		b[i] = true
	}

	a2 := Slice(a[:n])
	sort.Sort(a2)

	nLeft := n
	for x := int32(1); ; x++ {
		nSize := IntMax
		for i := n - 1; i >= 0; i-- {
			if !b[i] { continue }
			if a[i] >= nSize { continue }
			nSize = a[i]
			nLeft--
			b[i] = false
		}

		if nLeft == 0 {
			fmt.Println(x)
			break
		}
	}
}

const (
	IntMax = int32(^uint32(0) >> 1)
	IntMin = ^IntMax
)

// reader
type SReader struct {
	file *os.File
	scanner *bufio.Scanner
}

func (this *SReader) Init() {
	this.file = os.Stdin
	this.scanner = bufio.NewScanner(this.file)
	this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int32 {
	this.scanner.Scan()
	n, err:= strconv.ParseInt(this.scanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return int32(n)
}

// sort
type Slice []int32

func (a Slice) Len() int {
	return len(a)
}

func (a Slice) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

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

//  URL: http://codeforces.com/contest/903/problem/C
//  PROBLEM RESTATEMENT
//      Given boxes of width a[1], a[2] ... a[n], a[i] ∈ [1, 10^9].
//      Box a[i] can be placed in a[j] if a[j] > a[i] and contains no other
//      boxes.
//      What is the minimum number of piles of boxes that can be formed?
//  APPROACH
//      (1) Assume there are no duplicates. The answer is 1 -> take the
//          smallest box, place it in the next smallest, and so on.
//      (2) Assume there is one duplicate. We cannot add this duplicate to the
//          existing pile, so we create a new pile.
//      (3) By induction, the # of piles is equal to the maximally occurring
//          element.

package main

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

func main() {
	reader, writer := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var n, a int
	fmt.Fscanf(reader, "%d\n", &n)
	m := make(map[int]int)
	maxCount := 0
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d ", &a)
		m[a] += 1
		if m[a] > maxCount {
			maxCount = m[a]
		}
	}
	fmt.Fprintf(writer, "%d\n", maxCount)
}

package main

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

func Init() {
}

func Solve(io *FastIO) {
	N := io.NextInt()

	freq := make(map[int]int)
	most := 0
	for i := 0; i < N; i++ {
		A := io.NextInt()

		freq[A]++
		most = Max(most, freq[A])
	}
	io.Println(most)
}

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

type FastIO struct {
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}

func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = (res * 10) + int(c-'0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c-'0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}

func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextInt()
	}
	return arr
}

func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}

func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextLong()
	}
	return arr
}

func (io *FastIO) NextString() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}

func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}

func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}

func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}

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

func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	var ans, tmp int
	cnt := make(map[int]int, 5000)
	for ; n >= 0; n-- {
		fmt.Scan(&tmp)
		cnt[tmp]++
		if cnt[tmp] > ans {
			ans = cnt[tmp]
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

func main() {
	var a, b, c int
	r := make(map[int]bool, 1e5)
	fmt.Scan(&a, &b, &c)
	for i := 1; ; i++ {
		if c == a*10/b {
			fmt.Println(i)
			return
		}
		a = a * 10 % b
		if !r[a] {
			r[a] = true
		} else {
			break
		}
	}
	fmt.Println(-1)
}


Eric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.Given a graph $$$G=(V,E)$$$, an independent set is a subset of vertices $$$V' \subset V$$$ such that for every pair $$$u,v \in V'$$$, $$$(u,v) \not \in E$$$ (i.e. no edge in $$$E$$$ connects two vertices from $$$V'$$$).An edge-induced subgraph consists of a subset of edges $$$E' \subset E$$$ and all the vertices in the original graph that are incident on at least one edge in the subgraph.Given $$$E' \subset E$$$, denote $$$G[E']$$$ the edge-induced subgraph such that $$$E'$$$ is the edge set of the subgraph. Here is an illustration of those definitions:  In order to help his students get familiar with those definitions, he leaves the following problem as an exercise:Given a tree $$$G=(V,E)$$$, calculate the sum of $$$w(H)$$$ over all except null edge-induced subgraph $$$H$$$ of $$$G$$$, where $$$w(H)$$$ is the number of independent sets in $$$H$$$. Formally, calculate $$$\sum \limits_{\emptyset \not= E' \subset E} w(G[E'])$$$.Show Eric that you are smarter than his students by providing the correct answer as quickly as possible. Note that the answer might be large, you should output the answer modulo $$$998,244,353$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$), representing the number of vertices of the graph $$$G$$$. Each of the following $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \not= v$$$), describing edges of the given tree. It is guaranteed that the given edges form a tree.

Output one integer, representing the desired value modulo $$$998,244,353$$$.

NoteFor the second example, all independent sets are listed below.

package main

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

const mod = 998244353

var (
    graph [][]int
    dp [][]int64
    n int
)

func dfs(u, parent int) {
    for i := 0; i < 4; i++ {
        dp[u][i] = 1
    }
    tmp := int64(1)
    for i := 0; i < len(graph[u]); i++ {
        v := graph[u][i]
        if v == parent {
            continue
        }
        dfs(v, u)
        notLinkCnt := (dp[v][0] + dp[v][1] + dp[v][2]) % mod
        dp[u][0] = dp[u][0] * notLinkCnt % mod
        dp[u][1] = dp[u][1] * (dp[v][0] + notLinkCnt*2) % mod
        dp[u][2] = dp[u][2] * (notLinkCnt + dp[v][1] + dp[v][3]) % mod
        dp[u][3] = dp[u][3] * notLinkCnt % mod
        tmp = tmp * notLinkCnt % mod
    }
    dp[u][1] = (dp[u][1] - tmp + mod) % mod
    dp[u][2] = (dp[u][2] - tmp + mod) % mod
}

func main() {
    defer writer.Flush()
    n = reader.NextInt()
    dp = make([][]int64, n+1)
    graph = make([][]int, n+1)
    for i := 1; i <= n; i++ {
        dp[i] = make([]int64, 4)
        graph[i] = []int{}
    }
    for i := 1; i < n; i++ {
        u, v := reader.NextInt(), reader.NextInt()
        graph[u] = append(graph[u], v)
        graph[v] = append(graph[v], u)
    }
    dfs(1, 1)
    ans := (dp[1][0] + dp[1][1] + dp[1][2] - 1 + mod) % mod
    fmt.Println(ans)
}

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	maxCap := 2 << 20
	buf := make([]byte, maxCap)
	s.Buffer(buf, maxCap)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

package main

import "fmt"

const mod = 998244353

var (
    graph [][]int
    dp [][]int64
    n int
    ans int64
)

func dfs(u, parent int) {
    dp[u][0], dp[u][1] = 1, 1
    for i := 0; i < len(graph[u]); i++ {
        v := graph[u][i]
        if v == parent {
            continue
        }
        dfs(v, u)
        dp[u][0] = dp[u][0] * (1 + dp[v][1] + dp[v][0]) % mod
        dp[u][1] = dp[u][1] * (1 + dp[v][0]) % mod
    }
    ans = (ans + dp[u][0] + dp[u][1]) % mod
}

func main() {
    _, _ = fmt.Scanf("%d", &n)
    ans = 0
    dp = make([][]int64, n+1)
    graph = make([][]int, n+1)
    for i := 1; i <= n; i++ {
        dp[i] = make([]int64, 2)
        graph[i] = []int{}
    }
    for i := 1; i < n; i++ {
        var u, v int
        _, _ = fmt.Scanf("%d%d", &u, &v)
        graph[u] = append(graph[u], v)
        graph[v] = append(graph[v], u)
    }
    dfs(1, 1)
    fmt.Println(ans)
    ans = (ans - int64(n*2) + mod) % mod
    fmt.Println(ans)
}

package main

import "fmt"

const mod = 998244353

var (
    graph [][]int
    dp [][]int64
    n int
    ans int64
)

func dfs(u, parent int) {
    dp[u][0], dp[u][1] = 1, 1
    for i := 0; i < len(graph[u]); i++ {
        v := graph[u][i]
        if v == parent {
            continue
        }
        dfs(v, u)
        dp[u][0] = dp[u][0] * (1 + dp[v][1] + dp[v][0]) % mod
        dp[u][1] = dp[u][1] * (1 + dp[v][0]) % mod
    }
    ans = (ans + dp[u][0] + dp[u][1]) % mod
}

func main() {
    _, _ = fmt.Scan(&n)
    ans = 0
    dp = make([][]int64, n+1)
    graph = make([][]int, n+1)
    for i := 1; i <= n; i++ {
        dp[i] = make([]int64, 2)
        graph[i] = []int{}
    }
    for i := 1; i < n; i++ {
        var u, v int
        _, _ = fmt.Scan(&u, &v)
        graph[u] = append(graph[u], v)
        graph[v] = append(graph[v], u)
    }
    dfs(1, 1)
    ans = (ans - int64(n*2) + mod) % mod
    fmt.Println(ans)
}

package main

import "fmt"

const mod int64 = 998244353

var (
    graph [][]int
    dp [][]int64
    n int
    ans int64
)

func dfs(u, parent int) {
    dp[u][0], dp[u][1] = 1, 1
    for i := 0; i < len(graph[u]); i++ {
        v := graph[u][i]
        if v == parent {
            continue
        }
        dfs(v, u)
        dp[u][0] = dp[u][0] * (1 + dp[v][1] + dp[v][0]) % mod
        dp[u][1] = dp[u][1] * (1 + dp[v][0]) % mod
    }
    ans = (ans + dp[u][0] + dp[u][1]) % mod
}

func main() {
    _, _ = fmt.Scanf("%d", &n)
    ans = 0
    dp = make([][]int64, n+1)
    graph = make([][]int, n+1)
    for i := 1; i <= n; i++ {
        dp[i] = make([]int64, 2)
        graph[i] = []int{}
    }
    for i := 1; i < n; i++ {
        var u, v int
        _, _ = fmt.Scanf("%d%d", &u, &v)
        graph[u] = append(graph[u], v)
        graph[v] = append(graph[v], u)
    }
    dfs(1, 1)
    ans = (ans - int64(n*2) + mod) % mod
    fmt.Println(ans)
}

package main

import "fmt"

const mod = 998244353

var (
    graph [][]int
    dp [][]int64
    n int
    ans int64
)

func dfs(u, parent int) {
    dp[u][0], dp[u][1] = 1, 1
    for i := 0; i < len(graph[u]); i++ {
        v := graph[u][i]
        if v == parent {
            continue
        }
        dfs(v, u)
        dp[u][0] = dp[u][0] * (1 + dp[v][1] + dp[v][0]) % mod
        dp[u][1] = dp[u][1] * (1 + dp[v][0]) % mod
    }
    fmt.Println(u, dp[u][0], dp[u][1])
    ans = (ans + dp[u][0] + dp[u][1]) % mod
}

func main() {
    _, _ = fmt.Scanf("%d", &n)
    ans = 0
    dp = make([][]int64, n+1)
    graph = make([][]int, n+1)
    for i := 1; i <= n; i++ {
        dp[i] = make([]int64, 2)
        graph[i] = []int{}
    }
    for i := 1; i < n; i++ {
        var u, v int
        _, _ = fmt.Scanf("%d%d", &u, &v)
        graph[u] = append(graph[u], v)
        graph[v] = append(graph[v], u)
    }
    dfs(1, 1)
    ans = (ans - int64(n*2) + mod) % mod
    fmt.Println(ans)
}

package main

import "fmt"

const mod = 998244353

var (
    graph [][]int
    dp [][]int64
    n int
    ans int64
)

func dfs(u, parent int) {
    dp[u][0], dp[u][1] = 1, 1
    for i := 0; i < len(graph[u]); i++ {
        v := graph[u][i]
        if v == parent {
            continue
        }
        dfs(v, u)
        dp[u][0] = dp[u][0] * (1 + dp[v][1] + dp[v][0]) % mod
        dp[u][1] = dp[u][1] * (1 + dp[v][0]) % mod
    }
    ans = (ans + dp[u][0] + dp[u][1]) % mod
}

func main() {
    _, _ = fmt.Scanf("%d", &n)
    ans = 0
    dp = make([][]int64, n+1)
    graph = make([][]int, n+1)
    for i := 1; i <= n; i++ {
        dp[i] = make([]int64, 2)
        graph[i] = []int{}
    }
    for i := 1; i < n; i++ {
        var u, v int
        _, _ = fmt.Scanf("%d%d", &u, &v)
        graph[u] = append(graph[u], v)
        graph[v] = append(graph[v], u)
    }
    dfs(1, 1)
    ans = (ans - int64(n*2) + mod) % mod
    fmt.Println(ans)
}

package main

import "fmt"

const mod = 998244353

var (
    graph [][]int
    dp [][]int64
    n int
    ans int64
)

func dfs(u, parent int) {
    dp[u][0], dp[u][1] = 1, 1
    for i := 0; i < len(graph[u]); i++ {
        v := graph[u][i]
        if v == parent {
            continue
        }
        dfs(v, u)
        dp[u][0] = dp[u][0] * (1 + dp[v][1] + dp[v][0]) % mod
        dp[u][1] = dp[u][1] * (1 + dp[v][0]) % mod
    }
    ans = (ans + dp[u][0] + dp[u][1]) % mod
}

func main() {
    _, _ = fmt.Scanf("%d", &n)
    ans = 0
    dp = make([][]int64, n+1)
    graph = make([][]int, n+1)
    for i := 1; i <= n; i++ {
        dp[i] = make([]int64, 2)
        graph[i] = []int{}
    }
    for i := 1; i < n; i++ {
        var u, v int
        _, _ = fmt.Scanf("%d%d", &u, &v)
        graph[u] = append(graph[u], v)
        graph[v] = append(graph[v], u)
    }
    for i := 1; i <= n; i++ {
        fmt.Println(graph[i])
    }
    dfs(1, 1)
    ans = (ans - int64(n*2) + mod) % mod
    fmt.Println(ans)
}

package main

import "fmt"

const mod = 998244353

var (
    graph [][]int
    dp [][]int64
    n int
)

func dfs(u, parent int) {
    for i := 0; i < 4; i++ {
        dp[u][i] = 1
    }
    tmp := int64(1)
    for i := 0; i < len(graph[u]); i++ {
        v := graph[u][i]
        if v == parent {
            continue
        }
        dfs(v, u)
        notLinkCnt := (dp[v][0] + dp[v][1] + dp[v][2]) % mod
        dp[u][0] = dp[u][0] * notLinkCnt % mod
        dp[u][1] = dp[u][1] * (dp[v][0] + notLinkCnt*2) % mod
        dp[u][2] = dp[u][2] * (notLinkCnt + dp[v][1] + dp[v][3]) % mod
        dp[u][3] = dp[u][3] * notLinkCnt % mod
        tmp = tmp * notLinkCnt % mod
    }
    dp[u][1] = (dp[u][1] - tmp + mod) % mod
    dp[u][2] = (dp[u][2] - tmp + mod) % mod
}

func main() {
    _, _ = fmt.Scan(&n)
    dp = make([][]int64, n+1)
    graph = make([][]int, n+1)
    for i := 1; i <= n; i++ {
        dp[i] = make([]int64, 4)
        graph[i] = []int{}
    }
    for i := 1; i < n; i++ {
        var u, v int
        _, _ = fmt.Scanf("%d %d", &u, &v)
        graph[u] = append(graph[u], v)
        graph[v] = append(graph[v], u)
    }
    dfs(1, 1)
    ans := (dp[1][0] + dp[1][1] + dp[1][2] - 1 + mod) % mod
    fmt.Println(ans)
}


Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.  Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.

If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print  - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.

NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is  - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is  - 1.

package main

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

func main() {
	var n int
	fmt.Scan(&n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	costs := make([]int64, n+1)
	for i:=0;i<n;i++ {
		costs[i+1] = readInt64(scanner)
	}
	words := make([]string, n+1)
	reverseWords := make([]string, n+1)
	words[0] = ""
	reverseWords[0] = ""
	for i:=1;i<=n;i++ {
		words[i] = readString(scanner)
		reverseWords[i] = reverse(words[i])
	}
	DP := make([][]int64, n+1)
	DP[0] = make([]int64, 2)
	for i:=1;i<=n;i++ {
		DP[i] = make([]int64, 2)
		DP[i][0] = math.MaxInt64
		DP[i][1] = math.MaxInt64
	}
	for i:=1;i<=n;i++ {
		was := false
		if words[i] >= words[i-1] && DP[i-1][0] != math.MaxInt64 {
			DP[i][0] = DP[i-1][0]
			was = true
		}
		if words[i] >= reverseWords[i-1] && DP[i-1][1] != math.MaxInt64 {
			DP[i][0] = min(DP[i][0], DP[i-1][1])
			was = true
		}
		if reverseWords[i] >= words[i-1] && DP[i-1][0] != math.MaxInt64 {
			DP[i][1] = DP[i-1][0] + costs[i]
			was = true
		}
		if reverseWords[i] >= reverseWords[i-1] && DP[i-1][1] != math.MaxInt64 {
			DP[i][1] = min(DP[i][1], DP[i-1][1] + costs[i])
			was = true
		}
		if !was {
			fmt.Println("-1")
			return
		}
	}
	fmt.Println(min(DP[n][0], DP[n][1]))
}

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

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

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

func readInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	value, _ := strconv.Atoi(scanner.Text())
	return value
}

func readInt64(scanner *bufio.Scanner) int64 {
	scanner.Scan()
	value, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return value
}

package main

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

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

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

func smaller(s string, t string) bool {
	ns := len(s)
	nt := len(t)
	i := 0
	for (i < ns) && (i < nt) && (s[i] == t[i]) {
		i++
	}
	if i == ns {
		return i <= nt
	}
	if i == nt {
		return false
	}
	return s[i] < t[i]
}

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

const maxn = 100005
const inf = int64(20000000000000000)

var n int
var c [maxn]int64
var s, r [maxn]string
var f [maxn][2]int64

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

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

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

	for i := 1; i <= n; i++ {
		in.Scan()
		c[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}

	for i := 1; i <= n; i++ {
		in.Scan()
		s[i] = in.Text()
		r[i] = rev(s[i])
	}

	f[1][0] = 0
	f[1][1] = c[1]
	for i := 1; i < n; i++ {
		f[i+1][0] = inf
		f[i+1][1] = inf
		if f[i][0] < inf {
			if smaller(s[i], s[i+1]) {
				f[i+1][0] = min(f[i+1][0], f[i][0])
			}
			if smaller(s[i], r[i+1]) {
				f[i+1][1] = min(f[i+1][1], f[i][0]+c[i+1])
			}
		}
		if f[i][1] < inf {
			if smaller(r[i], s[i+1]) {
				f[i+1][0] = min(f[i+1][0], f[i][1])
			}
			if smaller(r[i], r[i+1]) {
				f[i+1][1] = min(f[i+1][1], f[i][1]+c[i+1])
			}
		}
	}

	res := min(f[n][0], f[n][1])
	if res < inf {
		out.WriteString(strconv.FormatInt(res, 10))

	} else {
		out.WriteString("-1")
	}
	out.WriteByte('\n')

}

// http://codeforces.com/problemset/problem/706/C

package main

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

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

	return b
}

func min3 (a, b, c int64) int64 {
	return min(min(a, b), c)
}

func InvStr(str string) string {
	data := []byte(str)
	n := len(data)
	for i := 0; i <= (n - 1)/ 2; i++ {
		data[i], data[n - i - 1] = data[n - i - 1], data[i]
	}

	return string(data)
}

func main() {
	var n int
	var tmp int64

	input := bufio.NewReaderSize(os.Stdin, 1 << 20)

	fmt.Fscanln(input, &n)
	c := make([]int64, n)
	strs := make([]string, n)
	strinv := make([]string, n)
	dp := make([][]int64, n)

	for i := 0; i < n; i++ {
		if i == n - 1 {
			fmt.Fscanln(input, &tmp)
		} else {
			fmt.Fscan(input, &tmp)
		}
		c[i] = tmp
		dp[i] = make([]int64, 2)
		dp[i][0], dp[i][1] = math.MaxInt64, math.MaxInt64
	}

	for i := 0; i < n; i++ {
		var str string
		fmt.Fscanln(input, &str)

		strs[i] = str
		strinv[i] = InvStr(str)
	}

	// Solve
	if strings.Compare(strs[0], strs[1]) <= 0 {
		dp[1][0] = 0
	}
	if strings.Compare(strinv[0], strs[1]) <= 0 {
		dp[1][0] = min(c[0], dp[1][0])
	}

	if strings.Compare(strs[0], strinv[1]) <= 0 {
		dp[1][1] = c[1]
	}

	if strings.Compare(strinv[0], strinv[1]) <= 0 {
		dp[1][1] = min(c[1] + c[0], dp[1][1])
	}

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

		if strings.Compare(strs[i - 1], strs[i]) <= 0 && dp[i - 1][0] != math.MaxInt64 {
			dp[i][0] = dp[i - 1][0] + 0
		}
		if strings.Compare(strinv[i - 1], strs[i]) <= 0 && dp[i - 1][1] != math.MaxInt64 {
			dp[i][0] = min(dp[i - 1][1] + 0, dp[i][0])
		}

		if strings.Compare(strs[i - 1], strinv[i]) <= 0 && dp[i - 1][0] != math.MaxInt64 {
			dp[i][1] = dp[i - 1][0] + c[i]
		}

		if strings.Compare(strinv[i - 1], strinv[i]) <= 0 && dp[i - 1][1] != math.MaxInt64 {
			dp[i][1] = min(dp[i - 1][1] + c[i], dp[i][1])
		}

		if dp[i][0] == math.MaxInt64 && dp[i][1] == math.MaxInt64 {
			fmt.Println(-1)
			return
		}
	}

	if ans := min(dp[n - 1][0], dp[n - 1][1]); ans == math.MaxInt64 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

package main

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

const EMPTY = -2

var (
	n  int
	c  []int64
	s  []string
	dp []int64
)

func reverseStr(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 calcEnergy(start int, reverse bool) int64 {
	if start+1 >= len(c) {
		// For the last element the amount of energy needed is just that (or zero if not reversing)
		if reverse {
			return c[start]
		} else {
			return 0
		}
	}
	dpIdx := start
	if reverse {
		dpIdx += n
	}
	if dp[dpIdx] != EMPTY {
		return dp[dpIdx]
	}
	var res1 int64 = -1
	var res2 int64 = -1
	if reverse {
		if strings.Compare(reverseStr(s[start]), s[start+1]) <= 0 {
			res1 = calcEnergy(start+1, false)
			if res1 != -1 {
				res1 += c[start]
			}
		}
		if strings.Compare(reverseStr(s[start]), reverseStr(s[start+1])) <= 0 {
			res2 = calcEnergy(start+1, true)
			if res2 != -1 {
				res2 += c[start]
			}
		}
	} else {
		if strings.Compare(s[start], s[start+1]) <= 0 {
			res1 = calcEnergy(start+1, false)
		}
		if strings.Compare(s[start], reverseStr(s[start+1])) <= 0 {
			res2 = calcEnergy(start+1, true)
		}
	}
	dp[dpIdx] = minEnergy(res1, res2)
	return dp[dpIdx]
}

func minEnergy(en1 int64, en2 int64) int64 {
	if en2 != -1 && (en1 == -1 || en2 < en1) {
		return en2
	} else {
		return en1
	}
}

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

	fmt.Fscanf(reader, "%d ", &n)
	c = make([]int64, n)
	for i := range c {
		fmt.Fscanf(reader, "%d ", &c[i])
	}
	s = make([]string, n)
	for i := range s {
		fmt.Fscanf(reader, "%s ", &s[i])
	}
	dp = make([]int64, n*2)
	for i := range dp {
		dp[i] = EMPTY
	}

	res1 := calcEnergy(0, false)
	res2 := calcEnergy(0, true)
	fmt.Println(minEnergy(res1, res2))
}

package main

import (
	"bufio"
	. "container/heap"
	. "fmt"
	"io"
	"os"
)

type hPair struct {
	x int64
	y int
}
type pairHeap []hPair

func (h pairHeap) Len() int              { return len(h) }
func (h pairHeap) Less(i, j int) bool    { return h[i].x < h[j].x || h[i].x == h[j].x && h[i].y < h[j].y }
func (h pairHeap) Swap(i, j int)         { h[i], h[j] = h[j], h[i] }
func (h *pairHeap) Push(v interface{})   { *h = append(*h, v.(hPair)) }
func (h *pairHeap) Pop() (v interface{}) { n := len(*h); *h, v = (*h)[:n-1], (*h)[n-1]; return }

// github.com/EndlessCheng/codeforces-go
func Sol706C(reader io.Reader, writer io.Writer) {
	const inf int64 = 1e18
	reverse := func(ss string) string {
		n := len(ss)
		s := make([]byte, n)
		for i := range s {
			s[i] = ss[n-1-i]
		}
		return string(s)
	}
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	costs := make([]int, n)
	for i := range costs {
		Fscan(in, &costs[i])
	}
	type neighbor struct {
		vertex int
		weight int
	}
	g := make([][]neighbor, 2*n+2)
	var prev, rPrev, cur, rCur string
	for i, c := range costs {
		Fscan(in, &cur)
		rCur = reverse(cur)
		if prev == "" {
			g[0] = []neighbor{{1, 0}, {2, c}}
		} else {
			if prev <= cur {
				g[2*i-1] = append(g[2*i-1], neighbor{2*i + 1, 0})
			}
			if prev <= rCur {
				g[2*i-1] = append(g[2*i-1], neighbor{2*i + 2, c})
			}
			if rPrev <= cur {
				g[2*i] = append(g[2*i], neighbor{2*i + 1, 0})
			}
			if rPrev <= rCur {
				g[2*i] = append(g[2*i], neighbor{2*i + 2, c})
			}
		}
		prev, rPrev = cur, rCur
	}
	g[2*n-1] = []neighbor{{2*n + 1, 0}}
	g[2*n] = []neighbor{{2*n + 1, 0}}

	dist := make([]int64, 2*n+2)
	for i := range dist {
		dist[i] = inf
	}
	dist[0] = 0
	visited := make([]bool, 2*n+2)
	h := &pairHeap{}
	Push(h, hPair{0, 0})
	for h.Len() > 0 {
		p := Pop(h).(hPair)
		v := p.y
		if visited[v] {
			continue
		}
		visited[v] = true
		for _, e := range g[v] {
			w := e.vertex
			if newDist := dist[v] + int64(e.weight); newDist < dist[w] {
				dist[w] = newDist
				Push(h, hPair{newDist, w})
			}
		}
	}
	ans := dist[2*n+1]
	if ans == inf {
		ans = -1
	}
	Fprintln(out, ans)
}

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

package main

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

/*
	2
	1 2
	ba
	ac
 */

 /**

  */

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanln(reader, &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	fmt.Fscanln(reader)
	str := make([]string, n)
	reverse := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanln(reader, &str[i])
		reverse[i] = reverseString(str[i])
	}

	var ret [][]int64
	ret = make([][]int64, n)
	for i := 0; i < n; i++ {
		ret[i] = make([]int64, 2) // 0 表示没有reverse 1 表示reverse
	}

	ret[0][0] = 0
	ret[0][1] = int64(a[0])
	for i := 1; i < n; i++ {
		var ret0, ret1 int64 = math.MaxInt64, math.MaxInt64
		if ret[i-1][0] != math.MaxInt64 {
			if strings.Compare(str[i], str[i-1]) >= 0 {
				ret0 = int64(ret[i-1][0])
			}
			if strings.Compare(reverse[i], str[i-1]) >= 0{
				ret1 = int64(ret[i-1][0]) + int64(a[i])
			}
		}

		if ret[i-1][1] != math.MaxInt64 {
			if strings.Compare(str[i], reverse[i-1]) >= 0 {
				if ret[i-1][1] < ret0 {
					ret0 = ret[i-1][1]
				}
			}
			if strings.Compare(reverse[i], reverse[i-1]) >= 0{
				if ret[i-1][1] + int64(a[i]) < ret1 {
					ret1 = ret[i-1][1] + int64(a[i])
				}
			}
		}
		ret[i][0]=ret0
		ret[i][1]=ret1
	}
	if ret[n-1][0] == math.MaxInt64 && ret[n-1][1] == math.MaxInt64 {
		fmt.Println(-1)
	} else {
		if ret[n-1][0] < ret[n-1][1] {
			fmt.Println(ret[n-1][0])
		} else {
			fmt.Println(ret[n-1][1])
		}
	}
	//fmt.Println(ret)
}

func reverseString(str string) string {
	ret := make([]byte, len(str))
	count := len(str)
	for i := 0; i < len(str); i++ {
		ret[i] = str[count - i - 1]
	}
	return string(ret)
}

package main

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

const (
	MAX_N = 100100
)

var INF int64 = 1 << 50
var N int
var C [MAX_N]int64
var words [MAX_N]string
var rev_words [MAX_N]string

func Reverse(value string) string {
	data := []rune(value)
	result := []rune{}
	for i := len(data) - 1; i >= 0; i-- {
		result = append(result, data[i])
	}
	return string(result)
}

var dp [MAX_N][2]int64

func Compare(s, t string) bool {
	n := len(s)
	m := len(t)
	k := IntMin(n, m)
	for i := 0; i < k; i++ {
		if s[i] == t[i] {
			continue
		}
		return s[i] < t[i]
	}
	if n == m {
		return true
	}
	if n < m {
		return true
	}
	return false
}
func memo(pos, rev int) int64 {

	if pos == N {
		return 0
	}
	if dp[pos][rev] >= 0 {
		return dp[pos][rev]
	}
	var res int64
	res = INF
	// fmt.Println(res)
	if rev == 1 {
		if Compare(rev_words[pos-1], words[pos]) {
			res = Int64Min(res, memo(pos+1, 0))
		}
		if Compare(rev_words[pos-1], rev_words[pos]) {
			res = Int64Min(res, memo(pos+1, 1)+C[pos])
		}
	} else {
		if Compare(words[pos-1], words[pos]) {
			res = Int64Min(res, memo(pos+1, 0))
		}
		if Compare(words[pos-1], rev_words[pos]) {
			res = Int64Min(res, memo(pos+1, 1)+C[pos])
		}
	}
	// fmt.Println(pos, rev, res)
	dp[pos][rev] = res
	return res
}
func init() {
	for i := 0; i < MAX_N; i++ {
		for j := 0; j < len(dp[i]); j++ {
			dp[i][j] = -1
		}
	}
}
func main() {
	fsc := NewFastScanner()
	N = fsc.NextInt()
	for i := 0; i < N; i++ {
		C[i] = fsc.NextInt64()
	}
	for i := 0; i < N; i++ {
		words[i] = fsc.Next()
		rev_words[i] = Reverse(words[i])
	}
	var result int64
	result = INF
	result = Int64Min(result, memo(1, 0))
	result = Int64Min(result, memo(1, 1)+C[0])
	if result >= INF {
		result = -1
	}
	fmt.Println(result)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1024)
	return &FastScanner{r: rdr}
}
func (s *FastScanner) 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 *FastScanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *FastScanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *FastScanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *FastScanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *FastScanner) 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
		}
	}
}

//Max,Min
func IntMax(a, b int) int {
	if a < b {
		return b
	}
	return a
}

func Int64Max(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func Float64Max(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

func Int64Min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func Float64Min(a, b float64) float64 {
	if a > b {
		return b
	}
	return a
}

//Gcd
func IntGcd(a, b int) int {
	if a < b {
		b, a = a, b
	}
	if b == 0 {
		return a
	}
	return IntGcd(b, a%b)
}
func Int64Gcd(a, b int64) int64 {
	if a < b {
		b, a = a, b
	}
	if b == 0 {
		return a
	}
	return Int64Gcd(b, a%b)
}

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

package main

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

const MaxCost = 1e14 + 1

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

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

func Solve(n int, c []int64, s []string) int64 {
	dp := make([][2]int64, n)
	dp[0][0] = 0
	dp[0][1] = int64(c[0])
	for i := 1; i < n; i++ {
		dp[i][0] = MaxCost + 1
		dp[i][1] = MaxCost + 1
		if s[i] >= s[i-1] {
			dp[i][0] = min(dp[i][0], dp[i-1][0])
		}
		if s[i] >= reverse(s[i-1]) {
			dp[i][0] = min(dp[i][0], dp[i-1][1])
		}
		if reverse(s[i]) >= s[i-1] {
			dp[i][1] = min(dp[i][1], c[i]+dp[i-1][0])
		}
		if reverse(s[i]) >= reverse(s[i-1]) {
			dp[i][1] = min(dp[i][1], c[i]+dp[i-1][1])
		}
	}
	if dp[n-1][0] == MaxCost+1 && dp[n-1][1] == MaxCost+1 {
		return -1
	}
	return min(dp[n-1][0], dp[n-1][1])
}

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

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

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

package main

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

func main() {
	var n int
	fmt.Scan(&n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	costs := make([]int64, n+1)
	for i:=0;i<n;i++ {
		costs[i+1] = readInt64(scanner)
	}
	words := make([]string, n+1)
	reverseWords := make([]string, n+1)
	words[0] = ""
	reverseWords[0] = ""
	for i:=1;i<=n;i++ {
		words[i] = readString(scanner)
		reverseWords[i] = reverse(words[i])
	}
	DP := make([][]int64, n+1)
	DP[0] = make([]int64, 2)
	for i:=1;i<=n;i++ {
		DP[i] = make([]int64, 2)
		DP[i][0] = math.MaxInt64
		DP[i][1] = math.MaxInt64
	}
	for i:=1;i<=n;i++ {
		was := false
		if words[i] >= words[i-1] {
			DP[i][0] = DP[i-1][0]
			was = true
		}
		if words[i] >= reverseWords[i-1] {
			DP[i][0] = min(DP[i][0], DP[i-1][1])
			was = true
		}
		if reverseWords[i] >= words[i-1] {
			DP[i][1] = DP[i-1][0] + costs[i]
			was = true
		}
		if reverseWords[i] >= reverseWords[i-1] {
			DP[i][1] = min(DP[i][1], DP[i-1][1] + costs[i])
			was = true
		}
		if !was {
			fmt.Println("-1")
			return
		}
	}
	fmt.Println(min(DP[n][0], DP[n][1]))
}

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

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

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

func readInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	value, _ := strconv.Atoi(scanner.Text())
	return value
}

func readInt64(scanner *bufio.Scanner) int64 {
	scanner.Scan()
	value, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return value
}

// http://codeforces.com/problemset/problem/706/C

package main

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

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

	return b
}

func min3 (a, b, c int64) int64 {
	return min(min(a, b), c)
}

func InvStr(str string) string {
	data := []byte(str)
	n := len(data)
	for i := 0; i <= (n - 1)/ 2; i++ {
		data[i], data[n - i - 1] = data[n - i - 1], data[i]
	}

	return string(data)
}

func main() {
	var n int
	var tmp int64

	input := bufio.NewReaderSize(os.Stdin, 1 << 20)

	fmt.Fscanln(input, &n)
	c := make([]int64, n)
	strs := make([]string, n)
	strinv := make([]string, n)
	dp := make([][]int64, n)

	for i := 0; i < n; i++ {
		if i == n - 1 {
			fmt.Fscanln(input, &tmp)
		} else {
			fmt.Fscan(input, &tmp)
		}
		c[i] = tmp
		dp[i] = make([]int64, 2)
		dp[i][0], dp[i][1] = math.MaxInt64, math.MaxInt64
	}

	for i := 0; i < n; i++ {
		var str string
		fmt.Fscanln(input, &str)

		strs[i] = str
		strinv[i] = InvStr(str)
	}

	// Solve
	if strings.Compare(strs[0], strs[1]) < 0 {
		dp[1][0] = 0
	}
	if strings.Compare(strinv[0], strs[1]) < 0 {
		dp[1][0] = min(c[0], dp[1][0])
	}

	if strings.Compare(strs[0], strinv[1]) < 0 {
		dp[1][1] = c[1]
	}

	if strings.Compare(strinv[0], strinv[1]) < 0 {
		dp[1][1] = min(c[1] + c[0], dp[1][1])
	}

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

		if strings.Compare(strs[i - 1], strs[i]) < 0 && dp[i - 1][0] != math.MaxInt64 {
			dp[i][0] = dp[i - 1][0] + 0
		}
		if strings.Compare(strinv[i - 1], strs[i]) < 0 && dp[i - 1][1] != math.MaxInt64 {
			dp[i][0] = min(dp[i - 1][1] + 0, dp[i][0])
		}

		if strings.Compare(strs[i - 1], strinv[i]) < 0 && dp[i - 1][0] != math.MaxInt64 {
			dp[i][1] = dp[i - 1][0] + c[i]
		}

		if strings.Compare(strinv[i - 1], strinv[i]) < 0 && dp[i - 1][1] != math.MaxInt64 {
			dp[i][1] = min(dp[i - 1][1] + c[i], dp[i][1])
		}

		if dp[i][0] == math.MaxInt64 && dp[i][1] == math.MaxInt64 {
			fmt.Println(-1)
			return
		}
	}

	if ans := min(dp[n - 1][0], dp[n - 1][1]); ans == math.MaxInt64 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

package main

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

const EMPTY = -2

var (
	n  int
	c  []int64
	s  []string
	dp []int64
)

func reverseStr(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 calcEnergy(start int, reverse bool) int64 {
	if start+1 >= len(c) {
		// For the last element the amount of energy needed is just that (or zero if not reversing)
		if reverse {
			return c[start]
		} else {
			return 0
		}
	}
	dpIdx := start
	if reverse {
		dpIdx += n
	}
	if dp[dpIdx] != EMPTY {
		return dp[dpIdx]
	}
	var res1 int64 = -1
	var res2 int64 = -1
	if reverse {
		if strings.Compare(reverseStr(s[start]), s[start+1]) <= 0 {
			res1 = c[start] + calcEnergy(start+1, false)
		}
		if strings.Compare(reverseStr(s[start]), reverseStr(s[start+1])) <= 0 {
			res2 = c[start] + calcEnergy(start+1, true)
		}
	} else {
		if strings.Compare(s[start], s[start+1]) <= 0 {
			res1 = calcEnergy(start+1, false)
		}
		if strings.Compare(s[start], reverseStr(s[start+1])) <= 0 {
			res2 = calcEnergy(start+1, true)
		}
	}
	dp[dpIdx] = minEnergy(res1, res2)
	return dp[dpIdx]
}

func minEnergy(en1 int64, en2 int64) int64 {
	if en2 != -1 && (en1 == -1 || en2 < en1) {
		return en2
	} else {
		return en1
	}
}

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

	fmt.Fscanf(reader, "%d ", &n)
	c = make([]int64, n)
	for i := range c {
		fmt.Fscanf(reader, "%d ", &c[i])
	}
	s = make([]string, n)
	for i := range s {
		fmt.Fscanf(reader, "%s ", &s[i])
	}
	dp = make([]int64, n*2)
	for i := range dp {
		dp[i] = EMPTY
	}

	res1 := calcEnergy(0, false)
	res2 := calcEnergy(0, true)
	fmt.Println(minEnergy(res1, res2))
}

package main

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

/*
	2
	1 2
	ba
	ac
 */

 /**

  */

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanln(reader, &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	fmt.Fscanln(reader)
	str := make([]string, n)
	reverse := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanln(reader, &str[i])
		reverse[i] = reverseString(str[i])
	}

	var ret [][]int
	ret = make([][]int, n)
	for i := 0; i < n; i++ {
		ret[i] = make([]int, 2) // 0 表示没有reverse 1 表示reverse
	}

	ret[0][0] = 0
	ret[0][1] = a[0]
	for i := 1; i < n; i++ {
		var ret0, ret1 = math.MaxInt32, math.MaxInt32
		if ret[i-1][0] != math.MaxInt32 {
			if strings.Compare(str[i], str[i-1]) >= 0 {
				ret0 = ret[i-1][0]
			}
			if strings.Compare(reverse[i], str[i-1]) >= 0{
				ret1 = ret[i-1][0] + a[i]
			}
		}

		if ret[i-1][1] != math.MaxInt32 {
			if strings.Compare(str[i], reverse[i-1]) >= 0 {
				if ret[i-1][1] < ret0 {
					ret0 = ret[i-1][1]
				}
			}
			if strings.Compare(reverse[i], reverse[i-1]) >= 0{
				if ret[i-1][1] + a[i] < ret1 {
					ret1 = ret[i-1][1] + a[i]
				}
			}
		}
		ret[i][0]=ret0
		ret[i][1]=ret1
	}
	if ret[n-1][0] == math.MaxInt32 && ret[n-1][1] == math.MaxInt32 {
		fmt.Println(-1)
	} else {
		if ret[n-1][0] < ret[n-1][1] {
			fmt.Println(ret[n-1][0])
		} else {
			fmt.Println(ret[n-1][1])
		}
	}
	//fmt.Println(ret)
}

func reverseString(str string) string {
	ret := make([]byte, len(str))
	count := len(str)
	for i := 0; i < len(str); i++ {
		ret[i] = str[count - i - 1]
	}
	return string(ret)
}

package main

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

/*
	2
	1 2
	ba
	ac
 */

 /**

  */

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanln(reader, &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	fmt.Fscanln(reader)
	str := make([]string, n)
	reverse := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanln(reader, &str[i])
		reverse[i] = reverseString(str[i])
	}

	var ret [][]int
	ret = make([][]int, n)
	for i := 0; i < n; i++ {
		ret[i] = make([]int, 2) // 0 表示没有reverse 1 表示reverse
	}

	ret[0][0] = 0
	ret[0][1] = a[0]
	for i := 1; i < n; i++ {
		var ret0, ret1 = math.MaxInt32, math.MaxInt32
		if ret[i-1][0] != math.MaxInt32 {
			if strings.Compare(str[i], str[i-1]) > 0 {
				ret0 = ret[i-1][0]
			} else if strings.Compare(reverse[i], str[i-1]) > 0{
				ret1 = ret[i-1][0] + a[i]
			}
		}

		if ret[i-1][1] != math.MaxInt32 {
			if strings.Compare(str[i], reverse[i-1]) > 0 {
				if ret[i-1][1] < ret0 {
					ret0 = ret[i-1][1]
				}
			} else if strings.Compare(reverse[i], reverse[i-1]) > 0{
				if ret[i-1][1] + a[i] < ret1 {
					ret1 = ret[i-1][1] + a[i]
				}
			}
		}
		ret[i][0]=ret0
		ret[i][1]=ret1
	}
	if ret[n-1][0] == math.MaxInt32 && ret[n-1][1] == math.MaxInt32 {
		fmt.Println(-1)
	} else {
		if ret[n-1][0] < ret[n-1][1] {
			fmt.Println(ret[n-1][0])
		} else {
			fmt.Println(ret[n-1][1])
		}
	}
	//fmt.Println(ret)
}

func reverseString(str string) string {
	ret := make([]byte, len(str))
	count := len(str)
	for i := 0; i < len(str); i++ {
		ret[i] = str[count - i - 1]
	}
	return string(ret)
}

package main

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

/*
	2
	1 2
	ba
	ac
 */

 /**

  */

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanln(reader, &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	fmt.Fscanln(reader)
	str := make([]string, n)
	reverse := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanln(reader, &str[i])
		reverse[i] = reverseString(str[i])
	}

	var ret [][]int64
	ret = make([][]int64, n)
	for i := 0; i < n; i++ {
		ret[i] = make([]int64, 2) // 0 表示没有reverse 1 表示reverse
	}

	ret[0][0] = 0
	ret[0][1] = int64(a[0])
	for i := 1; i < n; i++ {
		var ret0, ret1 int64 = math.MaxInt64, math.MaxInt64
		if ret[i-1][0] != math.MaxInt32 {
			if strings.Compare(str[i], str[i-1]) >= 0 {
				ret0 = int64(ret[i-1][0])
			}
			if strings.Compare(reverse[i], str[i-1]) >= 0{
				ret1 = int64(ret[i-1][0]) + int64(a[i])
			}
		}

		if ret[i-1][1] != math.MaxInt32 {
			if strings.Compare(str[i], reverse[i-1]) >= 0 {
				if ret[i-1][1] < ret0 {
					ret0 = ret[i-1][1]
				}
			}
			if strings.Compare(reverse[i], reverse[i-1]) >= 0{
				if ret[i-1][1] + int64(a[i]) < ret1 {
					ret1 = ret[i-1][1] + int64(a[i])
				}
			}
		}
		ret[i][0]=ret0
		ret[i][1]=ret1
	}
	if ret[n-1][0] == math.MaxInt32 && ret[n-1][1] == math.MaxInt32 {
		fmt.Println(-1)
	} else {
		if ret[n-1][0] < ret[n-1][1] {
			fmt.Println(ret[n-1][0])
		} else {
			fmt.Println(ret[n-1][1])
		}
	}
	//fmt.Println(ret)
}

func reverseString(str string) string {
	ret := make([]byte, len(str))
	count := len(str)
	for i := 0; i < len(str); i++ {
		ret[i] = str[count - i - 1]
	}
	return string(ret)
}

package main

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

const (
	MAX_N = 100100
)

var INF int64 = 1 << 50
var N int
var C [MAX_N]int64
var words [MAX_N]string
var rev_words [MAX_N]string

func Reverse(value string) string {
	data := []rune(value)
	result := []rune{}
	for i := len(data) - 1; i >= 0; i-- {
		result = append(result, data[i])
	}
	return string(result)
}

var dp [MAX_N][2]int64

func Compare(s, t string) bool {
	n := len(s)
	m := len(t)
	k := IntMin(n, m)
	for i := 0; i < k; i++ {
		if s[i] == t[i] {
			continue
		}
		return s[i] < t[i]
	}
	if n < m {
		return true
	}
	return false
}
func memo(pos, rev int) int64 {

	if pos == N {
		return 0
	}
	if dp[pos][rev] >= 0 {
		return dp[pos][rev]
	}
	var res int64
	res = INF
	// fmt.Println(res)
	if rev == 1 {
		if Compare(rev_words[pos-1], words[pos]) {
			res = Int64Min(res, memo(pos+1, 0))
		}
		if Compare(rev_words[pos-1], rev_words[pos]) {
			res = Int64Min(res, memo(pos+1, 1)+C[pos])
		}
	} else {
		if Compare(words[pos-1], words[pos]) {
			res = Int64Min(res, memo(pos+1, 0))
		}
		if Compare(words[pos-1], rev_words[pos]) {
			res = Int64Min(res, memo(pos+1, 1)+C[pos])
		}
	}
	// fmt.Println(pos, rev, res)
	dp[pos][rev] = res
	return res
}
func init() {
	for i := 0; i < MAX_N; i++ {
		for j := 0; j < len(dp[i]); j++ {
			dp[i][j] = -1
		}
	}
}
func main() {
	fsc := NewFastScanner()
	N = fsc.NextInt()
	for i := 0; i < N; i++ {
		C[i] = fsc.NextInt64()
	}
	for i := 0; i < N; i++ {
		words[i] = fsc.Next()
		rev_words[i] = Reverse(words[i])
	}
	var result int64
	result = INF
	result = Int64Min(result, memo(1, 0))
	result = Int64Min(result, memo(1, 1)+C[0])
	if result >= INF {
		result = -1
	}
	fmt.Println(result)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1024)
	return &FastScanner{r: rdr}
}
func (s *FastScanner) 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 *FastScanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *FastScanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *FastScanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *FastScanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *FastScanner) 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
		}
	}
}

//Max,Min
func IntMax(a, b int) int {
	if a < b {
		return b
	}
	return a
}

func Int64Max(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func Float64Max(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

func Int64Min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func Float64Min(a, b float64) float64 {
	if a > b {
		return b
	}
	return a
}

//Gcd
func IntGcd(a, b int) int {
	if a < b {
		b, a = a, b
	}
	if b == 0 {
		return a
	}
	return IntGcd(b, a%b)
}
func Int64Gcd(a, b int64) int64 {
	if a < b {
		b, a = a, b
	}
	if b == 0 {
		return a
	}
	return Int64Gcd(b, a%b)
}


Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to mi.Define di as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of di over all days. There are no marks on the channel before the first day.

The first line contains a single positive integer n (1 ≤ n ≤ 105) — the number of days. The second line contains n space-separated integers m1, m2, ..., mn (0 ≤ mi < i) — the number of marks strictly above the water on each day.

Output one single integer — the minimum possible sum of the number of marks strictly below the water level among all days.

NoteIn the first example, the following figure shows an optimal case.  Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0 + 0 + 2 + 0 + 3 + 1 = 6.In the second example, the following figure shows an optimal case.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF924C(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	max := func(a ...int) int {
		res := a[0]
		for _, v := range a[1:] {
			if v > res {
				res = v
			}
		}
		return res
	}

	var n, mx int
	Fscan(in, &n)
	m := make([]int, n)
	for i := range m {
		Fscan(in, &m[i])
	}
	maxs := make([]int, n)
	for i := n - 1; i >= 0; i-- {
		mx = max(mx-1, m[i]+1)
		maxs[i] = mx
	}
	cnt := make([]int, n)
	cnt[0] = 1
	for i := 1; i < n; i++ {
		cnt[i] = max(cnt[i-1], m[i]+1, maxs[i])
	}
	ans := int64(0)
	for i, v := range cnt {
		ans += int64(v - 1 - m[i])
	}
	Fprint(out, ans)
}

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


Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.

The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.

NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.

package main

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

var sc *bufio.Scanner

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

type Flight struct {
	cost, time int
}

type FHeap []Flight

func (h FHeap) Len() int { return len(h) }
func (h FHeap) Less(i, j int) bool {
	return h[i].cost > h[j].cost
}
func (h FHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}
func (h *FHeap) Push(f interface{}) {
	*h = append(*h, f.(Flight))
}

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

func main() {
	sc = bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 0, 1<<20), 1<<20)
	sc.Split(bufio.ScanWords)
	n, k := I(), I()
	m := k
	if m > n {
		m = n
	}
	h, t, res := make(FHeap, m), 0, int64(0)
	for ; t < m; t++ {
		h[t] = Flight{I(), t}
	}
	heap.Init(&h)
	timing := make([]int, n)
	for ; t < n; t++ {
		heap.Push(&h, Flight{I(), t})
		f := heap.Pop(&h).(Flight)
		timing[f.time] = t
		res += int64(t-f.time) * int64(f.cost)
	}
	k += n
	for ; t < k; t++ {
		f := heap.Pop(&h).(Flight)
		timing[f.time] = t
		res += int64(t-f.time) * int64(f.cost)
	}
	fmt.Println(res)
	var buffer bytes.Buffer
	for _, t := range timing {
		buffer.WriteString(strconv.Itoa(t + 1))
		buffer.WriteString(" ")
	}
	fmt.Println(buffer.String())
}

package main

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

func solve() {
	n := readInt()
	k := readInt()
	heap := NewMinHeap(n)
	cost := int64(0)
	a := make([]int, n)
	for i := 0; i < n+k; i++ {
		if i < n {
			heap.Add(i, -readInt())
		}
		if i >= k {
			index := heap.ArgMin()
			value := -heap.Min()
			a[index] = i + 1
			heap.Remove(index)
			cost += int64(i-index) * int64(value)
		}
	}
	fmt.Println(cost)
	var buffer bytes.Buffer
	for i := 0; i < n; i++ {
		if i > 0 {
			buffer.WriteString(" ")
		}
		buffer.WriteString(strconv.Itoa(a[i]))
	}
	fmt.Println(buffer.String())
}

type MinHeap struct {
	a    []int
	vmap []int
	imap []int
	n    int
	pos  int
}

const INF = math.MaxInt32

func NewMinHeap(m int) *MinHeap {
	heap := &MinHeap{}
	m += 2
	heap.n = m
	heap.a = make([]int, heap.n)
	heap.vmap = make([]int, heap.n)
	heap.imap = make([]int, heap.n)
	heap.pos = 1
	for i := 0; i < heap.n; i++ {
		heap.a[i] = INF
		heap.vmap[i] = -1
		heap.imap[i] = -1
	}
	return heap
}

func (h *MinHeap) Add(ind, x int) int {
	ret := h.imap[ind]
	if h.imap[ind] < 0 {
		h.a[h.pos] = x
		h.vmap[h.pos] = ind
		h.imap[ind] = h.pos
		h.pos++
		h.up(h.pos - 1)
	}
	if ret != -1 {
		return h.a[ret]
	}
	return x
}

func (h *MinHeap) Update(ind, x int) int {
	ret := h.imap[ind]
	if h.imap[ind] < 0 {
		h.a[h.pos] = x
		h.vmap[h.pos] = ind
		h.imap[ind] = h.pos
		h.pos++
		h.up(h.pos - 1)
	} else {
		h.a[ret] = x
		h.up(ret)
		h.down(ret)
	}
	return x
}

func (h *MinHeap) Remove(ind int) int {
	if h.pos == 1 {
		return INF
	}
	if h.imap[ind] == -1 {
		return INF
	}

	h.pos--
	rem := h.imap[ind]
	ret := h.a[rem]
	h.vmap[rem] = h.vmap[h.pos]
	h.imap[h.vmap[h.pos]] = rem
	h.imap[ind] = -1
	h.a[rem] = h.a[h.pos]
	h.a[h.pos] = INF
	h.vmap[h.pos] = -1

	h.up(rem)
	h.down(rem)
	return ret
}

func (h *MinHeap) Min() int {
	return h.a[1]
}

func (h *MinHeap) ArgMin() int {
	return h.vmap[1]
}

func (h *MinHeap) Size() int {
	return h.pos - 1
}

func (h *MinHeap) up(cur int) {
	for c, p := cur, cur>>1; p >= 1 && h.a[p] > h.a[c]; c, p = c>>1, p>>1 {
		h.a[p], h.a[c] = h.a[c], h.a[p]
		h.imap[h.vmap[p]], h.imap[h.vmap[c]] = h.imap[h.vmap[c]], h.imap[h.vmap[p]]
		h.vmap[p], h.vmap[c] = h.vmap[c], h.vmap[p]
	}
}

func (h *MinHeap) down(cur int) {
	for c := cur; 2*c < h.pos; {
		b := 0
		if h.a[2*c] < h.a[2*c+1] {
			b = 2 * c
		} else {
			b = 2*c + 1
		}
		if h.a[b] < h.a[c] {
			h.a[c], h.a[b] = h.a[b], h.a[c]
			h.imap[h.vmap[c]], h.imap[h.vmap[b]] = h.imap[h.vmap[b]], h.imap[h.vmap[c]]
			h.vmap[c], h.vmap[b] = h.vmap[b], h.vmap[c]
			c = b
		} else {
			break
		}
	}
}

var scanner *bufio.Scanner

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

// IO

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

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

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

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

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

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
}

package main

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

type flight struct {
	t, c int64
}

var k int64

func solve() {
	n := readInt()
	k = readInt64()
	flights := make([]flight, n)
	ft := make([]int64, n)
	for i := 0; i < n; i++ {
		flights[i] = flight{int64(i + 1), readInt64()}
	}
	sort.Sort(ByCost(flights))
	cost := int64(0)
	for i := 0; i < n; i++ {
		c := (int64(i) + 1 - flights[i].t + k) * flights[i].c
		cost += c
		ft[flights[i].t-1] = (int64(i) + 1 + k)
	}
	fmt.Println(cost)
	var buffer bytes.Buffer
	for i := 0; i < n; i++ {
		if i > 0 {
			buffer.WriteString(" ")
		}
		buffer.WriteString(strconv.FormatInt(ft[i], 10))
	}
	fmt.Println(buffer.String())
}

type ByCost []flight

func (a ByCost) Len() int      { return len(a) }
func (a ByCost) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByCost) Less(i, j int) bool {
	c0 := (int64(i) + 1 - a[i].t + k) * a[i].c
	c1 := (int64(j) + 1 - a[j].t + k) * a[j].c
	return c0 > c1
}

var scanner *bufio.Scanner

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

// IO

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

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

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

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

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

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
}


There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations.Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of numbers l, l + 1, l + 2, ..., r; let's consider all its k-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one.Dima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where F1 = 1, F2 = 1, Fn = Fn - 1 + Fn - 2 for n ≥ 3.Dima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by m.

The first line contains four space-separated integers m, l, r and k (1 ≤ m ≤ 109; 1 ≤ l < r ≤ 1012; 2 ≤ k ≤ r - l + 1). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Print a single integer — the residue from dividing the sought greatest common divisor by m.

package main

import "fmt"

type Matrix struct {
	x [][]uint64
}

func newMatrix(dx int, dy int) Matrix {
	var r Matrix
	r.x = make([][]uint64, dx)
	for i := 0; i < dx; i++ {
		r.x[i] = make([]uint64, dy)
	}
	return r
}

func (r *Matrix) setValue(dx int, dy int, val uint64) {
	r.x[dx][dy] = val
}

func (r Matrix) multi(r1 Matrix, m uint64) Matrix {
	res := newMatrix(2, 2)
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			for k := 0; k < 2; k++ {
				res.x[i][j] = (res.x[i][j] + r.x[i][k]*r1.x[k][j]) % m
			}
		}
	}
	return res
}

func (r Matrix) powerMod(a uint64, b uint64) Matrix {
	matrix := newMatrix(2, 2)
	matrix.setValue(0, 0, 1)
	matrix.setValue(0, 1, 1)
	matrix.setValue(1, 0, 1)
	for a > 0 {
		if a%2 == 1 {
			matrix = matrix.multi(r, b)
		}
		r = r.multi(r, b)
		a /= 2
	}
	return matrix
}

func ok(u uint64, l uint64, r uint64, k uint64) bool {
	if (r/u - (l-1)/u) >= k {
		return true
	}
	return false
}

func main() {
	var m uint64
	var l uint64
	var r uint64
	var k uint64
	fmt.Scanf("%d%d%d%d", &m, &l, &r, &k)
	var found uint64
	for i := uint64(1); i*i <= r; i++ {
		if ok(i, l, r, k) {
			if i > found {
				found = i
			}
		}
		if ok(r/i, l, r, k) {
			if r/i > found {
				found = r / i
			}
		}
	}
	if found <= 2 {
		fmt.Println(1 % m)
		return
	}
	matrix := newMatrix(2, 2)
	matrix.setValue(0, 0, 1)
	matrix.setValue(0, 1, 1)
	matrix.setValue(1, 0, 1)
	matrix = matrix.powerMod(found-2, m)
	fmt.Println(matrix.x[0][0])
}

package main

import "fmt"

type Matrix struct {
	x [][]int64
}

func newMatrix(dx int, dy int) Matrix {
	var r Matrix
	r.x = make([][]int64, dx)
	for i := 0; i < dx; i++ {
		r.x[i] = make([]int64, dy)
	}
	return r
}

func (r *Matrix) setValue(dx int, dy int, val int64) {
	r.x[dx][dy] = val
}

func (r Matrix) multi(r1 Matrix, m int64) Matrix {
	res := newMatrix(2, 2)
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			for k := 0; k < 2; k++ {
				res.x[i][j] = (res.x[i][j] + r.x[i][k]*r1.x[k][j]) % m
			}
		}
	}
	return res
}

func (r Matrix) powerMod(a int64, b int64) Matrix {
	matrix := newMatrix(2, 2)
	matrix.setValue(0, 0, 1)
	matrix.setValue(0, 1, 1)
	matrix.setValue(1, 0, 1)
	for a > 0 {
		if a%2 == 1 {
			matrix = matrix.multi(r, b)
		}
		r = r.multi(r, b)
		a /= 2
	}
	return matrix
}

func main() {
	var m int64
	var l int64
	var r int64
	var k int64
	fmt.Scanf("%d%d%d%d", &m, &l, &r, &k)
	ll := int64(1)
	rr := r
	found := int64(1)
	for ll <= rr {
		mid := int64((ll + rr) / 2)
		val := int64(r/mid - (l-1)/mid)
		if val >= k {
			found = mid
			ll = mid + 1
		} else {
			rr = mid - 1
		}
	}
	if found <= 2 {
		fmt.Println(1)
		return
	}
	matrix := newMatrix(2, 2)
	matrix.setValue(0, 0, 1)
	matrix.setValue(0, 1, 1)
	matrix.setValue(1, 0, 1)
	matrix = matrix.powerMod(found-2, m)
	fmt.Println(matrix.x[0][0])
}

package main

import "fmt"

type Matrix struct {
	x [][]uint64
}

func newMatrix(dx int, dy int) Matrix {
	var r Matrix
	r.x = make([][]uint64, dx)
	for i := 0; i < dx; i++ {
		r.x[i] = make([]uint64, dy)
	}
	return r
}

func (r *Matrix) setValue(dx int, dy int, val uint64) {
	r.x[dx][dy] = val
}

func (r Matrix) multi(r1 Matrix, m uint64) Matrix {
	res := newMatrix(2, 2)
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			for k := 0; k < 2; k++ {
				res.x[i][j] = (res.x[i][j] + r.x[i][k]*r1.x[k][j]) % m
			}
		}
	}
	return res
}

func (r Matrix) powerMod(a uint64, b uint64) Matrix {
	matrix := newMatrix(2, 2)
	matrix.setValue(0, 0, 1)
	matrix.setValue(0, 1, 1)
	matrix.setValue(1, 0, 1)
	for a > 0 {
		if a%2 == 1 {
			matrix = matrix.multi(r, b)
		}
		r = r.multi(r, b)
		a /= 2
	}
	return matrix
}

func ok(u uint64, l uint64, r uint64, k uint64) bool {
	if (r/u - (l-1)/u) >= k {
		return true
	}
	return false
}

func main() {
	var m uint64
	var l uint64
	var r uint64
	var k uint64
	fmt.Scanf("%d%d%d%d", &m, &l, &r, &k)
	var found uint64
	for i := uint64(1); i*i <= r; i++ {
		if ok(i, l, r, k) {
			if i > found {
				found = i
			}
		}
		if ok(r/i, l, r, k) {
			if r/i > found {
				found = r / i
			}
		}
	}
	if found <= 2 {
		fmt.Println(1)
		return
	}
	matrix := newMatrix(2, 2)
	matrix.setValue(0, 0, 1)
	matrix.setValue(0, 1, 1)
	matrix.setValue(1, 0, 1)
	matrix = matrix.powerMod(found-2, m)
	fmt.Println(matrix.x[0][0])
}

package main

import "fmt"

type Matrix struct {
	x [][]int64
}

func newMatrix(dx int, dy int) Matrix {
	var r Matrix
	r.x = make([][]int64, dx)
	for i := 0; i < dx; i++ {
		r.x[i] = make([]int64, dy)
	}
	return r
}

func (r *Matrix) setValue(dx int, dy int, val int64) {
	r.x[dx][dy] = val
}

func (r Matrix) multi(r1 Matrix, m int64) Matrix {
	res := newMatrix(2, 2)
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			for k := 0; k < 2; k++ {
				res.x[i][j] = (res.x[i][j] + r.x[i][k]*r1.x[k][j]) % m
			}
		}
	}
	return res
}

func (r Matrix) powerMod(a int64, b int64) Matrix {
	matrix := newMatrix(2, 2)
	matrix.setValue(0, 0, 1)
	matrix.setValue(0, 1, 1)
	matrix.setValue(1, 0, 1)
	for a > 0 {
		if a%2 == 1 {
			matrix = matrix.multi(r, b)
		}
		r = r.multi(r, b)
		a /= 2
	}
	return matrix
}

func main() {
	var m int64
	var l int64
	var r int64
	var k int64
	fmt.Scanf("%d%d%d%d", &m, &l, &r, &k)
	ll := int64(1)
	rr := r
	found := int64(1)
	for ll <= rr {
		mid := int64((ll + rr) / 2)
		val := int64(r/mid - (l-1)/mid)
		if val >= k {
			found = mid
			ll = mid + 1
		} else {
			rr = mid - 1
		}
	}
	if found <= 2 {
		fmt.Println(1)
		return
	}
	matrix := newMatrix(2, 2)
	matrix.setValue(0, 0, 1)
	matrix.setValue(0, 1, 1)
	matrix.setValue(1, 0, 1)
	matrix = matrix.powerMod(found-2, 100000)
	fmt.Println(matrix.x[0][0])
}