You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).For example, for string "010210" we can perform the following moves:   "010210" $$$\rightarrow$$$ "100210";  "010210" $$$\rightarrow$$$ "001210";  "010210" $$$\rightarrow$$$ "010120";  "010210" $$$\rightarrow$$$ "010201". Note than you cannot swap "02" $$$\rightarrow$$$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).String $$$a$$$ is lexicographically less than string $$$b$$$ (if strings $$$a$$$ and $$$b$$$ have the same length) if there exists some position $$$i$$$ ($$$1 \le i \le |a|$$$, where $$$|s|$$$ is the length of the string $$$s$$$) such that for every $$$j < i$$$ holds $$$a_j = b_j$$$, and $$$a_i < b_i$$$.

The first line of the input contains the string $$$s$$$ consisting only of characters '0', '1' and '2', its length is between $$$1$$$ and $$$10^5$$$ (inclusive).

Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).

package main

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

func main() {
	sc := NewScanner()
  var input []byte
	inputs := sc.NextLine()
  for i:=0;i<len(inputs);i++ {
    input = append(input, inputs[i])
  }
  var counter int

  for i:=0;i<len(input);i++ {
		if input[i] == 49 {
			counter++
		}
  }

  var result string
	var flag bool = true
  for i:=0;i<len(input);i++ {
    if input[i] == 48 {
      result = result + "0"
    }
		if input[i] == 50 {
			if flag {
				for counter>0 {
					result = result + "1"
					counter--
				}
				flag = false
			}
			result = result + "2"
		}
  }
	if flag {
		for counter>0 {
			result = result + "1"
			counter--
		}
		flag = false
	}

	fmt.Println(result)

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

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

package main

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

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

func scanf(f string, a ...interface{}) {
	fmt.Fscanf(reader, f, a...)
}
func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}
func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}
func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}
func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func main() {
	defer writer.Flush()
	var s, t, one []byte
	scan(&s)
	cnt1 := 0
	for _, i := range s {
		if i == byte('1') {
			cnt1++
			one = append(one, i)
		} else {
			t = append(t, i)
		}
	}

	i := 0
	for i < len(t) && t[i] == byte('0') {
		i++
	}
	println(string(t[:i]) + string(one) + string(t[i:]))
}

package main

import "fmt"

func main() {
	var s, t, one []byte
	fmt.Scan(&s)
	cnt1 := 0
	for _, i := range s {
		if i == byte('1') {
			cnt1++
			one = append(one, i)
		} else {
			t = append(t, i)
		}
	}

	i := 0
	for i < len(t) && t[i] == byte('0') {
		i++
	}
	fmt.Println(string(t[:i]) + string(one) + string(t[i:]))

}

package main

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

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

func scanf(f string, a ...interface{}) {
	fmt.Fscanf(reader, f, a...)
}
func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}
func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}
func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}
func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func main() {
	defer writer.Flush()
	var s, t, one []byte
	scan(&s)
	cnt1 := 0
	for _, i := range s {
		if i == byte('1') {
			cnt1++
			one = append(one, i)
		} else {
			t = append(t, i)
		}
	}

	i := 0
	for i < len(t) && t[i] == byte('0') {
		i++
	}
	fmt.Println(string(t[:i]) + string(one) + string(t[i:]))
}

package main

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

func main() {
	sc := NewScanner()
  var input []byte
	inputs := sc.NextLine()
  for i:=0;i<len(inputs);i++ {
    input = append(input, inputs[i])
  }
  var counter int

  for i:=0;i<len(input);i++ {
		if input[i] == 49 {
			counter++
		}
  }

  var result string
	var flag bool = true
  for i:=0;i<len(input);i++ {
    if input[i] == 48 {
      result = result + "0"
    }
		if input[i] == 50 && flag{
			if flag {
				for counter>0 {
					result = result + "1"
					counter--
				}
				flag = false
			}
			result = result + "2"
		}
  }
	if flag {
		for counter>0 {
			result = result + "1"
			counter--
		}
		flag = false
	}

	fmt.Println(result)

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

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

package main

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

func main() {
	sc := NewScanner()
  var input []byte
	inputs := sc.NextLine()
  for i:=0;i<len(inputs);i++ {
    input = append(input, inputs[i])
  }
  var counter int

  for i:=0;i<len(input);i++ {
		if input[i] == 49 {
			counter++
		}
  }

  var result string
	var flag bool = true
  for i:=0;i<len(input);i++ {
    if input[i] == 48 {
      result = result + "0"
    }
		if input[i] == 50{
			if flag {
				for counter>0 {
					result = result + "1"
					counter--
				}
				flag = false
			}
			result = result + "2"
		}
  }

	fmt.Println(result)

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

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

package main

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

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

func scanf(f string, a ...interface{}) {
	fmt.Fscanf(reader, f, a...)
}
func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}
func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}
func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}
func main() {

	var s, t, one []byte
	scan(&s)
	cnt1 := 0
	for _, i := range s {
		if i == byte('1') {
			cnt1++
			one = append(one, i)
		} else {
			t = append(t, i)
		}
	}

	i := 0
	for i < len(t) && t[i] == byte('0') {
		i++
	}
	println(string(t[:i]) + string(one) + string(t[i:]))
}

package main

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

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

func scanf(f string, a ...interface{}) {
	fmt.Fscanf(reader, f, a...)
}
func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}
func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}
func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}
func main() {

	var s, t, one []byte
	scan(&s)
	cnt1 := 0
	for _, i := range s {
		if i == byte('1') {
			cnt1++
			one = append(one, i)
		} else {
			t = append(t, i)
		}
	}

	i := 0
	for i < len(t) && t[i] == byte('0') {
		i++
	}
	print(string(t[:i]) + string(one) + string(t[i:]))
}


You are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make  as large as possible, where  denotes the bitwise OR. Find the maximum possible value of  after performing at most k operations optimally.

The first line contains three integers n, k and x (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 10, 2 ≤ x ≤ 8). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).

Output the maximum value of a bitwise OR of sequence elements after performing operations.

NoteFor the first sample, any possible choice of doing one operation will result the same three numbers 1, 1, 2 so the result is . For the second sample if we multiply 8 by 3 two times we'll get 72. In this case the numbers will become 1, 2, 4, 72 so the OR value will be 79 and is the largest possible result.

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	var n, k, x int
	Fscan(in, &n, &k, &x)
	mul := int64(1)
	for ; k > 0; k -- {
		mul *= int64(x)
	}
	arr := make([]int64, n)
	pOR, sOR := make([]int64, n+1), make([]int64, n+1)
	for i := 0; i < n; i++ {
		Fscan(in, &arr[i])
		pOR[i+1] = pOR[i] | arr[i]
	}
	for i := n; i > 0; i-- {
		sOR[i-1] = sOR[i] | arr[i-1]
	}
	maxOR := int64(0)
	for i := range arr {
		if or := arr[i]*mul | pOR[i] | sOR[i+1]; or > maxOR {
			maxOR = or
		}
	}
	Print(maxOR)
}


Theseus has just arrived to Crete to fight Minotaur. He found a labyrinth that has a form of a rectangular field of size n × m and consists of blocks of size 1 × 1.Each block of the labyrinth has a button that rotates all blocks 90 degrees clockwise. Each block rotates around its center and doesn't change its position in the labyrinth. Also, each block has some number of doors (possibly none). In one minute, Theseus can either push the button in order to rotate all the blocks 90 degrees clockwise or pass to the neighbouring block. Theseus can go from block A to some neighbouring block B only if block A has a door that leads to block B and block B has a door that leads to block A.Theseus found an entrance to labyrinth and is now located in block (xT, yT) — the block in the row xT and column yT. Theseus know that the Minotaur is hiding in block (xM, yM) and wants to know the minimum number of minutes required to get there.Theseus is a hero, not a programmer, so he asks you to help him.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in labyrinth, respectively. Each of the following n lines contains m characters, describing the blocks of the labyrinth. The possible characters are:   «+» means this block has 4 doors (one door to each neighbouring block);  «-» means this block has 2 doors — to the left and to the right neighbours;  «|» means this block has 2 doors — to the top and to the bottom neighbours;  «^» means this block has 1 door — to the top neighbour;  «>» means this block has 1 door — to the right neighbour;  «<» means this block has 1 door — to the left neighbour;  «v» means this block has 1 door — to the bottom neighbour; «L» means this block has 3 doors — to all neighbours except left one;  «R» means this block has 3 doors — to all neighbours except right one;  «U» means this block has 3 doors — to all neighbours except top one;  «D» means this block has 3 doors — to all neighbours except bottom one; «*» means this block is a wall and has no doors.  Left, right, top and bottom are defined from representing labyrinth as a table, where rows are numbered from 1 to n from top to bottom and columns are numbered from 1 to m from left to right. Next line contains two integers — coordinates of the block (xT, yT) (1 ≤ xT ≤ n, 1 ≤ yT ≤ m), where Theseus is initially located. Last line contains two integers — coordinates of the block (xM, yM) (1 ≤ xM ≤ n, 1 ≤ yM ≤ m), where Minotaur hides. It's guaranteed that both the block where Theseus starts and the block where Minotaur is hiding have at least one door. Theseus and Minotaur may be initially located at the same block.

If Theseus is not able to get to Minotaur, then print -1 in the only line of the output. Otherwise, print the minimum number of minutes required to get to the block where Minotaur is hiding.

NoteAssume that Theseus starts at the block (xT, yT) at the moment 0.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF676D(_r io.Reader, _w io.Writer) {
	doorTable := [...]string{
		'+': "++++",
		'-': "-|-|",
		'|': "|-|-",
		'^': "^>v<",
		'>': ">v<^",
		'v': "v<^>",
		'<': "<^>v",
		'U': "URDL",
		'R': "RDLU",
		'D': "DLUR",
		'L': "LURD",
	}
	dir4 := [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} // 上右下左
	dirTable := [...][]int{
		'+': {0, 1, 2, 3},
		'-': {1, 3},
		'|': {0, 2},
		'^': {0},
		'>': {1},
		'v': {2},
		'<': {3},
		'U': {1, 2, 3},
		'R': {0, 2, 3},
		'D': {0, 1, 3},
		'L': {0, 1, 2},
	}
	canBack := func(from int, backs []int) bool {
		for _, back := range backs {
			if (back+2)&3 == from {
				return true
			}
		}
		return false
	}

	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var n, m, ax, ay, bx, by int
	Fscan(in, &n, &m)
	g := make([][]byte, n)
	for i := range g {
		Fscan(in, &g[i])
	}
	Fscan(in, &ax, &ay, &bx, &by)
	bx--
	by--

	type stat struct{ x, y, rot int }
	qs := [4][]stat{{{ax - 1, ay - 1, 0}}}
	allEmpty := func() bool {
		for _, q := range qs {
			if len(q) > 0 {
				return false
			}
		}
		return true
	}
	vis := [1000][1000][4]bool{}
	for time := 0; !allEmpty(); time++ {
		q := qs[time&3]
		qs[time&3] = []stat{}
		for _, s := range q {
			if s.x == bx && s.y == by {
				Fprint(out, time)
				return
			}
			if vis[s.x][s.y][s.rot] {
				continue
			}
			vis[s.x][s.y][s.rot] = true
			for rotTimes := 0; rotTimes < 4; rotTimes++ {
				rot := (s.rot + rotTimes) & 3
				door := doorTable[g[s.x][s.y]][rot]
				for _, i := range dirTable[door] {
					d := dir4[i]
					x, y := s.x+d[0], s.y+d[1]
					if x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '*' || vis[x][y][rot] {
						continue
					}
					door1 := doorTable[g[x][y]][rot]
					if !canBack(i, dirTable[door1]) {
						continue
					}
					tarTime := time + rotTimes + 1
					qs[tarTime&3] = append(qs[tarTime&3], stat{x, y, rot})
				}
			}
		}
	}
	Fprint(out, -1)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF676D(_r io.Reader, _w io.Writer) {
	doorTable := [125]string{}
	doorTable['+'] = "++++"
	doorTable['-'] = "-|-|"
	doorTable['|'] = "|-|-"
	doorTable['^'] = "^>v<"
	doorTable['>'] = ">v<^"
	doorTable['v'] = "v<^>"
	doorTable['<'] = "<^>v"
	doorTable['U'] = "URDL"
	doorTable['R'] = "RDLU"
	doorTable['D'] = "DLUR"
	doorTable['L'] = "LURD"
	dir4 := [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} // 上右下左
	dirTable := [125][]int{}
	dirTable['+'] = []int{0, 1, 2, 3}
	dirTable['-'] = []int{1, 3}
	dirTable['|'] = []int{0, 2}
	dirTable['^'] = []int{0}
	dirTable['>'] = []int{1}
	dirTable['v'] = []int{2}
	dirTable['<'] = []int{3}
	dirTable['U'] = []int{1, 2, 3}
	dirTable['R'] = []int{0, 2, 3}
	dirTable['D'] = []int{0, 1, 3}
	dirTable['L'] = []int{0, 1, 2}
	canBack := func(from int, backs []int) bool {
		for _, back := range backs {
			if (back+2)&3 == from {
				return true
			}
		}
		return false
	}

	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var n, m, ax, ay, bx, by int
	Fscan(in, &n, &m)
	g := make([]string, n)
	for i := range g {
		Fscan(in, &g[i])
	}
	Fscan(in, &ax, &ay, &bx, &by)
	bx--
	by--

	type stat struct{ x, y, rot int }
	qs := [4][]stat{{{ax - 1, ay - 1, 0}}}
	vis := [1000][1000][4]bool{}
	isAllQueueEmpty := func() bool {
		for _, q := range qs {
			if len(q) > 0 {
				return false
			}
		}
		return true
	}
	for time := 0; !isAllQueueEmpty(); time++ {
		curQ := make([]stat, len(qs[time&3]))
		copy(curQ, qs[time&3])
		qs[time&3] = []stat{}
		for _, s := range curQ {
			if s.x == bx && s.y == by {
				Fprint(out, time)
				return
			}
			if vis[s.x][s.y][s.rot] {
				continue
			}
			vis[s.x][s.y][s.rot] = true
			for rotTimes := 0; rotTimes < 4; rotTimes++ {
				rot := (s.rot + rotTimes) & 3
				door := doorTable[g[s.x][s.y]][rot]
				for _, i := range dirTable[door] {
					dir := dir4[i]
					x, y := s.x+dir[0], s.y+dir[1]
					if x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '*' || vis[x][y][rot] {
						continue
					}
					door1 := doorTable[g[x][y]][rot]
					if !canBack(i, dirTable[door1]) {
						continue
					}
					tarTime := time + rotTimes + 1
					qs[tarTime&3] = append(qs[tarTime&3], stat{x, y, rot})
				}
			}
		}
	}
	Fprint(out, -1)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF676D(_r io.Reader, _w io.Writer) {
	doorTable := [125]string{}
	doorTable['+'] = "++++"
	doorTable['-'] = "-|-|"
	doorTable['|'] = "|-|-"
	doorTable['^'] = "^>v<"
	doorTable['>'] = ">v<^"
	doorTable['v'] = "v<^>"
	doorTable['<'] = "<^>v"
	doorTable['U'] = "URDL"
	doorTable['R'] = "RDLU"
	doorTable['D'] = "DLUR"
	doorTable['L'] = "LURD"
	dir4 := [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} // 上右下左
	dirTable := [125][]int{}
	dirTable['+'] = []int{0, 1, 2, 3}
	dirTable['-'] = []int{1, 3}
	dirTable['|'] = []int{0, 2}
	dirTable['^'] = []int{0}
	dirTable['>'] = []int{1}
	dirTable['v'] = []int{2}
	dirTable['<'] = []int{3}
	dirTable['U'] = []int{1, 2, 3}
	dirTable['R'] = []int{0, 2, 3}
	dirTable['D'] = []int{0, 1, 3}
	dirTable['L'] = []int{0, 1, 2}
	canBack := func(from int, backs []int) bool {
		for _, back := range backs {
			if (back+2)&3 == from {
				return true
			}
		}
		return false
	}

	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var n, m, ax, ay, bx, by int
	Fscan(in, &n, &m)
	g := make([]string, n)
	for i := range g {
		Fscan(in, &g[i])
	}
	Fscan(in, &ax, &ay, &bx, &by)
	bx--
	by--

	type stat struct{ x, y, rot int }
	qs := [4][]stat{{{ax - 1, ay - 1, 0}}}
	vis := [1000][1000][4]bool{}
	isAllQueueEmpty := func() bool {
		for _, q := range qs {
			if len(q) > 0 {
				return false
			}
		}
		return true
	}
	for time := 0; !isAllQueueEmpty(); time++ {
		curQ := make([]stat, len(qs[time&3]))
		copy(curQ, qs[time&3])
		qs[time&3] = []stat{}
		for _, s := range curQ {
			if s.x == bx && s.y == by {
				Fprint(out, time)
				return
			}
			if vis[s.x][s.y][s.rot] {
				continue
			}
			vis[s.x][s.y][s.rot] = true
			for rotTimes := 0; rotTimes < 4; rotTimes++ {
				rot := (s.rot + rotTimes) & 3
				door := doorTable[g[s.x][s.y]][rot]
				for _, i := range dirTable[door] {
					dir := dir4[i]
					x, y := s.x+dir[0], s.y+dir[1]
					if x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '*' {
						continue
					}
					door1 := doorTable[g[x][y]][rot]
					if !canBack(i, dirTable[door1]) {
						continue
					}
					tarTime := time + rotTimes + 1
					qs[tarTime&3] = append(qs[tarTime&3], stat{x, y, rot})
				}
			}
		}
	}
	Fprint(out, -1)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF676D(_r io.Reader, _w io.Writer) {
	doorTable := [125]string{}
	doorTable['+'] = "++++"
	doorTable['-'] = "-|-|"
	doorTable['|'] = "|-|-"
	doorTable['^'] = "^>v<"
	doorTable['>'] = ">v<^"
	doorTable['v'] = "v<^>"
	doorTable['<'] = "<^>v"
	doorTable['U'] = "URDL"
	doorTable['R'] = "RDLU"
	doorTable['D'] = "DLUR"
	doorTable['L'] = "LURD"
	dir4 := [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} // 上右下左
	dirTable := [125][]int{}
	dirTable['+'] = []int{0, 1, 2, 3}
	dirTable['-'] = []int{1, 3}
	dirTable['|'] = []int{0, 2}
	dirTable['^'] = []int{0}
	dirTable['>'] = []int{1}
	dirTable['v'] = []int{2}
	dirTable['<'] = []int{3}
	dirTable['U'] = []int{1, 2, 3}
	dirTable['R'] = []int{0, 2, 3}
	dirTable['D'] = []int{0, 1, 3}
	dirTable['L'] = []int{0, 1, 2}
	canBack := func(from int, backs []int) bool {
		for _, back := range backs {
			if (back+2)&3 == from {
				return true
			}
		}
		return false
	}

	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var n, m, ax, ay, bx, by int
	Fscan(in, &n, &m)
	g := make([]string, n)
	for i := range g {
		Fscan(in, &g[i])
	}
	Fscan(in, &ax, &ay, &bx, &by)
	bx--
	by--

	type stat struct{ x, y, rot int }
	qs := [4][]stat{{{ax - 1, ay - 1, 0}}}
	vis := [1000][1000][4]bool{}
	isAllQueueEmpty := func() bool {
		for _, q := range qs {
			if len(q) > 0 {
				return false
			}
		}
		return true
	}
	for time := 0; !isAllQueueEmpty(); time++ {
		q := qs[time&3]
		sz := len(q)
		for _, s := range q[:sz] {
			if s.x == bx && s.y == by {
				Fprint(out, time)
				return
			}
			if vis[s.x][s.y][s.rot] {
				continue
			}
			vis[s.x][s.y][s.rot] = true
			for rotTimes := 0; rotTimes < 4; rotTimes++ {
				rot := (s.rot + rotTimes) & 3
				door := doorTable[g[s.x][s.y]][rot]
				for _, i := range dirTable[door] {
					dir := dir4[i]
					x, y := s.x+dir[0], s.y+dir[1]
					if x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '*' || vis[x][y][rot] {
						continue
					}
					door1 := doorTable[g[x][y]][rot]
					if !canBack(i, dirTable[door1]) {
						continue
					}
					tarTime := time + rotTimes + 1
					qs[tarTime&3] = append(qs[tarTime&3], stat{x, y, rot})
				}
			}
		}
		qs[time&3] = qs[time&3][sz:]
	}
	Fprint(out, -1)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF676D(_r io.Reader, _w io.Writer) {
	doorTable := [125]string{}
	doorTable['+'] = "++++"
	doorTable['-'] = "-|-|"
	doorTable['|'] = "|-|-"
	doorTable['^'] = "^>v<"
	doorTable['>'] = ">v<^"
	doorTable['v'] = "v<^>"
	doorTable['<'] = "<^>v"
	doorTable['U'] = "URDL"
	doorTable['R'] = "RDLU"
	doorTable['D'] = "DLUR"
	doorTable['L'] = "LURD"
	dir4 := [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} // 上右下左
	dirTable := [125][]int{}
	dirTable['+'] = []int{0, 1, 2, 3}
	dirTable['-'] = []int{1, 3}
	dirTable['|'] = []int{0, 2}
	dirTable['^'] = []int{0}
	dirTable['>'] = []int{1}
	dirTable['v'] = []int{2}
	dirTable['<'] = []int{3}
	dirTable['U'] = []int{1, 2, 3}
	dirTable['R'] = []int{0, 2, 3}
	dirTable['D'] = []int{0, 1, 3}
	dirTable['L'] = []int{0, 1, 2}
	canBack := func(from int, backs []int) bool {
		for _, back := range backs {
			if (back+2)&3 == from {
				return true
			}
		}
		return false
	}

	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var n, m, ax, ay, bx, by int
	Fscan(in, &n, &m)
	g := make([]string, n)
	for i := range g {
		Fscan(in, &g[i])
	}
	Fscan(in, &ax, &ay, &bx, &by)
	bx--
	by--

	type stat struct{ x, y, rot int }
	qs := [4][]stat{{{ax - 1, ay - 1, 0}}}
	vis := [1000][1000]bool{}
	isAllQueueEmpty := func() bool {
		for _, q := range qs {
			if len(q) > 0 {
				return false
			}
		}
		return true
	}
	for time := 0; !isAllQueueEmpty(); time++ {
		curQ := make([]stat, len(qs[time&3]))
		copy(curQ, qs[time&3])
		qs[time&3] = []stat{}
		for _, s := range curQ {
			if s.x == bx && s.y == by {
				Fprint(out, time)
				return
			}
			if vis[s.x][s.y] {
				continue
			}
			vis[s.x][s.y] = true
			for rotTimes := 0; rotTimes < 4; rotTimes++ {
				rot := (s.rot + rotTimes) & 3
				door := doorTable[g[s.x][s.y]][rot]
				for _, i := range dirTable[door] {
					dir := dir4[i]
					x, y := s.x+dir[0], s.y+dir[1]
					if x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '*' || vis[x][y] {
						continue
					}
					door1 := doorTable[g[x][y]][rot]
					if !canBack(i, dirTable[door1]) {
						continue
					}
					tarTime := time + rotTimes + 1
					qs[tarTime&3] = append(qs[tarTime&3], stat{x, y, rot})
				}
			}
		}
	}
	Fprint(out, -1)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF676D(_r io.Reader, _w io.Writer) {
	doorTable := [125]string{}
	doorTable['+'] = "++++"
	doorTable['-'] = "-|-|"
	doorTable['|'] = "|-|-"
	doorTable['^'] = "^>v<"
	doorTable['>'] = ">v<^"
	doorTable['v'] = "v<^>"
	doorTable['<'] = "<^>v"
	doorTable['U'] = "URDL"
	doorTable['R'] = "RDLU"
	doorTable['D'] = "DLUR"
	doorTable['L'] = "LURD"
	dir4 := [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} // 上右下左
	dirTable := [125][]int{}
	dirTable['+'] = []int{0, 1, 2, 3}
	dirTable['-'] = []int{1, 3}
	dirTable['|'] = []int{0, 2}
	dirTable['^'] = []int{0}
	dirTable['>'] = []int{1}
	dirTable['v'] = []int{2}
	dirTable['<'] = []int{3}
	dirTable['U'] = []int{1, 2, 3}
	dirTable['R'] = []int{0, 2, 3}
	dirTable['D'] = []int{0, 1, 3}
	dirTable['L'] = []int{0, 1, 2}
	canBack := func(from int, backs []int) bool {
		for _, back := range backs {
			if (back+2)&3 == from {
				return true
			}
		}
		return false
	}

	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var n, m, ax, ay, bx, by int
	Fscan(in, &n, &m)
	g := make([]string, n)
	for i := range g {
		Fscan(in, &g[i])
	}
	Fscan(in, &ax, &ay, &bx, &by)
	bx--
	by--

	type stat struct{ x, y, rot int }
	qs := [4][]stat{{{ax - 1, ay - 1, 0}}}
	vis := [1000][1000]bool{}
	isAllQueueEmpty := func() bool {
		for _, q := range qs {
			if len(q) > 0 {
				return false
			}
		}
		return true
	}
	for time := 0; !isAllQueueEmpty(); time++ {
		curQ := make([]stat, len(qs[time&3]))
		copy(curQ, qs[time&3])
		qs[time&3] = []stat{}
		for _, s := range curQ {
			if s.x == bx && s.y == by {
				Fprint(out, time)
				return
			}
			if vis[s.x][s.y] {
				continue
			}
			vis[s.x][s.y] = true
			for rotTimes := 0; rotTimes < 4; rotTimes++ {
				rot := (s.rot + rotTimes) & 3
				door := doorTable[g[s.x][s.y]][rot]
				for _, i := range dirTable[door] {
					dir := dir4[i]
					x, y := s.x+dir[0], s.y+dir[1]
					if x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '*' {
						continue
					}
					door1 := doorTable[g[x][y]][rot]
					if !canBack(i, dirTable[door1]) {
						continue
					}
					tarTime := time + rotTimes + 1
					qs[tarTime&3] = append(qs[tarTime&3], stat{x, y, rot})
				}
			}
		}
	}
	Fprint(out, -1)
}

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


You are given a sequence of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$.You have to construct two sequences of integers $$$b$$$ and $$$c$$$ with length $$$n$$$ that satisfy:  for every $$$i$$$ ($$$1\leq i\leq n$$$) $$$b_i+c_i=a_i$$$  $$$b$$$ is non-decreasing, which means that for every $$$1<i\leq n$$$, $$$b_i\geq b_{i-1}$$$ must hold  $$$c$$$ is non-increasing, which means that for every $$$1<i\leq n$$$, $$$c_i\leq c_{i-1}$$$ must hold You have to minimize $$$\max(b_i,c_i)$$$. In other words, you have to minimize the maximum number in sequences $$$b$$$ and $$$c$$$.Also there will be $$$q$$$ changes, the $$$i$$$-th change is described by three integers $$$l,r,x$$$. You should add $$$x$$$ to $$$a_l,a_{l+1}, \ldots, a_r$$$. You have to find the minimum possible value of $$$\max(b_i,c_i)$$$ for the initial sequence and for sequence after each change.

The first line contains an integer $$$n$$$ ($$$1\leq n\leq 10^5$$$). The secound line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\leq i\leq n$$$, $$$-10^9\leq a_i\leq 10^9$$$). The third line contains an integer $$$q$$$ ($$$1\leq q\leq 10^5$$$). Each of the next $$$q$$$ lines contains three integers $$$l,r,x$$$ ($$$1\leq l\leq r\leq n,-10^9\leq x\leq 10^9$$$), desribing the next change.

Print $$$q+1$$$ lines. On the $$$i$$$-th ($$$1 \leq i \leq q+1$$$) line, print the answer to the problem for the sequence after $$$i-1$$$ changes.

NoteIn the first test:  The initial sequence $$$a = (2, -1, 7, 3)$$$. Two sequences $$$b=(-3,-3,5,5),c=(5,2,2,-2)$$$ is a possible choice.  After the first change $$$a = (2, -4, 4, 0)$$$. Two sequences $$$b=(-3,-3,5,5),c=(5,-1,-1,-5)$$$ is a possible choice.  After the second change $$$a = (2, -4, 6, 2)$$$. Two sequences $$$b=(-4,-4,6,6),c=(6,0,0,-4)$$$ is a possible choice.

package main

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

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

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

	s := int64(a[0])
	d := make([]int64, n)
	for i := 1; i < n; i++ {
		d[i] = int64(a[i] - a[i-1])
		s += max(0, d[i])
	}

	ans := func() int64 {
		if s < 0 {
			return s / 2
		}
		return (s + 1) / 2
	}
	fmt.Fprintln(out, ans())

	var q int
	fmt.Fscan(in, &q)
	for ; q > 0; q-- {
		var l, r, x int
		fmt.Fscan(in, &l, &r, &x)
		if l == 1 {
			s += int64(x)
		} else {
			s -= max(0, d[l-1])
			d[l-1] += int64(x)
			s += max(0, d[l-1])
		}
		if r < n {
			s -= max(0, d[r])
			d[r] -= int64(x)
			s += max(0, d[r])
		}
		fmt.Fprintln(out, ans())
	}
}

func max(i, j int64) int64 {
	if i > j {
		return i
	}
	return j
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n := io.NextInt()
	a := io.NextInts(n)

	asc, dsc := make([]int64, n+1), make([]int64, n+1)
	for i := 1; i <= n; i++ {
		dif := int64(a[i-1]) - (asc[i-1] + dsc[i-1])
		asc[i], dsc[i] = asc[i-1], dsc[i-1]
		if dif >= 0 {
			asc[i] += dif
		} else {
			dsc[i] += dif
		}
	}
	ast, dst := NewLazySegTree(n), NewLazySegTree(n)
	for i := 0; i < n; i++ {
		ast.Update(i, i+1, asc[i+1])
		dst.Update(i, i+1, dsc[i+1])
	}

	getAns := func() int64 {
		sum := ast.Query(0, n) + dst.Query(0, n)
		if sum < 0 {
			return sum / 2
		}
		return (sum + 1) / 2
	}

	fix := func(i int) {
		if i > n {
			return
		}
		adif, ddif := ast.Query(i, i+1), dst.Query(i, i+1)
		if i > 0 {
			adif -= ast.Query(i-1, i)
			ddif -= dst.Query(i-1, i)
		}
		dif := max(-adif, ddif)
		ast.Update(i, n, dif)
		dst.Update(i, n, -dif)
	}

	io.Println(getAns())
	for q := io.NextInt(); q > 0; q-- {
		l, r, x := io.NextInt()-1, io.NextInt(), int64(io.NextInt())
		if x >= 0 {
			ast.Update(l, n, x)
			dst.Update(r, n, -x)
		} else {
			dst.Update(l, n, x)
			ast.Update(r, n, -x)
		}
		fix(l)
		fix(r)
		io.Println(getAns())
	}
}

type LazySegTree struct {
	n    int
	data []int64
	lazy []int64
}

func NewLazySegTree(n int) *LazySegTree {
	return &LazySegTree{n, make([]int64, 4*n), make([]int64, 4*n)}
}

func (t *LazySegTree) Update(l, r int, v int64) { t.update(1, 0, t.n, l, r, v) }
func (t *LazySegTree) Query(l, r int) int64     { return t.query(1, 0, t.n, l, r) }

func (t *LazySegTree) get(i int) int64 { return t.data[i] + t.lazy[i] }

func (t *LazySegTree) update(i, s, e, l, r int, v int64) {
	if e <= l || r <= s {
		return
	}
	if l <= s && e <= r {
		t.lazy[i] += v
		return
	}
	m := (s + e) / 2
	t.update(i*2, s, m, l, r, v)
	t.update(i*2+1, m, e, l, r, v)
	t.data[i] = max(t.get(i*2), t.get(i*2+1))
}

func (t *LazySegTree) query(i, s, e, l, r int) int64 {
	if e <= l || r <= s {
		return math.MinInt64
	}
	if l <= s && e <= r {
		return t.get(i)
	}
	m := (s + e) / 2
	return t.lazy[i] + max(t.query(i*2, s, m, l, r), t.query(i*2+1, m, e, l, r))
}

func max(i, j int64) int64 {
	if i > j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

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

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

func calculateK(diff []int64) int64 {
	var K int64
	for i := 0; i < len(diff); i++ {
		if diff[i] > 0 {
			K += diff[i]
		}
	}
	return K
}

func changeK(K int64, l int, r int, x int64, diff []int64) int64 {
	if x == 0 {
		return K
	}

	if l > 0 {
		if diff[l-1] > 0 {
			K -= diff[l-1]
		}

		if diff[l-1]+x > 0 {
			K += diff[l-1] + x
		}
	}

	if r < len(diff) {
		if diff[r] > 0 {
			K -= diff[r]
		}

		if diff[r]-x > 0 {
			K += diff[r] - x
		}
	}

	if l > 0 {
		diff[l-1] += x
	}

	if r < len(diff) {
		diff[r] -= x
	}

	return K
}

func calculateMax(a0 int64, K int64) int64 {
	c0 := (a0 + K) / 2
	b0 := a0 - c0
	b := b0 + K

	if c0 > b {
		return c0
	}
	return b
}

func main() {
	defer writer.Flush()

	var n int
	scan(&n)

	diff := make([]int64, n-1)
	var prevA, a0, a int64
	scan(&a0)
	prevA = a0
	for i := 0; i < n-1; i++ {
		scan(&a)
		diff[i] = a - prevA
		prevA = a
	}

	K := calculateK(diff)
	println(calculateMax(a0, K))
	var q, l, r int
	var x int64
	scan(&q)

	for i := 0; i < q; i++ {
		scan(&l, &r, &x)
		l--
		r--
		if l == 0 {
			a0 += x
		}

		K = changeK(K, l, r, x, diff)
		println(calculateMax(a0, K))
	}
}

package main

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

var rw = NewFastIO(os.Stdin, os.Stdout)

func max(u, v int64) int64 {
	if u > v {
		return u
	}
	return v
}
func main() {
	defer rw.Flush()
	n := rw.NextInt()
	a := rw.NextInt64s(n)
	fen := make([]int64, n+5)
	add := func(p, v int) {
		p += 2
		for ; p < n+5; p += p & -p {
			fen[p] += int64(v)
		}
	}
	sum := func(p int) int64 {
		p += 2
		res := int64(0)
		for ; p > 0; p -= p & -p {
			res += fen[p]
		}
		return res
	}
	ask := func(p int) int64 {
		return a[p] + sum(p)
	}
	del := int64(0)
	for i := 1; i < n; i++ {
		del += max(0, a[i]-a[i-1])
	}
	ans := ask(0) + del
	if ans%2 == 1 {
		ans++
	}
	rw.Println(ans / 2)
	for q := rw.NextInt(); q > 0; q-- {
		l, r, x := rw.NextInt()-1, rw.NextInt()-1, rw.NextInt()
		if l > 0 {
			del -= max(0, ask(l)-ask(l-1))
		}
		if r+1 < n {
			del -= max(0, ask(r+1)-ask(r))
		}
		add(l, x)
		add(r+1, -x)
		if l > 0 {
			del += max(0, ask(l)-ask(l-1))
		}
		if r+1 < n {
			del += max(0, ask(r+1)-ask(r))
		}
		ans := ask(0) + del
		if ans%2 == 1 {
			ans++
		}
		rw.Println(ans / 2)
	}
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}
func (f *FastIO) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}
func (f *FastIO) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n := io.NextInt()
	a := io.NextInts(n)

	asc, dsc := make([]int64, n+1), make([]int64, n+1)
	for i := 1; i <= n; i++ {
		dif := int64(a[i-1]) - (asc[i-1] + dsc[i-1])
		asc[i], dsc[i] = asc[i-1], dsc[i-1]
		if dif >= 0 {
			asc[i] += dif
		} else {
			dsc[i] += dif
		}
	}
	ast, dst := NewLazySegTree(n), NewLazySegTree(n)
	for i := 0; i < n; i++ {
		ast.Update(i, i+1, asc[i+1])
		dst.Update(i, i+1, dsc[i+1])
	}

	getAns := func() int64 {
		aa := make([]int64, n)
		dd := make([]int64, n)
		for i := range aa {
			aa[i] = ast.Query(i, i+1)
			dd[i] = dst.Query(i, i+1)
		}
		sum := ast.Query(0, n) + dst.Query(0, n)
		if sum > 0 {
			return (sum + 1) / 2
		}
		return (sum - 1) / 2
	}

	io.Println(getAns())
	for q := io.NextInt(); q > 0; q-- {
		l, r, x := io.NextInt()-1, io.NextInt(), int64(io.NextInt())
		if x >= 0 {
			y := dst.Query(l, l+1) - dst.Query(l-1, l)
			dif := max(-x, y)
			dst.Update(l, r, -dif)
			ast.Update(r, n, dif)
			x += dif
			ast.Update(l, r, x)
			dst.Update(r, n, -x)
		} else {
			y := ast.Query(l, l+1) - ast.Query(l-1, l)
			dif := max(x, -y)
			ast.Update(l, r, dif)
			dst.Update(r, n, -dif)
			x -= dif
			dst.Update(l, r, x)
			ast.Update(r, n, -x)
		}
		io.Println(getAns())
	}
}

type dType = int64
type lType = int64

const identity = math.MinInt64

type LazySegTree struct {
	n    int
	data []dType
	lazy []lType
}

func NewLazySegTree(n int) *LazySegTree {
	return &LazySegTree{n, make([]dType, 4*n), make([]lType, 4*n)}
}

func (t *LazySegTree) Update(l, r int, v dType) { t.update(1, 0, t.n, l, r, v) }
func (t *LazySegTree) Query(l, r int) dType     { return t.query(1, 0, t.n, l, r) }

func (t *LazySegTree) get(i int) dType { return t.data[i] + t.lazy[i] }

func (t *LazySegTree) update(i, s, e, l, r int, v dType) {
	if e <= l || r <= s {
		return
	}
	if l <= s && e <= r {
		t.lazy[i] += v
		return
	}
	m := (s + e) / 2
	t.update(i*2, s, m, l, r, v)
	t.update(i*2+1, m, e, l, r, v)
	t.data[i] = max(t.get(i*2), t.get(i*2+1))
}

func (t *LazySegTree) query(i, s, e, l, r int) dType {
	if e <= l || r <= s {
		return identity
	}
	if l <= s && e <= r {
		return t.get(i)
	}
	m := (s + e) / 2
	return t.lazy[i] + max(t.query(i*2, s, m, l, r), t.query(i*2+1, m, e, l, r))
}

func max(i, j dType) dType {
	if i > j {
		return i
	}
	return j
}

func min(i, j dType) dType {
	if i < j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n := io.NextInt()
	a := io.NextInts(n)

	asc, dsc := make([]int64, n+1), make([]int64, n+1)
	for i := 1; i <= n; i++ {
		dif := int64(a[i-1]) - (asc[i-1] + dsc[i-1])
		asc[i], dsc[i] = asc[i-1], dsc[i-1]
		if dif >= 0 {
			asc[i] += dif
		} else {
			dsc[i] += dif
		}
	}
	ast, dst := NewLazySegTree(n), NewLazySegTree(n)
	for i := 0; i < n; i++ {
		ast.Update(i, i+1, asc[i+1])
		dst.Update(i, i+1, dsc[i+1])
	}

	getAns := func() int64 {
		sum := ast.Query(0, n) + dst.Query(0, n)
		if sum < 0 {
			return sum / 2
		}
		return (sum + 1) / 2
	}

	fix := func(i int) {
		adif, ddif := ast.Query(i, i+1), dst.Query(i, i+1)
		if i > 0 {
			adif -= ast.Query(i-1, i)
			ddif -= dst.Query(i-1, i)
		}
		dif := max(-adif, ddif)
		ast.Update(i, n, dif)
		dst.Update(i, n, dif)
	}

	io.Println(getAns())
	for q := io.NextInt(); q > 0; q-- {
		l, r, x := io.NextInt()-1, io.NextInt(), int64(io.NextInt())
		if x >= 0 {
			ast.Update(l, n, x)
			dst.Update(r, n, -x)
		} else {
			dst.Update(l, n, x)
			ast.Update(r, n, -x)
		}
		fix(l)
		fix(r)
		io.Println(getAns())
	}
}

type LazySegTree struct {
	n    int
	data []int64
	lazy []int64
}

func NewLazySegTree(n int) *LazySegTree {
	return &LazySegTree{n, make([]int64, 4*n), make([]int64, 4*n)}
}

func (t *LazySegTree) Update(l, r int, v int64) { t.update(1, 0, t.n, l, r, v) }
func (t *LazySegTree) Query(l, r int) int64     { return t.query(1, 0, t.n, l, r) }

func (t *LazySegTree) get(i int) int64 { return t.data[i] + t.lazy[i] }

func (t *LazySegTree) update(i, s, e, l, r int, v int64) {
	if e <= l || r <= s {
		return
	}
	if l <= s && e <= r {
		t.lazy[i] += v
		return
	}
	m := (s + e) / 2
	t.update(i*2, s, m, l, r, v)
	t.update(i*2+1, m, e, l, r, v)
	t.data[i] = max(t.get(i*2), t.get(i*2+1))
}

func (t *LazySegTree) query(i, s, e, l, r int) int64 {
	if e <= l || r <= s {
		return math.MinInt64
	}
	if l <= s && e <= r {
		return t.get(i)
	}
	m := (s + e) / 2
	return t.lazy[i] + max(t.query(i*2, s, m, l, r), t.query(i*2+1, m, e, l, r))
}

func max(i, j int64) int64 {
	if i > j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n := io.NextInt()
	a := io.NextInts(n)

	asc, dsc := make([]int64, n+1), make([]int64, n+1)
	for i := 1; i <= n; i++ {
		dif := int64(a[i-1]) - (asc[i-1] + dsc[i-1])
		asc[i], dsc[i] = asc[i-1], dsc[i-1]
		if dif >= 0 {
			asc[i] += dif
		} else {
			dsc[i] += dif
		}
	}
	ast, dst := NewLazySegTree(n), NewLazySegTree(n)
	for i := 0; i < n; i++ {
		ast.Update(i, i+1, asc[i+1])
		dst.Update(i, i+1, dsc[i+1])
	}

	getAns := func() int64 {
		aa := make([]int64, n)
		dd := make([]int64, n)
		for i := range aa {
			aa[i] = ast.Query(i, i+1)
			dd[i] = dst.Query(i, i+1)
		}
		sum := ast.Query(0, n) + dst.Query(0, n)
		if sum < 0 {
			return sum / 2
		}
		return (sum + 1) / 2
	}

	io.Println(getAns())
	for q := io.NextInt(); q > 0; q-- {
		l, r, x := io.NextInt()-1, io.NextInt(), int64(io.NextInt())
		if x >= 0 {
			y := dst.Query(l, l+1) - max(0, dst.Query(l-1, l))
			dif := max(-x, y)
			dst.Update(l, r, -dif)
			ast.Update(r, n, dif)
			x += dif
			ast.Update(l, r, x)
			dst.Update(r, n, -x)
		} else {
			y := ast.Query(l, l+1) - max(0, ast.Query(l-1, l))
			dif := max(x, -y)
			ast.Update(l, r, dif)
			dst.Update(r, n, -dif)
			x -= dif
			dst.Update(l, r, x)
			ast.Update(r, n, -x)
		}
		io.Println(getAns())
	}
}

type dType = int64
type lType = int64

const identity = math.MinInt64

type LazySegTree struct {
	n    int
	data []dType
	lazy []lType
}

func NewLazySegTree(n int) *LazySegTree {
	return &LazySegTree{n, make([]dType, 4*n), make([]lType, 4*n)}
}

func (t *LazySegTree) Update(l, r int, v dType) { t.update(1, 0, t.n, l, r, v) }
func (t *LazySegTree) Query(l, r int) dType     { return t.query(1, 0, t.n, l, r) }

func (t *LazySegTree) get(i int) dType { return t.data[i] + t.lazy[i] }

func (t *LazySegTree) update(i, s, e, l, r int, v dType) {
	if e <= l || r <= s {
		return
	}
	if l <= s && e <= r {
		t.lazy[i] += v
		return
	}
	m := (s + e) / 2
	t.update(i*2, s, m, l, r, v)
	t.update(i*2+1, m, e, l, r, v)
	t.data[i] = max(t.get(i*2), t.get(i*2+1))
}

func (t *LazySegTree) query(i, s, e, l, r int) dType {
	if e <= l || r <= s {
		return identity
	}
	if l <= s && e <= r {
		return t.get(i)
	}
	m := (s + e) / 2
	return t.lazy[i] + max(t.query(i*2, s, m, l, r), t.query(i*2+1, m, e, l, r))
}

func max(i, j dType) dType {
	if i > j {
		return i
	}
	return j
}

func min(i, j dType) dType {
	if i < j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n := io.NextInt()
	a := io.NextInts(n)

	asc, dsc := make([]int64, n+1), make([]int64, n+1)
	for i := 1; i <= n; i++ {
		dif := int64(a[i-1]) - (asc[i-1] + dsc[i-1])
		asc[i], dsc[i] = asc[i-1], dsc[i-1]
		if dif >= 0 {
			asc[i] += dif
		} else {
			dsc[i] += dif
		}
	}
	ast, dst := NewLazySegTree(n), NewLazySegTree(n)
	for i := 0; i < n; i++ {
		ast.Update(i, i+1, asc[i+1])
		dst.Update(i, i+1, dsc[i+1])
	}

	getAns := func() int64 {
		aa := make([]int64, n)
		dd := make([]int64, n)
		for i := range aa {
			aa[i] = ast.Query(i, i+1)
			dd[i] = dst.Query(i, i+1)
		}
		sum := ast.Query(0, n) + dst.Query(0, n)
		if sum < 0 {
			return sum / 2
		}
		return (sum + 1) / 2
	}

	io.Println(getAns())
	for q := io.NextInt(); q > 0; q-- {
		l, r, x := io.NextInt()-1, io.NextInt(), int64(io.NextInt())
		if x >= 0 {
			y := dst.Query(l, l+1) - dst.Query(l-1, l)
			if l == 0 {
				y = dst.Query(l, l+1)
			}
			dif := max(-x, y)
			dst.Update(l, r, -dif)
			ast.Update(r, n, dif)
			x += dif
			ast.Update(l, r, x)
			dst.Update(r, n, -x)
		} else {
			y := ast.Query(l, l+1) - ast.Query(l-1, l)
			if l == 0 {
				y = ast.Query(l, l+1)
			}
			dif := max(x, -y)
			ast.Update(l, r, dif)
			dst.Update(r, n, -dif)
			x -= dif
			dst.Update(l, r, x)
			ast.Update(r, n, -x)
		}
		io.Println(getAns())
	}
}

type dType = int64
type lType = int64

const identity = math.MinInt64

type LazySegTree struct {
	n    int
	data []dType
	lazy []lType
}

func NewLazySegTree(n int) *LazySegTree {
	return &LazySegTree{n, make([]dType, 4*n), make([]lType, 4*n)}
}

func (t *LazySegTree) Update(l, r int, v dType) { t.update(1, 0, t.n, l, r, v) }
func (t *LazySegTree) Query(l, r int) dType     { return t.query(1, 0, t.n, l, r) }

func (t *LazySegTree) get(i int) dType { return t.data[i] + t.lazy[i] }

func (t *LazySegTree) update(i, s, e, l, r int, v dType) {
	if e <= l || r <= s {
		return
	}
	if l <= s && e <= r {
		t.lazy[i] += v
		return
	}
	m := (s + e) / 2
	t.update(i*2, s, m, l, r, v)
	t.update(i*2+1, m, e, l, r, v)
	t.data[i] = max(t.get(i*2), t.get(i*2+1))
}

func (t *LazySegTree) query(i, s, e, l, r int) dType {
	if e <= l || r <= s {
		return identity
	}
	if l <= s && e <= r {
		return t.get(i)
	}
	m := (s + e) / 2
	return t.lazy[i] + max(t.query(i*2, s, m, l, r), t.query(i*2+1, m, e, l, r))
}

func max(i, j dType) dType {
	if i > j {
		return i
	}
	return j
}

func min(i, j dType) dType {
	if i < j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n := io.NextInt()
	a := io.NextInts(n)

	asc, dsc := make([]int64, n+1), make([]int64, n+1)
	for i := 1; i <= n; i++ {
		dif := int64(a[i-1]) - (asc[i-1] + dsc[i-1])
		asc[i], dsc[i] = asc[i-1], dsc[i-1]
		if dif >= 0 {
			asc[i] += dif
		} else {
			dsc[i] += dif
		}
	}
	ast, dst := NewLazySegTree(n), NewLazySegTree(n)
	for i := 0; i < n; i++ {
		ast.Update(i, i+1, asc[i+1])
		dst.Update(i, i+1, dsc[i+1])
	}

	getAns := func() int64 {
		aa := make([]int64, n)
		dd := make([]int64, n)
		for i := range aa {
			aa[i] = ast.Query(i, i+1)
			dd[i] = dst.Query(i, i+1)
		}
		sum := ast.Query(0, n) + dst.Query(0, n)
		if sum < 0 {
			return sum / 2
		}
		return (sum + 1) / 2
	}

	io.Println(getAns())
	for q := io.NextInt(); q > 0; q-- {
		l, r, x := io.NextInt()-1, io.NextInt(), int64(io.NextInt())
		if x >= 0 {
			y := dst.Query(l, l+1) - dst.Query(l-1, l)
			dif := max(-x, y)
			dst.Update(l, r, -dif)
			ast.Update(r, n, dif)
			x += dif
			ast.Update(l, r, x)
			dst.Update(r, n, -x)
		} else {
			y := ast.Query(l, l+1) - ast.Query(l-1, l)
			dif := max(x, -y)
			ast.Update(l, r, dif)
			dst.Update(r, n, -dif)
			x -= dif
			dst.Update(l, r, x)
			ast.Update(r, n, -x)
		}
		io.Println(getAns())
	}
}

type dType = int64
type lType = int64

const identity = math.MinInt64

type LazySegTree struct {
	n    int
	data []dType
	lazy []lType
}

func NewLazySegTree(n int) *LazySegTree {
	return &LazySegTree{n, make([]dType, 4*n), make([]lType, 4*n)}
}

func (t *LazySegTree) Update(l, r int, v dType) { t.update(1, 0, t.n, l, r, v) }
func (t *LazySegTree) Query(l, r int) dType     { return t.query(1, 0, t.n, l, r) }

func (t *LazySegTree) get(i int) dType { return t.data[i] + t.lazy[i] }

func (t *LazySegTree) update(i, s, e, l, r int, v dType) {
	if e <= l || r <= s {
		return
	}
	if l <= s && e <= r {
		t.lazy[i] += v
		return
	}
	m := (s + e) / 2
	t.update(i*2, s, m, l, r, v)
	t.update(i*2+1, m, e, l, r, v)
	t.data[i] = max(t.get(i*2), t.get(i*2+1))
}

func (t *LazySegTree) query(i, s, e, l, r int) dType {
	if e <= l || r <= s {
		return identity
	}
	if l <= s && e <= r {
		return t.get(i)
	}
	m := (s + e) / 2
	return t.lazy[i] + max(t.query(i*2, s, m, l, r), t.query(i*2+1, m, e, l, r))
}

func max(i, j dType) dType {
	if i > j {
		return i
	}
	return j
}

func min(i, j dType) dType {
	if i < j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

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

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

func calculateK(a []int64) int64 {
	var K int64
	for i := 0; i < len(a)-1; i++ {
		if a[i+1] > a[i] {
			K += a[i+1] - a[i]
		}
	}
	return K
}

func changeK(K int64, l int, r int, x int64, a []int64) int64 {
	if l > 0 {
		if a[l] - a[l - 1] > 0 {
			K += x
		} else if a[l] + x - a[l - 1] > 0 {
			K += a[l] + x - a[l - 1]
		}
	}

	if r + 1 < len(a) {
		if a[r + 1] - a[r] > 0 {
			K += x
		} else if a[r + 1] + x - a[r] > 0 {
			K += a[r + 1] + x - a[r]
		}
	}

	for i := l; i <= r; i ++ {
		a[i] += x
	}

	return K
}

func calculateMax(a []int64, K int64) int64 {
	c := (a[0] + K) / 2
	b := a[0] - c + K

	if c > b {
		return c
	}
	return b
}

func main() {
	defer writer.Flush()

	var n int
	scan(&n)
	a := make([]int64, n)
	for i := 0; i < n; i ++ {
		scan(&a[i])
	}

	K := calculateK(a)
	println(calculateMax(a, K))
	var q, l, r int
	var x int64
	scan(&q)

	for i := 0; i < q; i ++ {
		scan(&l, &r, &x)
		l --
		r --
		K = changeK(K, l, r, x, a)
		println(calculateMax(a, K))
	}
}

package main

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

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

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

func calculateK(diff []int64) int64 {
	var K int64
	for i := 0; i < len(diff); i++ {
		if diff[i] > 0 {
			K += diff[i]
		}
	}
	return K
}

func changeK(K int64, l int, r int, x int64, diff []int64, a0 *int64) int64 {
	if l == 0 {
		*a0 += x
	}

	if x == 0 {
		return K
	}

	if l > 0 {
		if diff[l-1] > 0 {
			K -= diff[l-1]
		}

		if diff[l-1]+x > 0 {
			K += diff[l-1] + x
		}
	}

	if r < len(diff) {
		if diff[r] > 0 {
			K -= diff[r]
		}

		if diff[r]-x > 0 {
			K += diff[r] - x
		}
	}

	if l > 0 && r != l {
		diff[l-1] += x
	}

	if r < len(diff) {
		diff[r] += x
	}

	return K
}

func calculateMax(a0 int64, K int64) int64 {
	c := (a0 + K) / 2
	b := a0 - c + K

	if c > b {
		return c
	}
	return b
}

func main() {
	defer writer.Flush()

	var n int
	scan(&n)

	diff := make([]int64, n-1)
	var prevA, a0, a int64
	scan(&a0)
	prevA = a0
	for i := 0; i < n-1; i++ {
		scan(&a)
		diff[i] = a - prevA
		prevA = a
	}

	K := calculateK(diff)
	println(calculateMax(a0, K))
	var q, l, r int
	var x int64
	scan(&q)

	for i := 0; i < q; i++ {
		scan(&l, &r, &x)
		l--
		r--
		K = changeK(K, l, r, x, diff, &a0)
		println(calculateMax(a0, K))
	}
}


Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions:  the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers  the condition |ci - cj| ≤ 1 must hold.  if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions.

The first line contains single integer n (1 ≤ n ≤ 1000) — the number of cards in Vladik's sequence. The second line contains the sequence of n positive integers not exceeding 8 — the description of Vladik's sequence.

Print single integer — the length of the longest subsequence of Vladik's sequence that satisfies both conditions.

NoteIn the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.

package main

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

const sz = 8
const maxN = 1001
type Perm [sz]int
type Perms []Perm

func (p Perm) sum() int {
    s := 0
    for _, v := range p {
        s += v
    }
    return s
}

func perms() Perms {
    res := Perms{}

    cur, was := Perm{}, [sz]bool{}
    var gen func(j int)
    gen = func(j int) {
        if j == sz {
            res = append(res, cur)
            return
        }
        for i := 0; i < sz; i++ {
            if !was[i] {
                cur[j], was[i] = i, true
                gen(j+1)
                was[i] = false
            }
        }
    }
    gen(0)
    return res
}

func combs(k int) Perms {
    res := Perms{}

    cur := Perm{}
    var gen func(j int)
    gen = func(j int) {
        if j == sz {
            res = append(res, cur)
            return
        }
        for _, v := range []int{k, k+1} {
            cur[j] = v
            gen(j+1)
        }
    }
    gen(0)

    return res[:len(res)-1]
}

func options(n int) []Perms {
    res := make([]Perms, n+1)

    for k := 0; k <= n; k++ {
        for _, p := range combs(k) {
            s := p.sum()
            if s < len(res) {
                res[s] = append(res[s], p)
            }
        }
    }

    return res
}

type Index [sz][maxN][maxN]int

func buildIndex(a []int) Index {
    res := Index{}
    n := len(a)

    for d := 0; d < sz; d++ {
        for i := 0; i <= n; i++ {
            for k := 0; k < n; k++ {
                cur := i
                if k > 0 {
                    cur = -1
                    if i < n {
                        if prev := res[d][i][k-1]; prev >= 0 {
                            for j := prev; j < n; j++ {
                                if a[j] == d+1 {
                                    cur = j+1
                                    break
                                }
                            }
                        }
                    }
                }
                res[d][i][k] = cur
            }
        }
    }

    return res
}

func solve() {
    n := readInt()
    a := readIntArray(n)
    index := buildIndex(a)
    ops := options(n)

    try := func(order Perm, s int) bool {
        for _, o := range ops[s] {
            cur := 0
            for _, d := range order {
                if cur < 0 {
                    break
                }
                cur = index[d][cur][o[d]]
            }
            if cur >= 0 {
                return true
            }
        }
        return false
    }

    ans := 0
    for _, order := range perms() {
        l, r := 0, len(ops)-1
        for l < r {
            if mid := (l+r+1) / 2; try(order, mid) {
                l = mid
            } else {
                r = mid-1
            }
        }
        ans = max(ans, l)
    }
    fmt.Println(ans)
}

// Helpers

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

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

// Math

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

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

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

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

// Sort

type Ints64 []int64

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

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

import (
	"fmt"
)

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

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

	m := n / 8 + 2
	skip := make([][]int, n)

	for i := 0; i < n; i++ {
		skip[i] = make([]int, m)
		for j := 0; j < m; j++ {
			skip[i][j] = -2
		}
	}

	for i := 0; i < n; i++ {
		skip[i][0] = i
		cnt := 0
		for j := i; j >= 0; j-- {
			if a[i] == a[j] {
				cnt ++
				if cnt < m {
					skip[i][cnt] = j - 1
				} else {
					break
				}
			}
		}
	}

	return skip
}

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

	near := make([][]int, n)
	last := make([]int, 9)

	for i := 0; i < 9; i++ {
		last[i] = -1
	}

	for i := 0; i < n; i++ {
		near[i] = make([]int, 9)
		last[a[i]] = i
		for j := 0; j < 9; j++ {
			near[i][j] = last[j]
		}
	}

	return near
}

func jump(p, num, k int, skip, nearest [][]int) int{
	if k == 0 {
		return p
	}
	p = nearest[p][num + 1]
	if p == -1 {
		return -2
	}
	return skip[p][k]
}

func case0(a []int, n int) int{
	present := make([]bool, 8)
	res := 0
	for i := 0; i < n; i++ {
		if !present[a[i] - 1]{
			res ++
			present[a[i] - 1] = true
		}
	}
	return res
}

func try(a []int, skip, nearest [][]int, n, k int) (bool, int) {
	//fmt.Println("try", k)
	if k == 0 {
		return true, case0(a, n)
	}
	var dp = make([][]int, n)
	power := [8]int{1, 2, 4, 8, 16, 32, 64, 128}

	for i := 0; i < n; i++ {
		dp[i] = make([]int, 256)
		dp[i][0] = 0
		for mask := 1; mask < 256; mask++ {
			dp[i][mask] = -10000
			for j := 0; j < 8; j++ {
				if (power[j] & mask) == 0 {
					continue
				}
				jumpRes := jump(i, j, k, skip, nearest)
				if jumpRes != -2 {
					if jumpRes == -1 {
						if mask == power[j] {
							dp[i][mask] = k
						}
					} else {
						dp[i][mask] = max(dp[i][mask], dp[jumpRes][mask - power[j]] + k)
					}
				}
				jumpRes = jump(i, j, k + 1, skip, nearest)
				if jumpRes != -2 {
					if jumpRes == -1 {
						if mask == power[j] {
							dp[i][mask] = k + 1
						}
					} else {
						dp[i][mask] = max(dp[i][mask], dp[jumpRes][mask - power[j]] + k + 1)
					}
				}
			}
		}
	}
	return (dp[n - 1][255] > 0), dp[n - 1][255]
}

func solve(a []int, n int) int {
	beg := 0
	skip := compSkip(a, n)
	near := compNear(a, n)
	end := n / 8
	for beg + 1 < end {
		sr := (beg + end) /2
		if b, _ := try(a, skip, near, n, sr); b {
			beg = sr
		} else {
			end = sr - 1
		}
	}

	b, r := try(a, skip, near, n, end)

	if b {
		return r
	}

	_, r = try(a, skip, near, n, beg)

	return r
}

func main() {
	var n, x int
	fmt.Scan(&n)
	var a []int
	for i := 0; i < n; i++ {
		fmt.Scan(&x)
		a = append(a, x)
	}
	fmt.Println(solve(a, n))
}

package main

import (
	"fmt"
)

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

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

	m := n / 8 + 2
	skip := make([][]int, n)

	for i := 0; i < n; i++ {
		skip[i] = make([]int, m)
		for j := 0; j < m; j++ {
			skip[i][j] = -2
		}
	}

	for i := 0; i < n; i++ {
		skip[i][0] = i
		cnt := 0
		for j := i; j >= 0; j-- {
			if a[i] == a[j] {
				cnt ++
				if cnt < m {
					skip[i][cnt] = j - 1
				} else {
					break
				}
			}
		}
	}

	return skip
}

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

	near := make([][]int, n)
	last := make([]int, 9)

	for i := 0; i < 9; i++ {
		last[i] = -1
	}

	for i := 0; i < n; i++ {
		near[i] = make([]int, 9)
		last[a[i]] = i
		for j := 0; j < 9; j++ {
			near[i][j] = last[j]
		}
	}

	return near
}

func jump(p, num, k int, skip, nearest [][]int) int{
	if k == 0 {
		return p
	}
	p = nearest[p][num + 1]
	if p == -1 {
		return -2
	}
	return skip[p][k]
}

func case0(a []int, n int) int{
	present := make([]bool, 8)
	res := 0
	for i := 0; i < n; i++ {
		if !present[a[i] - 1]{
			res ++
			present[a[i] - 1] = true
		}
	}
	return res
}

func try(a []int, skip, nearest [][]int, n, k int) (bool, int) {
	if k == 0 {
		return true, case0(a, n)
	}
	var dp = make([][]int, n)
	power := [8]int{1, 2, 4, 8, 16, 32, 64, 128}

	for i := 0; i < n; i++ {
		dp[i] = make([]int, 256)
		dp[i][0] = 0
		for mask := 1; mask < 256; mask++ {
			dp[i][mask] = -10000
			for j := 0; j < 8; j++ {
				if (power[j] & mask) == 0 {
					continue
				}
				jumpRes := jump(i, j, k, skip, nearest)
				if jumpRes != -2 {
					if jumpRes == -1 {
						if mask == power[j] {
							dp[i][mask] = k
						} else {
							dp[i][mask] = -10000
						}
					} else {
						dp[i][mask] = max(dp[i][mask], dp[jump(i, j, k, skip, nearest)][mask - power[j]] + k)
					}
				}
				jumpRes = jump(i, j, k + 1, skip, nearest)
				if jumpRes != -2 {
					if jumpRes == -1 {
						if mask == power[j] {
							dp[i][mask] = k + 1
						} else {
							dp[i][mask] = -10000
						}
					} else {
						dp[i][mask] = max(dp[i][mask], dp[jump(i, j, k + 1, skip, nearest)][mask - power[j]] + k + 1)
					}
				}
			}
		}
	}
	//fmt.Println(dp[
	return (dp[n - 1][255] > 0), dp[n - 1][255]
}

func solve(a []int, n int) int {
	beg := 0
	skip := compSkip(a, n)
	near := compNear(a, n)
	end := n / 8
	for beg + 1 < end {
		sr := (beg + end) /2
		if b, _ := try(a, skip, near, n, sr); b {
			beg = sr
		} else {
			end = sr - 1
		}
	}

	b, r := try(a, skip, near, n, end)

	if b {
		return r
	}

	_, r = try(a, skip, near, n, beg)

	return r
}

func main() {
	var n, x int
	fmt.Scan(&n)
	var a []int
	for i := 0; i < n; i++ {
		fmt.Scan(&x)
		a = append(a, x)
	}
	fmt.Println(solve(a, n))
}

package main

import (
	"fmt"
)

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

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

	m := n / 8 + 2
	skip := make([][]int, n)

	for i := 0; i < n; i++ {
		skip[i] = make([]int, m)
		for j := 0; j < m; j++ {
			skip[i][j] = -2
		}
	}

	for i := 0; i < n; i++ {
		skip[i][0] = i
		cnt := 0
		for j := i; j >= 0; j-- {
			if a[i] == a[j] {
				cnt ++
				if cnt < m {
					skip[i][cnt] = j - 1
				} else {
					break
				}
			}
		}
	}

	return skip
}

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

	near := make([][]int, n)
	last := make([]int, 9)

	for i := 0; i < 9; i++ {
		last[i] = -1
	}

	for i := 0; i < n; i++ {
		near[i] = make([]int, 9)
		last[a[i]] = i
		for j := 0; j < 9; j++ {
			near[i][j] = last[j]
		}
	}

	return near
}

func jump(p, num, k int, skip, nearest [][]int) int{
	if k == 0 {
		return p
	}
	p = nearest[p][num + 1]
	if p == -1 {
		return -2
	}
	return skip[p][k]
}

func try(a []int, skip, nearest [][]int, n, k int) (bool, int) {
	//fmt.Println("try", k)
	var dp = make([][]int, n)
	power := [8]int{1, 2, 4, 8, 16, 32, 64, 128}

	for i := 0; i < n; i++ {
		dp[i] = make([]int, 256)
		dp[i][0] = 0
		for mask := 1; mask < 256; mask++ {
			dp[i][mask] = -10000
			for j := 0; j < 8; j++ {
				if (power[j] & mask) == 0 {
					continue
				}
				jumpRes := jump(i, j, k, skip, nearest)
				if jumpRes != -2 {
					if jumpRes == -1 {
						if mask == power[j] || k == 0 {
							dp[i][mask] = k
						} else {
							dp[i][mask] = -10000
						}
					} else {
						dp[i][mask] = max(dp[i][mask], dp[jump(i, j, k, skip, nearest)][mask - power[j]] + k)
					}
				}
				jumpRes = jump(i, j, k + 1, skip, nearest)
				if jumpRes != -2 {
					if jumpRes == -1 {
						if mask == power[j] || k == 0 {
							dp[i][mask] = k + 1
						} else {
							dp[i][mask] = -10000
						}
					} else {
						dp[i][mask] = max(dp[i][mask], dp[jump(i, j, k + 1, skip, nearest)][mask - power[j]] + k + 1)
					}
				}
			}
		}
	}
	//fmt.Println(dp[
	return (dp[n - 1][255] > 0), dp[n - 1][255]
}

func solve(a []int, n int) int {
	beg := 0
	skip := compSkip(a, n)
	near := compNear(a, n)
	end := n / 8
	for beg + 1 < end {
		sr := (beg + end) /2
		if b, _ := try(a, skip, near, n, sr); b {
			beg = sr
		} else {
			end = sr - 1
		}
	}

	b, r := try(a, skip, near, n, end)

	if b {
		return r
	}

	_, r = try(a, skip, near, n, beg)

	return r
}

func main() {
	var n, x int
	fmt.Scan(&n)
	var a []int
	for i := 0; i < n; i++ {
		fmt.Scan(&x)
		a = append(a, x)
	}
	fmt.Println(solve(a, n))
}


Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands:  Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end.  Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation.As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!

The first line contains integer n (1 ≤ n ≤ 105) — the number of Inna's commands. Then n lines follow, describing Inna's commands. Each line consists an integer:   Integer a (1 ≤ a ≤ 105) means that Inna gives Dima a command to add number a into one of containers.  Integer 0 shows that Inna asks Dima to make at most three extractions from different containers.

Each command of the input must correspond to one line of the output — Dima's action. For the command of the first type (adding) print one word that corresponds to Dima's choice:   pushStack — add to the end of the stack;  pushQueue — add to the end of the queue;  pushFront — add to the beginning of the deck;  pushBack — add to the end of the deck.  For a command of the second type first print an integer k (0 ≤ k ≤ 3), that shows the number of extract operations, then print k words separated by space. The words can be:   popStack — extract from the end of the stack;  popQueue — extract from the beginning of the line;  popFront — extract from the beginning from the deck;  popBack — extract from the end of the deck.  The printed operations mustn't extract numbers from empty containers. Also, they must extract numbers from distinct containers. The printed sequence of actions must lead to the maximum number of kisses. If there are multiple sequences of actions leading to the maximum number of kisses, you are allowed to print any of them.

0
pushStack
1 popStack
pushStack
pushQueue
2 popStack popQueue
pushStack
pushQueue
pushFront
3 popStack popQueue popFront

package main

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

var (
	in  = bufio.NewReaderSize(os.Stdin, 2<<16)
	out = bufio.NewWriterSize(os.Stdout, 2<<16)
)

func solve(cmds []int) {
	if len(cmds) <= 3 {
		inCmds := []string{"pushQueue", "pushStack", "pushFront"}
		outCmds := []string{"popQueue", "popStack", "popFront"}
		for _, s := range inCmds[:len(cmds)] {
			fmt.Fprintln(out, s)
		}
		fmt.Fprint(out, len(cmds))
		for _, s := range outCmds[:len(cmds)] {
			fmt.Fprint(out, " ", s)
		}
		fmt.Fprintln(out)
		return
	}
	top3 := []int{-1, -1, -1}
	for i := range cmds {
		for j := range top3 {
			if top3[j] == -1 || cmds[i] > cmds[top3[j]] {
				for k := 2; k > j; k-- {
					top3[k] = top3[k-1]
				}
				top3[j] = i
				break
			}
		}
	}
	sort.Ints(top3)
	i := 0
	for i = range cmds {
		fmt.Fprintln(out, "pushStack")
		if i == top3[0] {
			break
		}
	}
	for i++; i != top3[1]; i++ {
		fmt.Fprintln(out, "pushFront")
	}
	fmt.Fprintln(out, "pushQueue")
	for i++; i != top3[2]; i++ {
		fmt.Fprintln(out, "pushQueue")
	}
	fmt.Fprintln(out, "pushFront")
	for i++; i < len(cmds); i++ {
		fmt.Fprintln(out, "pushBack")
	}
	fmt.Fprintln(out, "3 popQueue popStack popFront")
}

func main() {
	defer out.Flush()

	var n int
	fmt.Fscan(in, &n)
	cmds := make([]int, n)
	for i := range cmds {
		fmt.Fscan(in, &cmds[i])
	}

	start := 0
	for i := range cmds {
		if cmds[i] == 0 {
			solve(cmds[start:i])
			start = i + 1
		}
	}
	for start < n {
		fmt.Fprintln(out, "pushStack")
		start++
	}
}

package main

import (
	"container/list"
	"fmt"
	"sort"
)

type is []struct {
	i int
	s string
}

func (is is) Len() int {
	return len(is)
}

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

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

func main() {
	var n int
	fmt.Scan(&n)
	stack := list.New()
	deck := list.New()
	queue := list.New()
	for i := 0; i < n; i++ {
		var a int
		fmt.Scan(&a)
		if a == 0 {
			cmds := make([]string, 0, 3)
			if stack.Len() > 0 {
				stack.Remove(stack.Back())
				cmds = append(cmds, "popStack")
			}
			if queue.Len() > 0 {
				queue.Remove(queue.Front())
				cmds = append(cmds, "popQueue")
			}
			if deck.Len() > 0 {
				if deck.Back().Value.(int) < deck.Front().Value.(int) {
					deck.Remove(deck.Front())
					cmds = append(cmds, "popFront")
				} else {
					deck.Remove(deck.Back())
					cmds = append(cmds, "popBack")
				}
			}
			fmt.Print(len(cmds))
			for _, cmd := range cmds {
				fmt.Printf(" %s", cmd)
			}
			fmt.Println()
		} else {
			getAction := func() string {
				if stack.Len() == 0 {
					return "pushStack"
				}
				if queue.Len() == 0 {
					return "pushQueue"
				}
				if deck.Len() < 2 {
					return "pushFront"
				}
				vals := is{
					{
						stack.Back().Value.(int),
						"pushStack",
					},
					{
						queue.Front().Value.(int),
						"pushQueue",
					},
					{
						deck.Front().Value.(int),
						"pushFront",
					},
					{
						deck.Back().Value.(int),
						"pushBack",
					},
				}
				sort.Sort(vals)
				return vals[0].s
			}
			act := getAction()
			switch act {
			case "pushStack":
				stack.PushBack(a)
			case "pushQueue":
				queue.PushBack(a)
			case "pushFront":
				deck.PushFront(a)
			case "pushBack":
				deck.PushBack(a)
			default:
				panic("w?")
			}
			fmt.Println(act)
		}
	}
}


Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.This time Miroslav laid out $$$n$$$ skewers parallel to each other, and enumerated them with consecutive integers from $$$1$$$ to $$$n$$$ in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number $$$i$$$, it leads to turning $$$k$$$ closest skewers from each side of the skewer $$$i$$$, that is, skewers number $$$i - k$$$, $$$i - k + 1$$$, ..., $$$i - 1$$$, $$$i + 1$$$, ..., $$$i + k - 1$$$, $$$i + k$$$ (if they exist). For example, let $$$n = 6$$$ and $$$k = 1$$$. When Miroslav turns skewer number $$$3$$$, then skewers with numbers $$$2$$$, $$$3$$$, and $$$4$$$ will come up turned over. If after that he turns skewer number $$$1$$$, then skewers number $$$1$$$, $$$3$$$, and $$$4$$$ will be turned over, while skewer number $$$2$$$ will be in the initial position (because it is turned again).As we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all $$$n$$$ skewers with the minimal possible number of actions. For example, for the above example $$$n = 6$$$ and $$$k = 1$$$, two turnings are sufficient: he can turn over skewers number $$$2$$$ and $$$5$$$.Help Miroslav turn over all $$$n$$$ skewers.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 1000$$$, $$$0 \leq k \leq 1000$$$) — the number of skewers and the number of skewers from each side that are turned in one step.

The first line should contain integer $$$l$$$ — the minimum number of actions needed by Miroslav to turn over all $$$n$$$ skewers. After than print $$$l$$$ integers from $$$1$$$ to $$$n$$$ denoting the number of the skewer that is to be turned over at the corresponding step.

NoteIn the first example the first operation turns over skewers $$$1$$$, $$$2$$$ and $$$3$$$, the second operation turns over skewers $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$.In the second example it is also correct to turn over skewers $$$2$$$ and $$$5$$$, but turning skewers $$$2$$$ and $$$4$$$, or $$$1$$$ and $$$5$$$ are incorrect solutions because the skewer $$$3$$$ is in the initial state after these operations.

package main

import "fmt"

func main() {
	var n, k, mn int
	fmt.Scan(&n, &k)
	mn = n
	k2p1 := k + k + 1
	kp := k + 1
	ans := 1
	for i := 1; i <= kp; i++ {
		tmp := 1
		j := i
		for {
			if j+k >= n {
				break
			}
			j += k2p1
			tmp++
		}
		if tmp < mn {
			mn = tmp
			ans = i
		}
	}
	fmt.Println(mn)
	for ; ans <= n; ans += k2p1 {
		fmt.Printf("%d ", ans)
	}
	fmt.Println("")
}

package main

import "fmt"

func doable(N int, K int, first int, generate bool) (bool, []int) {
	var ans []int
	if generate {
		ans = []int{}
	}
	cur := first
	for {
		if generate {
			ans = append(ans, cur)
		}
		if cur+K+1 > N {
			return true, ans
		}
		next := cur + K + K + 1
		if next > N {
			return false, ans
		}
		cur = next
	}
}

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

	var l int
	var pos []int
	if 2*K+1 >= N {
		l = 1
		pos = []int{N/2 + 1}
	} else {
		first := K + 1
		for {
			if done, _ := doable(N, K, first, false); done {
				break
			}
			first--
		}
		_, ans := doable(N, K, first, true)
		l = len(ans)
		pos = ans
	}
	fmt.Println(l)
	fmt.Print(pos[0])
	for i, v := range pos {
		if i > 0 {
			fmt.Print(" ", v)
		}
	}
	fmt.Println()
}

package main

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

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

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

func main() {
	defer writer.Flush()
	var n, k, t1, t2, ans int
	scanf("%d %d", &n, &k)

	t1 = n % (2*k + 1)
	t2 = 1
	if t1 != 0 {
		for t1 <= k {
			t1++
		}
	} else {
		printf("%d\n", n/(2*k+1))
		t2 = k + 1
		for t2 <= n {
			printf("%d ", t2)
			t2 += 2*k + 1
		}
		return
	}

	t1 -= k
	t2 = t1

	for t2 <= n {
		t2 += 2*k + 1
		ans++
	}
	printf("%d\n", ans)
	t2 = t1

	for t2 <= n {
		printf("%d ", t2)
		t2 += 2*k + 1
	}

}

package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 1024*1024)
	dims := readInts(r, 2)
	n := dims[0]
	k := dims[1]

	cntLeft := n % (1 + 2*k)

	var first int
	if cntLeft == 0 {
		first = k + 1
	} else {
		if cntLeft < 1 + k {
			cntLeft += k
		}
		first = cntLeft - k
	}

	var nums [] string
	for i := first; i <= n; i += 2 * k + 1 {
		nums = append(nums, strconv.Itoa(i))
	}

	fmt.Println(len(nums))
	fmt.Print(strings.Join(nums, " "))
}

func readInts(reader *bufio.Reader, n int) []int {
	tmpInts := strings.Split(readLine(reader), " ")

	var result []int
	for i := 0; i < n; i++ {
		tmpInt, err := strconv.ParseInt(tmpInts[i], 10, 64)
		checkError(err)
		result = append(result, int(tmpInt))
	}
	return result
}

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

	return strings.TrimRight(string(str), "\r\n")
}

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

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	min, list := solve1pass(n, k)
	fmt.Printf("%d\n%s", min, strings.Trim(fmt.Sprintf("%v", list), "[]"))
}
func solve(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	offset := 0
	for {
		for i := k + 1 - offset; i <= n; i += 2*k + 1 {
			min++
			list = append(list, i)
		}
		if list[len(list)-1]+k >= n && len(list) != 0 {
			break
		}
		// reset
		min = 0
		list = list[:0]
		offset++
	}
	return
}

func solve1pass(n, k int) (min int, list []int) {
	segmentSize := 2*k + 1
	numSeg := n / segmentSize
	list = make([]int, 0, numSeg+1)
	diff := n % segmentSize
	offset := 0
	switch {
	case diff == 0:
		min = numSeg
	case diff < k+1:
		offset = k + 1 - diff
		min = numSeg + 1
	case diff >= k+1:
		min = numSeg + 1
	}

	for pos := segmentSize - k - offset; pos <= n; pos += segmentSize {
		list = append(list, pos)
	}

	return min, list
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	min, list := solve1pass(n, k)
	fmt.Printf("%d\n%s", min, strings.Trim(fmt.Sprintf("%v", list), "[]"))
}
func solve(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	offset := 0
	for {
		for i := k + 1 - offset; i <= n; i += 2*k + 1 {
			min++
			list = append(list, i)
		}
		if list[len(list)-1]+k >= n && len(list) != 0 {
			break
		}
		// reset
		min = 0
		list = list[:0]
		offset++
	}
	return
}

func solve1pass(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	segmentSize := 2*k + 1
	numSeg := n / segmentSize
	diff := n % segmentSize
	if diff == 0 {
		min = numSeg
		for pos := segmentSize - k; pos <= n; pos += segmentSize {
			list = append(list, pos)
		}
		return
	} else if diff >= k+1 {
		min = numSeg + 1
		for pos := segmentSize - k; pos <= n; pos += segmentSize {
			list = append(list, pos)
		}
	} else {
		move := k + 1 - diff
		min = numSeg + 1
		for pos := segmentSize - k - move; pos <= n; pos += segmentSize {
			list = append(list, pos)
		}
	}

	return min, list
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	min, list := solve(n, k)
	fmt.Printf("%d\n%s", min, strings.Trim(fmt.Sprintf("%v", list), "[]"))
}
func solve(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	if k == 0 {
		min = n
		for i := 1; i <= n; i++ {
			list = append(list, i)
		}
		return
	}
	offset := 0
	for {
		for i := k + 1 - offset; i <= n; i += 2*k + 1 {
			min++
			list = append(list, i)
		}
		if list[len(list)-1]+k >= n && len(list) != 0 {
			break
		}
		// reset
		min = 0
		list = list[:0]
		offset++
	}
	return
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	min, list := solve(n, k)
	fmt.Printf("%d\n%s", min, strings.Trim(fmt.Sprintf("%v", list), "[]"))
}
func solve(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	offset := 0
	for {
		for i := k + 1 - offset; i <= n; i += 2*k + 1 {
			min++
			list = append(list, i)
		}
		if list[len(list)-1]+k >= n && len(list) != 0 {
			break
		}
		// reset
		min = 0
		list = list[:0]
		offset++
	}
	return
}

package main

import "fmt"

func main() {
	var n, k, mn int
	fmt.Scan(&n, &k)
	mn = n
	k2p1 := k + k + 1
	kp := k + 1
	ans := 1
	for i := 1; i <= kp; i++ {
		tmp := 0
		j := i
		for ; j <= n; j += k2p1 {
			// fmt.Printf("%d ", j)
			tmp++
			if j+k > n {
				break
			}
		}
		if j > n {
			tmp++
		}
		// fmt.Printf(" %d = %d\n", j, tmp)
		if tmp < mn {
			ans = i
			mn = tmp
		}
	}
	fmt.Println(mn)
	for ; ans <= n; ans += k2p1 {
		fmt.Printf("%d ", ans)
	}
	fmt.Println("")
}

package main

import "fmt"

func main() {
	var n, k, ans, mn int
	fmt.Scan(&n, &k)
	mn = n
	k2p1 := k + k + 1
	kp := k + 1
	for i := 1; i <= kp; i++ {
		tmp := 0
		j := i
		for ; j <= n; j += k2p1 {
			// fmt.Printf("%d ", j)
			tmp++
			if j+k > n {
				break
			}
		}
		if j > n {
			tmp++
		}
		// fmt.Printf(" %d = %d\n", j, tmp)
		if tmp < mn {
			ans = i
			mn = tmp
		}
	}
	fmt.Println(mn)
	for ; ans <= n; ans += k2p1 {
		fmt.Printf("%d ", ans)
	}
	fmt.Println("")
}

package main

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

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

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

func main() {
	defer writer.Flush()
	var n, k, t1, t2, ans int
	scanf("%d %d", &n, &k)

	t1 = n % (2*k + 1)

	if t1 != 0 {
		for t1 < k+1 {
			t1++
			t2++
		}
	}

	t1 -= k + 1
	t2 = t1

	for t2 <= n {
		t2 += 2*k + 1
		ans++
	}
	printf("%d\n", ans)
	t2 = t1

	for t2 <= n {
		printf("%d ", t2+1)
		t2 += 2*k + 1
	}

}

package main

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

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

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

func main() {
	defer writer.Flush()
	var n, k, t1, t2, ans int
	scanf("%d %d", &n, &k)

	t1 = n % (2*k + 1)

	if t1 != 0 {
		for t1 < k+1 {
			t1++
			t2++
		}
	} else {
		printf("%d\n", n/(2*k+1))
		t2 = k
		for t2 <= n {
			printf("%d ", t2+1)
			t2 += 2*k + 1
		}
	}

	t1 -= k + 1
	t2 = t1

	for t2 <= n {
		t2 += 2*k + 1
		ans++
	}
	printf("%d\n", ans)
	t2 = t1

	for t2 <= n {
		printf("%d ", t2+1)
		t2 += 2*k + 1
	}

}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	min, list := solve(n, k)
	fmt.Printf("%d\n%s", min, strings.Trim(fmt.Sprintf("%v", list), "[]"))
}
func solve(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	if k == 0 {
		min = n
		for i := 1; i <= n; i++ {
			list = append(list, i)
		}
		return
	}

	min = n/(2*(k+1)) + 1
	for i := n % (2 * (k + 1)); i < n; i += 2*k + 1 {
		list = append(list, i)
	}
	return
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	min, list := solve(n, k)
	fmt.Printf("%d\n%s", min, strings.Trim(fmt.Sprintf("%v", list), "[]"))
}
func solve(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	if k == 0 {
		min = n
		for i := 1; i <= n; i++ {
			list = append(list, i)
		}
		return
	}

	min = n/(2*(k+1)) + 1
	offset := 0
	for {
		for i := n%(2*(k+1)) - offset; i <= n; i += 2*k + 1 {
			list = append(list, i)
		}
		if list[len(list)-1]+k >= n {
			break
		}
		// reset
		list = list[:0]
		min++
		offset++
	}
	return
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	min, list := solve1pass(n, k)
	fmt.Printf("%d\n%s", min, strings.Trim(fmt.Sprintf("%v", list), "[]"))
}
func solve(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	offset := 0
	for {
		for i := k + 1 - offset; i <= n; i += 2*k + 1 {
			min++
			list = append(list, i)
		}
		if list[len(list)-1]+k >= n && len(list) != 0 {
			break
		}
		// reset
		min = 0
		list = list[:0]
		offset++
	}
	return
}

func solve1pass(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	segmentSize := 2*k + 1
	numSeg := n / segmentSize
	diff := n % segmentSize
	if diff == 0 {
		min = numSeg
		for pos := segmentSize - k; pos <= n; pos += segmentSize {
			list = append(list, pos)
		}
		return
	}

	if diff >= k+1 {
		min = numSeg + 1
		for pos := segmentSize - k; pos <= n; pos += segmentSize {
			list = append(list, pos)
		}
		list = append(list, list[len(list)-1]+k+1)
	} else {
		move := k + 1 - diff
		min = numSeg + 1
		for pos := segmentSize - k - move; pos <= n; pos += segmentSize {
			list = append(list, pos)
		}
		list = append(list, n)
	}

	return min, list
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	min, list := solve(n, k)
	fmt.Printf("%d\n%s", min, strings.Trim(fmt.Sprintf("%v", list), "[]"))
}
func solve(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	if k == 0 {
		min = n
		for i := 1; i <= n; i++ {
			list = append(list, i)
		}
		return
	}
	offset := 0
	for {
		for i := k + 1 - offset; i <= n; i += 2*k + 1 {
			min++
			list = append(list, i)
		}
		if list[len(list)-1]+k >= n {
			break
		}
		// reset
		min = 0
		list = list[:0]
		offset++
	}
	return
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	min, list := solve1pass(n, k)
	fmt.Printf("%d\n%s", min, strings.Trim(fmt.Sprintf("%v", list), "[]"))
}
func solve(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	offset := 0
	for {
		for i := k + 1 - offset; i <= n; i += 2*k + 1 {
			min++
			list = append(list, i)
		}
		if list[len(list)-1]+k >= n && len(list) != 0 {
			break
		}
		// reset
		min = 0
		list = list[:0]
		offset++
	}
	return
}

func solve1pass(n, k int) (min int, list []int) {
	list = make([]int, 0, n)
	segmentSize := 2*k + 1
	numSeg := n / segmentSize
	diff := n % segmentSize
	if diff == 0 {
		min = numSeg
		for pos := segmentSize - k; pos <= n; pos += segmentSize {
			list = append(list, pos)
		}
		return
	} else if diff >= k+1 {
		min = numSeg + 1
		for pos := segmentSize - k; pos <= n; pos += segmentSize {
			list = append(list, pos)
		}
		list = append(list, list[len(list)-1]+k+1)
	} else {
		move := k + 1 - diff
		min = numSeg + 1
		for pos := segmentSize - k - move; pos <= n; pos += segmentSize {
			list = append(list, pos)
		}
		list = append(list, n)
	}

	return min, list
}


Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces.   However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.

The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order.

First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique.

NoteIn the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: and .However, you should choose the first one as it starts in the city with the lower number.

package main

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

var stdin *bufio.Reader
var stdout *bufio.Writer

func init() {
	stdin = bufio.NewReader(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

type Node struct {
	attacked bool
	neighbor []int
}

var nodes []Node
var point1, point2 int

func dfs(x, parent int) (int, int, bool) {

	maxlength, maxendpoint := 0, 0
	for _, v := range nodes[x].neighbor {
		if v == parent {
			continue
		}

		length, endpoint ,flag := dfs(v, x)

		if flag == true {
			nodes[x].attacked = true
			if length > maxlength || (length == maxlength && endpoint < maxendpoint) {
				maxlength = length
				maxendpoint = endpoint
			}
		}
	}

	if nodes[x].attacked {
		if maxlength == 0 {
			return maxlength + 1, x, true
		} else {
			return maxlength + 1, maxendpoint, true
		}
	} else {
		return 0, 0, false
	}
}

func main() {
	n, m := 0, 0

	fmt.Fscan(stdin, &n)
	fmt.Fscan(stdin, &m)

	nodes = make([]Node, n)

	for i := 0; i < n - 1; i++ {
		u, v := 0, 0
		fmt.Fscan(stdin, &u)
		fmt.Fscan(stdin, &v)
		u--
		v--
		nodes[u].neighbor = append(nodes[u].neighbor, v)
		nodes[v].neighbor = append(nodes[v].neighbor, u)
	}

	for i := 0; i < m; i++ {
		c := 0
		fmt.Fscan(stdin, &c)
		nodes[c - 1].attacked = true
	}

	for i := 0; i < n; i++ {
		if nodes[i].attacked == true {
			_, point1, _ = dfs(i, -1)
			break
		}
	}

	diameter, point2, _ := dfs(point1, -1)
	res := 0
	for i := 0; i < n; i++ {
		if nodes[i].attacked == true {
			res += 2
		}
	}

	if point1 > point2 {
		point1 = point2
	}

	fmt.Fprintf(stdout, "%d\n%d\n", point1 + 1, res - 1 - diameter)

	stdout.Flush()
}