This is a harder version of the problem. In this version $$$n \le 500\,000$$$The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $$$n$$$ plots along the highway and is preparing to build $$$n$$$ skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from $$$1$$$ to $$$n$$$. Then if the skyscraper on the $$$i$$$-th plot has $$$a_i$$$ floors, it must hold that $$$a_i$$$ is at most $$$m_i$$$ ($$$1 \le a_i \le m_i$$$). Also there mustn't be integers $$$j$$$ and $$$k$$$ such that $$$j < i < k$$$ and $$$a_j > a_i < a_k$$$. Plots $$$j$$$ and $$$k$$$ are not required to be adjacent to $$$i$$$.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 500\,000$$$) — the number of plots. The second line contains the integers $$$m_1, m_2, \ldots, m_n$$$ ($$$1 \leq m_i \leq 10^9$$$) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.

Print $$$n$$$ integers $$$a_i$$$ — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible. If there are multiple answers possible, print any of them.

NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer $$$[10, 6, 6]$$$ is optimal. Note that the answer of $$$[6, 6, 8]$$$ also satisfies all restrictions, but is not optimal.

package main

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

type node struct {
	val    int
	length int
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := int64(1)
	//fmt.Fscanf(in, "%d\n", &t)
	for tt := int64(0); tt < t; tt++ {
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d", &a[i])
		}
		fmt.Fscanf(in, "\n")
		f1 := make([]int64, n)
		f2 := make([]int64, n)
		st := make([]node, 0)
		st = append(st, node{a[0], 1})
		curVal := int64(a[0])
		f1[0] = curVal
		for i := 1; i < n; i++ {
			curLength := 1
			for len(st) > 0 && st[len(st)-1].val >= a[i] {
				curLength += st[len(st)-1].length
				curVal -= int64(st[len(st)-1].length) * int64(st[len(st)-1].val)
				st = st[:len(st)-1]
			}
			curVal = curVal + int64(curLength)*int64(a[i])
			st = append(st, node{a[i], curLength})
			f1[i] = curVal
		}
		curVal = int64(a[n-1])
		f2[n-1] = curVal
		st = []node{node{a[n-1], 1}}
		for i := n - 2; i >= 0; i-- {
			curLength := 1
			for len(st) > 0 && st[len(st)-1].val >= a[i] {
				curLength += st[len(st)-1].length
				curVal -= int64(st[len(st)-1].length) * int64(st[len(st)-1].val)
				st = st[:len(st)-1]
			}
			curVal = curVal + int64(curLength)*int64(a[i])
			st = append(st, node{a[i], curLength})
			f2[i] = curVal
		}
		//fmt.Println(f1)
		//fmt.Println(f2)

		bestAns := f1[0] + f2[0] - int64(a[0])
		ans := 0
		for i := 1; i < n; i++ {
			//fmt.Println(bestAns, ans)
			if f1[i]+f2[i]-int64(a[i]) > bestAns {
				bestAns = f1[i] + f2[i] - int64(a[i])
				ans = i
			}
		}
		for i := ans - 1; i >= 0; i-- {
			if a[i] > a[i+1] {
				a[i] = a[i+1]
			}
		}
		for i := ans + 1; i < n; i++ {
			if a[i] > a[i-1] {
				a[i] = a[i-1]
			}
		}
		fmt.Fprintf(out, "%d", a[0])
		for i := 1; i < n; i++ {
			fmt.Fprintf(out, " %d", a[i])
		}
		fmt.Fprintf(out, "\n")
	}
	return
}

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

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

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

var partialSum []int64

type Tree struct {
	a     []int64
	incr  []int
	fixed []int
	sz    int
}

func (t *Tree) Upd(v int) {
	if v < t.sz {
		t.a[v] = t.a[v<<1] + t.a[(v<<1)|1]
	}
}

func (t *Tree) Propagate(v int, l, r int) {
	prp := t.fixed[v]
	if prp >= 0 {
		if v < t.sz {
			t.fixed[v<<1] = prp
			t.fixed[(v<<1)|1] = prp
			t.incr[v<<1] = 0
			t.incr[(v<<1)|1] = 0
		}
		t.a[v] = 0
		t.fixed[v] = -1
	}

	prp = t.incr[v]
	if prp > 0 {
		if v < t.sz {
			t.incr[v<<1] += prp
			t.incr[(v<<1)|1] += prp
		}
		t.a[v] += int64(prp) * (partialSum[r+1] - partialSum[l])
		t.incr[v] = 0
	}
}

func (t *Tree) GoAdd(v, fixed, incr, l, r, L, R int) {
	t.Propagate(v, L, R)
	if l > r {
		return
	}
	if r < L || l > R {
		return
	}
	if l <= L && R <= r {
		if fixed >= 0 {
			t.fixed[v] = fixed
			t.incr[v] = 0
			t.Propagate(v, L, R)
		}
		t.incr[v] += incr
		t.Propagate(v, L, R)
		return
	}
	t.GoAdd(v<<1, fixed, incr, l, r, L, (L+R)>>1)
	t.GoAdd((v<<1)|1, fixed, incr, l, r, (L+R)/2+1, R)
	t.Upd(v)
}

func (t *Tree) GoSum(v, l, r, L, R int) int64 {
	t.Propagate(v, L, R)
	if l > r {
		return int64(0)
	}
	if r < L || l > R {
		return int64(0)
	}
	if l <= L && R <= r {
		return t.a[v]
	}
	r1 := t.GoSum(v<<1, l, r, L, (L+R)>>1)
	r2 := t.GoSum((v<<1)|1, l, r, (L+R)/2+1, R)
	t.Upd(v)
	return r1 + r2
}

func (t *Tree) Add(l, r int, fixed int, incr int) {
	l = max(l, 0)
	r = min(r, t.sz-1)
	if l > r {
		return
	}
	t.GoAdd(1, fixed, incr, l, r, 0, t.sz-1)
}

func (t *Tree) Sum(l, r int) int64 {
	if l > r {
		return 0
	}
	res := t.GoSum(1, l, r, 0, t.sz-1)
	return res
}

func NewTree(n int) *Tree {
	sz := 1
	for sz < n {
		sz <<= 1
	}
	a := make([]int64, 2*sz+1)
	incr := make([]int, 2*sz+1)
	fixed := make([]int, 2*sz+1)
	return &Tree{a, fixed, incr, sz}
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)

	n := NextInt()
	m := make([]int, n)
	sorted := make([]int, n)
	for i := 0; i < n; i++ {
		m[i] = NextInt()
		sorted[i] = m[i]
	}
	sort.Ints(sorted)
	// newLen := 0
	// for i := 0; i < n; i++ {
	// 	if newLen == 0 || sorted[newLen-1] != sorted[i] {
	// 		sorted[newLen] = sorted[i]
	// 		newLen++
	// 	}
	// }
	// sorted = sorted[:newLen]
	// partialSum = make([]int64, len(sorted)+1)
	// partialSum[0] = 0
	// for i := 1; i <= len(sorted); i++ {
	// 	partialSum[i] = partialSum[i-1] + int64(sorted[i-1])
	// }

	stack := make([]int, n)
	add := make([]int64, n)
	len := 0
	left := make([]int64, n)
	var sum int64
	for i := 0; i < n; i++ {
		for len > 0 && m[stack[len-1]] > m[i] {
			sum -= add[len-1]
			len--
		}
		if len > 0 {
			add[len] = int64(i-stack[len-1]) * int64(m[i])
		} else {
			add[len] = int64(i+1) * int64(m[i])
		}
		sum += add[len]
		left[i] = sum
		stack[len] = i
		// stderr("left", i, "=", sum)
		len++
	}

	len = 0
	right := make([]int64, n)
	sum = 0
	for i := n - 1; i >= 0; i-- {
		for len > 0 && m[stack[len-1]] > m[i] {
			sum -= add[len-1]
			len--
		}
		if len > 0 {
			add[len] = int64(stack[len-1]-i) * int64(m[i])
		} else {
			add[len] = int64(n-i) * int64(m[i])
		}
		sum += add[len]
		right[i] = sum
		stack[len] = i
		len++
		// stderr("right", i, "=", sum)
	}
	// tree := NewTree(newLen)
	// left := make([]int64, n)
	// right := make([]int64, n)
	// for i := 0; i < n; i++ {
	// 	pos:= sort.SearchInts(sorted, m[i])
	// 	tree.Add(0, pos, -1, 1)
	// 	tree.Add(pos+1, len(sorted)-1, 0, 0)
	// 	left[i] = tree.Sum(0, pos)
	// 	// stderr("left", i, left[i])
	// }
	// tree = NewTree(newLen)
	// for i := n - 1; i >= 0; i-- {
	// 	pos := sort.SearchInts(sorted, m[i])
	// 	tree.Add(0, pos, -1, 1)
	// 	tree.Add(pos+1, len(sorted)-1, 0, 0)
	// 	right[i] = tree.Sum(0, pos)
	// 	// stderr("right", i, right[i])
	// }

	var res int64
	var resI int

	for i := 0; i < n; i++ {
		if i == 0 || left[i]+right[i]-int64(m[i]) > res {
			res = left[i] + right[i] - int64(m[i])
			resI = i
		}
	}

	// stderr("resi", resI, "sum", res)

	resarrr := make([]int, n)
	resarrr[resI] = m[resI]

	for i := resI - 1; i >= 0; i-- {
		resarrr[i] = resarrr[i+1]
		if m[i] < resarrr[i] {
			resarrr[i] = m[i]
		}
	}
	for i := resI + 1; i < n; i++ {
		resarrr[i] = resarrr[i-1]
		if m[i] < resarrr[i] {
			resarrr[i] = m[i]
		}
	}

	for i := 0; i < n; i++ {
		fmt.Fprint(out, resarrr[i], " ")
	}
}

package main

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

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	a := make([]int, n)
	sum := make([]int64, n+1)
	for i := range a {
		Fscan(in, &a[i])
		sum[i+1] = sum[i] + int64(a[i])
	}

	type pair struct{ v, i int }
	posL := make([]int, n)
	stack := []pair{{0, -1}}
	for i, v := range a {
		for {
			if top := stack[len(stack)-1]; top.v <= v {
				posL[i] = top.i
				break
			}
			stack = stack[:len(stack)-1]
		}
		stack = append(stack, pair{v, i})
	}
	posR := make([]int, n)
	stack = []pair{{0, n}}
	for i := n - 1; i >= 0; i-- {
		v := a[i]
		for {
			if top := stack[len(stack)-1]; top.v <= v {
				posR[i] = top.i
				break
			}
			stack = stack[:len(stack)-1]
		}
		stack = append(stack, pair{v, i})
	}

	dpl := make([]int64, n)
	dpl[0] = int64(a[0])
	for i, v := range a {
		if i == 0 {
			continue
		}
		l := posL[i]
		dpl[i] = int64(v)
		if l == -1 {
			dpl[i] += int64(a[i]) * int64(i)
		} else {
			dpl[i] += int64(a[i])*int64(i-l-1) + dpl[l]
		}
	}

	dpr := make([]int64, n)
	dpr[n-1] = int64(a[n-1])
	for i := n - 1; i >= 0; i-- {
		v := a[i]
		if i == n-1 {
			continue
		}
		r := posR[i]
		dpr[i] = int64(v)
		if r == n {
			dpr[i] += int64(v) * int64(n-1-i)
		} else {
			dpr[i] += int64(v)*int64(r-1-i) + dpr[r]
		}
	}

	maxAns := int64(0)
	maxPos := 0
	for i, di := range dpl {
		ans := di+dpr[i]-int64(a[i])
		if ans > maxAns {
			maxAns = ans
			maxPos = i
		}
	}

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

	ans := make([]int, n)
	ans[maxPos] = a[maxPos]

	top := a[maxPos]
	tmpMax := top
	for j := maxPos; j >= 0; j-- {
		tmpMax = min(tmpMax, a[j])
		ans[j] = tmpMax
	}
	tmpMax = top
	for j := maxPos + 1; j < n; j++ {
		tmpMax = min(tmpMax, a[j])
		ans[j] = tmpMax

	}
	for i, v := range ans {
		if i > 0 {
			Fprint(out, " ")
		}
		Fprint(out, v)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}

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

	type pair struct{ v, i int }
	posL := make([]int, n)
	stack := []pair{{0, -1}}
	for i, v := range a {
		for {
			if top := stack[len(stack)-1]; top.v <= v {
				posL[i] = top.i
				break
			}
			stack = stack[:len(stack)-1]
		}
		stack = append(stack, pair{v, i})
	}
	posR := make([]int, n)
	stack = []pair{{0, n}}
	for i := n - 1; i >= 0; i-- {
		v := a[i]
		for {
			if top := stack[len(stack)-1]; top.v <= v {
				posR[i] = top.i
				break
			}
			stack = stack[:len(stack)-1]
		}
		stack = append(stack, pair{v, i})
	}

	dpl := make([]int64, n)
	dpl[0] = int64(a[0])
	for i := 1; i < n; i++ {
		l := posL[i]
		dpl[i] = int64(a[i]) * int64(i-l)
		if l >= 0 {
			dpl[i] += dpl[l]
		}
	}
	dpr := make([]int64, n)
	dpr[n-1] = int64(a[n-1])
	for i := n - 2; i >= 0; i-- {
		r := posR[i]
		dpr[i] = int64(a[i]) * int64(r-i)
		if r < n {
			dpr[i] += dpr[r]
		}
	}

	maxAns, maxPos := int64(0), 0
	for i, v := range a {
		if ans := dpl[i] + dpr[i] - int64(v); ans > maxAns {
			maxAns, maxPos = ans, i
		}
	}

	ans := make([]interface{}, n)
	curMax := a[maxPos]
	for j := maxPos; j >= 0; j-- {
		curMax = min(curMax, a[j])
		ans[j] = curMax
	}
	curMax = a[maxPos]
	for j := maxPos + 1; j < n; j++ {
		curMax = min(curMax, a[j])
		ans[j] = curMax
	}
	Fprint(out, ans...)
}

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


An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full.Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000"  →  "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address.Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below:  "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::";  "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0";  "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0";  "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000";  "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.You've got several short records of IPv6 addresses. Restore their full record.

The first line contains a single integer n — the number of records to restore (1 ≤ n ≤ 100). Each of the following n lines contains a string — the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.

For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.

package main

import (
	"fmt"
	"net"
)

func main() {
	n := 0
	s := ""
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s", &s) // why???
		fmt.Scanf("%s", &s) // why???
		ip := net.ParseIP(s)
		for i, x := range ip {
			if i > 0 && i%2 == 0 {
				fmt.Printf(":")
			}
			fmt.Printf("%02x", x)
		}
		fmt.Println("")
	}
}

package main

import (
	"fmt"
	"net"
)

func main() {
	n := 0
	s := ""
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s", &s)
		ip := net.ParseIP(s)
		for i, x := range ip {
			if i > 0 && i%2 == 0 {
				fmt.Printf(":")
			}
			fmt.Printf("%02x", x)
		}
		fmt.Println("")
	}
}


Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.

The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.

Print "YES", if the dwarves belong to the same race. Otherwise, print "NO".

Note  First example: you can simply swap two letters in string "ab". So we get "ba".  Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b".

package main

import (
	"fmt"
)

func main() {

	var (
		i, j, na, nb int32
		a, b, ans    string
	)

	fmt.Scan(&a)
	fmt.Scan(&b)

	na = int32(len(a))
	nb = int32(len(b))

	//	println("na,nb=", na, nb)

	ans = "NO"
	for na == nb {

		for i = 0; i < na && a[i] == b[i]; i++ {
		}
		if i == na {
			break
		}

		j = i
		i++
		for ; i < na && a[i] == b[i]; i++ {
		}

		if i == na {
			break
		}

		if a[j] != b[i] || a[i] != b[j] {
			break
		}

		if a[i+1:] == b[i+1:] {
			ans = "YES"
		}
		break
	} // kulso

	fmt.Println(ans)

}

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    var a,b string
    fmt.Fscan(reader,&a)
    fmt.Fscan(reader,&b)
    ans := "YES"
    if len(a) != len(b) {
        ans = "NO"
    } else {
        j, check := -1, false
        for i := 0; i < len(a); i++ {
            if a[i] != b[i] {
                if j == -1 {
                    ans = "NO"
                    j = i
                } else if (!check) && (a[i] == b[j]) && (a[j] == b[i]) {
                    ans = "YES"
                    check = true
                } else {
                    ans = "NO"
                    break
                }
            }
        }
    }
    fmt.Println(ans)
}

// 186A-mic_rizal
package main

import (
	"fmt"
)

func main() {
	var a, b string
	var in []int
	var x int
	fmt.Scan(&a, &b)

	if len(a) != len(b) {
		fmt.Println("NO")
		return
	}

	for i := 0; i < len(b); i++ {
		if a[i] != b[i] {
			in = append(in, i)
			x++
		}
	}

	if x != 2 {
		fmt.Println("NO")
	} else {
		if a[in[0]] == b[in[1]] && a[in[1]] == b[in[0]] {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

	var a, b string
	fmt.Fscanf(reader, "%s\n", &a)
	fmt.Fscanf(reader, "%s\n", &b)
	aLen := len(a)
	bLen := len(b)
	if aLen != bLen {
		fmt.Fprintf(writer, "NO\n")
		return
	}
	arr1 := []byte(a)
	arr2 := []byte(b)
	diff := make([]int, 0)
	for idx := 0; idx < aLen; idx++ {
		if arr1[idx] != arr2[idx] {
			diff = append(diff, idx)
		}
	}
	diffLen := len(diff)
	if diffLen != 2 {
		fmt.Fprintf(writer, "NO\n")
	} else {
		arr1[diff[0]], arr1[diff[1]] = arr1[diff[1]], arr1[diff[0]]
		if string(arr1) == string(arr2) {
			fmt.Fprintf(writer, "YES\n")
		} else {
			fmt.Fprintf(writer, "NO\n")
		}
	}
}

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    var a,b string
    fmt.Fscan(reader,&a)
    fmt.Fscan(reader,&b)
    ans := "YES"
    if len(a) != len(b) {
        ans = "NO"
    } else {
        cnt := 0
        for i := 0; i < len(a); i++ {
            if a[i] != b[i] { cnt++ }
            if cnt > 2 { break }
        }
        if cnt%2 != 0 { ans = "NO" }
    }
    fmt.Println(ans)
}

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    var a,b string
    fmt.Fscan(reader,&a)
    fmt.Fscan(reader,&b)
    ans := "YES"
    if len(a) != len(b) {
        ans = "NO"
    } else {
        j, check := -1, false
        for i := 0; i < len(a); i++ {
            if a[i] != b[i] {
                if j == -1 {
                    j = i
                } else if (!check) && (a[i] == b[j]) && (a[j] == b[i]) {
                    check = true
                } else {
                    ans = "NO"
                    break
                }
            }
        }
    }
    fmt.Println(ans)
}

package main

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

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

	var a, b string
	fmt.Fscanf(reader, "%s\n", &a)
	fmt.Fscanf(reader, "%s\n", &b)
	aLen := len(a)
	bLen := len(b)
	if aLen != bLen {
		fmt.Fprintf(writer, "NO\n")
		return
	}
	arr1 := []byte(a)
	arr2 := []byte(b)
	diff := make([]int, 0)
	for idx := 0; idx < aLen; idx++ {
		if arr1[idx] != arr2[idx] {
			diff = append(diff, idx)
		}
	}
	diffLen := len(diff)
	if diffLen != 2 {
		fmt.Fprintf(writer, "NO\n")
	} else {
		arr1[diff[0]], arr1[diff[1]] = arr1[diff[1]], arr1[diff[0]]
		if string(arr1) == string(arr2) {
			fmt.Fprintf(writer, "YES\n")
		}
	}
}

package main

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

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

	var a, b string
	fmt.Fscanf(reader, "%s\n", &a)
	fmt.Fscanf(reader, "%s\n", &b)
	aLen := len(a)
	bLen := len(b)
	if aLen != bLen {
		fmt.Fprintf(writer, "NO\n")
	}
	arr1 := []byte(a)
	arr2 := []byte(b)
	diff := make([]int, 0)
	for idx := 0; idx < aLen; idx++ {
		if arr1[idx] != arr2[idx] {
			diff = append(diff, idx)
		}
	}
	diffLen := len(diff)
	if diffLen != 2 {
		fmt.Fprintf(writer, "NO\n")
	} else {
		arr1[diff[0]], arr1[diff[1]] = arr1[diff[1]], arr1[diff[0]]
		if string(arr1) == string(arr2) {
			fmt.Fprintf(writer, "YES\n")
		}
	}
}


Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.

The first input line contains a non-empty string s1. The second input line contains a non-empty string s2. Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.

Print the number of common divisors of strings s1 and s2.

NoteIn first sample the common divisors are strings "abcd" and "abcdabcd".In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa".

package main

import (
	"fmt"
)

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

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

	l := gcd(len(s1), len(s2))

	ans := 0
	for i := 1;i <= l;i ++ {
		if l % i == 0 {
			s := s1[:i]
			var flag bool
			for j := 0;j < len(s1);j ++ {
				if s1[j] != s[j % i] {
					flag = true
				}
			}
			if flag {
				continue
			}
			for j := 0;j < len(s2);j ++ {
				if s2[j] != s[j % i] {
					flag = true
				}
			}
			if !flag {
				ans ++
			}
		}
	}
	fmt.Printf("%d", ans)

}

package main

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

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

  r, _ := reader.ReadString('\n')
  s, _ := reader.ReadString('\n')
  r, s = strings.TrimSpace(r), strings.TrimSpace(s)
  x, y := len(r), len(s)
  result := 0
  for a := 1; a <= x && a <= y; a++ {
    if x%a != 0 || y%a != 0 {
      continue
    }
    okay := true
    for start := a; start < x; start += a {
      for i := 0; i < a; i++ {
        if r[start+i] != r[i] {
          okay = false
          break
        }
      }
    }
    if !okay {
      continue
    }
    for start := 0; start < y; start += a {
      for i := 0; i < a; i++ {
        if s[start+i] != r[i] {
          okay = false
          break
        }
      }
    }
    if okay {
      result++
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

import "fmt"

func next(p string) []int {
	next := make([]int, len(p)+1)
	next[0] = -1
	for i, j := 0, -1; i < len(p); {
		if j == -1 || p[i] == p[j] {
			i++
			j++
			next[i] = j
		} else {
			j = next[j]
		}
	}
	return next
}

func divisor(s1, s2 string) {
	var count int
	next1 := next(s1)
	next2 := next(s2)
	minFix1 := len(s1) - next1[len(s1)]
	minFix2 := len(s2) - next2[len(s2)]
	switch {
	case len(s1)%minFix1 == 0 && len(s2)%minFix2 == 0:
		if s1[:minFix1] == s2[:minFix2] {
			for i := minFix1; i <= len(s1) && i <= len(s2); i = minFix1 + i {
				if (len(s1)%i + len(s2)%i) == 0 {
					count++
				}
			}
		}
	case len(s1)%minFix1 != 0 && len(s2)%minFix2 == 0:
		if len(s1) < len(s2) && len(s1)%minFix2 == 0 {
			if s1 == s2[:len(s1)] {
				count = 1
			}
		}
	case len(s1)%minFix1 == 0 && len(s2)%minFix2 != 0:
		if len(s2) < len(s1) && len(s2)%minFix1 == 0 {
			if s2 == s1[:len(s2)] {
				count = 1
			}
		}
	case len(s1)%minFix1 != 0 && len(s2)%minFix2 != 0:
		if s1 == s2 {
			count = 1
		}
	}
	fmt.Println(count)
}
func main() {
	var s1, s2 string
	fmt.Scan(&s1, &s2)
	divisor(s1, s2)
}

package main

import "fmt"

func next(p string) []int {
	next := make([]int, len(p)+1)
	next[0] = -1
	for i, j := 0, -1; i < len(p); {
		if j == -1 || p[i] == p[j] {
			i++
			j++
			next[i] = j
		} else {
			j = next[j]
		}
	}
	return next
}

func divisor(s1, s2 string) {
	var count int
	next1 := next(s1)
	next2 := next(s2)
	minFix1 := len(s1) - next1[len(s1)]
	minFix2 := len(s2) - next2[len(s2)]
	switch {
	case len(s1)%minFix1 == 0 && len(s2)%minFix2 == 0:
		if s1[:minFix1] == s2[:minFix2] {
			for i := minFix1; (len(s1)%i + len(s2)%i) == 0; i = i * 2 {
				count++
			}
		}
	case len(s1)%minFix1 != 0 && len(s2)%minFix2 == 0:
		if len(s1) < len(s2) && len(s1)%minFix2 == 0 {
			if s1 == s2[:len(s1)] {
				count = 1
			}
		}
	case len(s1)%minFix1 == 0 && len(s2)%minFix2 != 0:
		if len(s2) < len(s1) && len(s2)%minFix1 == 0 {
			if s2 == s1[:len(s2)] {
				count = 1
			}
		}
	case len(s1)%minFix1 != 0 && len(s2)%minFix2 != 0:
		if s1 == s2 {
			count = 1
		}
	}
	fmt.Println(count)
}
func main() {
	var s1, s2 string
	fmt.Scan(&s1, &s2)
	divisor(s1, s2)
}


This is yet another problem dealing with regular bracket sequences.We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.

The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.

Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

type Pair struct {
	leftIndex  int
	rightIndex int
}

type Brace struct {
	brace byte
	index int
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var s string
	fmt.Fscanf(reader, "%s\n", &s)
	b := []byte(s)

	braceStack, bracePointer := make([]*Brace, 1000000, 1000000), 0
	pairStack, pairPointer := make([]*Pair, 1000000, 1000000), 0
	max, maxCount := 0, 0

	for i := 0; i < len(b); i++ {
		flag := false
		if bracePointer != 0 {
			if braceStack[bracePointer-1].brace == '(' && b[i] == ')' {
				pair := Pair{braceStack[bracePointer-1].index, i}
				bracePointer--
				for pairPointer != 0 {
					p := pairStack[pairPointer-1]
					if p.rightIndex == pair.leftIndex-1 {
						pair.leftIndex = p.leftIndex
						pairPointer--
					} else if p.rightIndex == pair.rightIndex-1 && p.leftIndex == pair.leftIndex+1 {
						pairPointer--
					} else {
						break
					}
				}
				pairStack[pairPointer] = &pair
				pairPointer++
				size := pair.rightIndex - pair.leftIndex + 1
				if size > max {
					max = size
					maxCount = 0
				}
				if size == max {
					maxCount++
				}
				flag = true
			}
		}
		if !flag {
			braceStack[bracePointer] = &Brace{b[i], i}
			bracePointer++
		}
	}
	if max == 0 {
		fmt.Printf("0 1")
	} else {
		fmt.Printf("%d %d", max, maxCount)
	}

}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	s, _ := reader.ReadString('\n')
	a, b := solve(s)

	fmt.Printf("%d %d\n", a, b)
}

func solve(s string) (int, int) {
	n := len(s)
	dp := make([]int, n)

	st := make([]int, n)
	var p int

	for i := 0; i < n; i++ {
		dp[i] = -1
		if s[i] == '(' {
			st[p] = i
			p++
			continue
		}
		if s[i] == ')' {
			if p == 0 {
				continue
			}
			dp[i] = st[p-1]
			p--
			if dp[i] > 0 && dp[dp[i]-1] >= 0 {
				dp[i] = dp[dp[i]-1]
			}
		}
	}

	var best int
	var cnt = 1
	for i := 0; i < n; i++ {
		if dp[i] < 0 {
			continue
		}
		if i-dp[i]+1 > best {
			best = i - dp[i] + 1
			cnt = 1
		} else if i-dp[i]+1 == best {
			cnt++
		}
	}

	return best, cnt
}

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

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

  max, count := 0, 1
  line, _ := reader.ReadString('\n')
  s := strings.TrimSpace(line)
  depth := 0
  starts := make([]int, len(s)+1)
  starts[0] = -1
  for pos, rune := range s {
    if rune == '(' {
      depth++
      starts[depth] = pos
    } else if depth == 0 {
      starts[0] = pos
    } else {
      depth--
      length := pos - starts[depth]
      if length == max {
        count++
      } else if length > max {
        max = length
        count = 1
      }
      //writer.WriteString(fmt.Sprintf("depth = %d, starts[%d] = %d, pos = %d, length = %d, max = %d, count = %d\n", depth, depth, starts[depth], pos, length, max, count))
    }
  }
  writer.WriteString(fmt.Sprintf("%d %d\n", max, count))
}

package main

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

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

	var s string
	fmt.Fscanf(r, "%s", &s)

	good := make([]bool, len(s))
	beg := make([]int, len(s))

	for i := 0; i < len(s)-1; i++ {
		if s[i] == ')' {
			continue
		}

		l, r := i, i+1
		stop := false
		for !stop {
			stop = true
			for l >= 0 && r < len(s) && s[l] == '(' && s[r] == ')' {
				good[l] = true
				good[r] = true
				beg[r] = l - 1
				beg[l] = l - 1
				l--
				r++
			}
			stk := make([]int, 0)
			for l >= 0 && good[l] {
				stop = false
				stk = append(stk, l)
				l = beg[l]
			}
			for _, e := range stk {
				beg[e] = l
			}
		}
	}

	best, count := 0, 1
	for i := 0; i < len(s); i++ {
		cc := 0
		for i < len(s) && good[i] {
			i++
			cc++
		}
		if cc == 0 {
			continue
		}
		if best == cc {
			count++
		} else if best < cc {
			best = cc
			count = 1
		}
	}

	fmt.Printf("%d %d\n", best, count)
}

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

func scan(args ...interface{}) (int, error) {
	return fmt.Fscan(stdin, args...)
}

func printf(format string, args ...interface{}) {
	fmt.Fprintf(stdout, format, args...)
}

var s string

func main() {
	for true {
		if _, err := scan(&s); err != nil {
			break
		}
		n := len(s)
		longest := 0
		count := 1
		var leftBraceStack []int
		leftBraceStack = append(leftBraceStack, -1)
		stackI := 0
		for i := 0; i < n; i++ {
			if s[i] == '(' {
				if stackI + 1 == len(leftBraceStack) {
					leftBraceStack = append(leftBraceStack, i)
				} else {
					leftBraceStack[stackI + 1] = i
				}
				stackI++
			} else {
				if stackI > 0 {
					length := i - leftBraceStack[stackI - 1]
					stackI--
					if length == longest {
						count++
					} else if (length > longest) {
						longest = length
						count = 1
					}
				} else {
					leftBraceStack[0] = i
				}
			}
		}
		printf("%d %d\n", longest, count)
		stdout.Flush()
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol5C(reader io.Reader, writer io.Writer) {
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var s string
	Fscan(in, &s)
	bs := []byte(s)

	size := 0
	for i, c := range s {
		if c == '(' {
			size++
		} else {
			size--
			if size < 0 {
				bs[i] = ' '
				size = 0
			}
		}
	}
	size = 0
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == ')' {
			size++
		} else {
			size--
			if size < 0 {
				bs[i] = ' '
				size = 0
			}
		}
	}
	maxLen := map[int]int{0: 1}
	for _, ss := range strings.Split(string(bs), " ") {
		if ss != "" {
			maxLen[len(ss)]++
		}
	}
	ans := 0
	for l := range maxLen {
		if l > ans {
			ans = l
		}
	}
	Fprint(out, ans, maxLen[ans])
}

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

package main

import (
	"os"
	"strings"
	"fmt"
	"strconv"
	"errors"
	"io"
	"unicode/utf8"
	"bytes"
)

func mx(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}
func main() {
	source := []rune(nextWord())
	d := make([]int, len(source))
	t := 0
	m := 0
	for i, x := range source {
		if x == '(' {
			t++
			d[i] = t
		} else {
			d[i] = t
			if t > 0 {
				t--
			}
		}
		m = mx(m, d[i])
	}
	//for i := m; i >= 0; i-- {
	//	for _, x := range d {
	//		if x == i {
	//			fmt.Print(x)
	//		} else {
	//			fmt.Print(" ")
	//		}
	//	}
	//	fmt.Println()
	//}

	l := make([]int, m + 1)
	prev := d[len(d) - 1]
	maxlen := 0
	lencount := make(map[int]int)
	for i := len(d) - 1; i >= 0; i-- {
		if d[i] < prev {
			if l[d[i]] > 0 {
				l[d[i]] += l[d[i + 1]]
			}
			cl := l[d[i + 1]]
			if cl % 2 != 0 {
				cl--
			}
			if _, ok := lencount[cl]; ok {
				lencount[cl]++
			} else {
				lencount[cl] = 1
			}
			maxlen = mx(maxlen, cl)
			l[d[i + 1]] = 0
		}
		l[d[i]]++
		prev = d[i]
	}
	if source[0] == '(' {
		cl := l[d[0]]
		if cl % 2 != 0 {
			cl--
		}
		if _, ok := lencount[cl]; ok {
			lencount[cl]++
		} else {
			lencount[cl] = 1
		}
		maxlen = mx(maxlen, cl)
	}
	if maxlen == 0 {
		fmt.Println("0 1")
	} else {
		fmt.Printf("%d %d\n", maxlen, lencount[maxlen])
	}
}

var lineScanner *Scanner
var wordScanner *Scanner

func init() {
	lineScanner = NewScanner(os.Stdin)
	wordScanner = NewScanner(strings.NewReader(""))
	wordScanner.Split(ScanWords)
}
func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

func nextWord() string {
	for !wordScanner.Scan() {
		if err := wordScanner.Err(); err != nil {
			panic(err)
		}
		line, err := nextLine()
		if err != nil {
			return ""
		}
		wordScanner = NewScanner(strings.NewReader(line))
		wordScanner.Split(ScanWords)
	}
	return wordScanner.Text()
}

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

func nextInt64() int64 {
	res, err := strconv.ParseInt(nextWord(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func nextFloat64() float64 {
	res, err := strconv.ParseFloat(nextWord(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

// Scanner provides a convenient interface for reading data such as
// a file of newline-delimited lines of text. Successive calls to
// the Scan method will step through the 'tokens' of a file, skipping
// the bytes between the tokens. The specification of a token is
// defined by a split function of type SplitFunc; the default split
// function breaks the input into lines with line termination stripped. Split
// functions are defined in this package for scanning a file into
// lines, bytes, UTF-8-encoded runes, and space-delimited words. The
// client may instead provide a custom split function.
//
// Scanning stops unrecoverably at EOF, the first I/O error, or a token too
// large to fit in the buffer. When a scan stops, the reader may have
// advanced arbitrarily far past the last token. Programs that need more
// control over error handling or large tokens, or must run sequential scans
// on a reader, should use bufio.Reader instead.
//
type Scanner struct {
	r            io.Reader // The reader provided by the client.
	split        SplitFunc // The function to split the tokens.
	maxTokenSize int       // Maximum size of a token; modified by tests.
	token        []byte    // Last token returned by split.
	buf          []byte    // Buffer used as argument to split.
	start        int       // First non-processed byte in buf.
	end          int       // End of data in buf.
	err          error     // Sticky error.
	empties      int       // Count of successive empty tokens.
	scanCalled   bool      // Scan has been called; buffer is in use.
	done         bool      // Scan has finished.
}

// SplitFunc is the signature of the split function used to tokenize the
// input. The arguments are an initial substring of the remaining unprocessed
// data and a flag, atEOF, that reports whether the Reader has no more data
// to give. The return values are the number of bytes to advance the input
// and the next token to return to the user, plus an error, if any. If the
// data does not yet hold a complete token, for instance if it has no newline
// while scanning lines, SplitFunc can return (0, nil, nil) to signal the
// Scanner to read more data into the slice and try again with a longer slice
// starting at the same point in the input.
//
// If the returned error is non-nil, scanning stops and the error
// is returned to the client.
//
// The function is never called with an empty data slice unless atEOF
// is true. If atEOF is true, however, data may be non-empty and,
// as always, holds unprocessed text.
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

// Errors returned by Scanner.
var (
	ErrTooLong         = errors.New("bufio.Scanner: token too long")
	ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
	ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
)

const (
// MaxScanTokenSize is the maximum size used to buffer a token
// unless the user provides an explicit buffer with Scan.Buffer.
// The actual maximum token size may be smaller as the buffer
// may need to include, for instance, a newline.
	MaxScanTokenSize = 2 * 1024 * 2014

	startBufSize = 4096 // Size of initial allocation for buffer.
)

// NewScanner returns a new Scanner to read from r.
// The split function defaults to ScanLines.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        ScanLines,
		maxTokenSize: MaxScanTokenSize,
	}
}

// Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Err() error {
	if s.err == io.EOF {
		return nil
	}
	return s.err
}

// Bytes returns the most recent token generated by a call to Scan.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Scan. It does no allocation.
func (s *Scanner) Bytes() []byte {
	return s.token
}

// Text returns the most recent token generated by a call to Scan
// as a newly allocated string holding its bytes.
func (s *Scanner) Text() string {
	return string(s.token)
}

// ErrFinalToken is a special sentinel error value. It is intended to be
// returned by a Split function to indicate that the token being delivered
// with the error is the last token and scanning should stop after this one.
// After ErrFinalToken is received by Scan, scanning stops with no error.
// The value is useful to stop processing early or when it is necessary to
// deliver a final empty token. One could achieve the same behavior
// with a custom error value but providing one here is tidier.
// See the emptyFinalToken example for a use of this value.
var ErrFinalToken = errors.New("final token")

// Scan advances the Scanner to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Scan returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil.
// Scan panics if the split function returns 100 empty tokens without
// advancing the input. This is a common error mode for scanners.
func (s *Scanner) Scan() bool {
	if s.done {
		return false
	}
	s.scanCalled = true
	// Loop until we have a token.
	for {
		// See if we can get a token with what we already have.
		// If we've run out of data but have an error, give the split function
		// a chance to recover any remaining, possibly empty token.
		if s.end > s.start || s.err != nil {
			advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
			if err != nil {
				if err == ErrFinalToken {
					s.token = token
					s.done = true
					return true
				}
				s.setErr(err)
				return false
			}
			if !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				if s.err == nil || advance > 0 {
					s.empties = 0
				} else {
					// Returning tokens not advancing input at EOF.
					s.empties++
					if s.empties > 100 {
						panic("bufio.Scan: 100 empty tokens without progressing")
					}
				}
				return true
			}
		}
		// We cannot generate a token with what we are holding.
		// If we've already hit EOF or an I/O error, we are done.
		if s.err != nil {
			// Shut it down.
			s.start = 0
			s.end = 0
			return false
		}
		// Must read more data.
		// First, shift data to beginning of buffer if there's lots of empty space
		// or space is needed.
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		// Is the buffer full? If so, resize.
		if s.end == len(s.buf) {
			// Guarantee no overflow in the multiplication below.
			const maxInt = int(^uint(0) >> 1)
			if len(s.buf) >= s.maxTokenSize || len(s.buf) > maxInt/2 {
				s.setErr(ErrTooLong)
				return false
			}
			newSize := len(s.buf) * 2
			if newSize == 0 {
				newSize = startBufSize
			}
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		// Finally we can read some input. Make sure we don't get stuck with
		// a misbehaving Reader. Officially we don't need to do this, but let's
		// be extra careful: Scanner is for safe, simple jobs.
		for loop := 0; ; {
			n, err := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if err != nil {
				s.setErr(err)
				break
			}
			if n > 0 {
				s.empties = 0
				break
			}
			loop++
			if loop > 10 {
				s.setErr(io.ErrNoProgress)
				break
			}
		}
	}
}

// advance consumes n bytes of the buffer. It reports whether the advance was legal.
func (s *Scanner) advance(n int) bool {
	if n < 0 {
		s.setErr(ErrNegativeAdvance)
		return false
	}
	if n > s.end-s.start {
		s.setErr(ErrAdvanceTooFar)
		return false
	}
	s.start += n
	return true
}

// setErr records the first error encountered.
func (s *Scanner) setErr(err error) {
	if s.err == nil || s.err == io.EOF {
		s.err = err
	}
}

// Buffer sets the initial buffer to use when scanning and the maximum
// size of buffer that may be allocated during scanning. The maximum
// token size is the larger of max and cap(buf). If max <= cap(buf),
// Scan will use this buffer only and do no allocation.
//
// By default, Scan uses an internal buffer and sets the
// maximum token size to MaxScanTokenSize.
//
// Buffer panics if it is called after scanning has started.
func (s *Scanner) Buffer(buf []byte, max int) {
	if s.scanCalled {
		panic("Buffer called after Scan")
	}
	s.buf = buf[0:cap(buf)]
	s.maxTokenSize = max
}

// Split sets the split function for the Scanner.
// The default split function is ScanLines.
//
// Split panics if it is called after scanning has started.
func (s *Scanner) Split(split SplitFunc) {
	if s.scanCalled {
		panic("Split called after Scan")
	}
	s.split = split
}

// Split functions

// ScanBytes is a split function for a Scanner that returns each byte as a token.
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	return 1, data[0:1], nil
}

var errorRune = []byte(string(utf8.RuneError))

// ScanRunes is a split function for a Scanner that returns each
// UTF-8-encoded rune as a token. The sequence of runes returned is
// equivalent to that from a range loop over the input as a string, which
// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
// Because of the Scan interface, this makes it impossible for the client to
// distinguish correctly encoded replacement runes from encoding errors.
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}

	// Fast path 1: ASCII.
	if data[0] < utf8.RuneSelf {
		return 1, data[0:1], nil
	}

	// Fast path 2: Correct UTF-8 decode without error.
	_, width := utf8.DecodeRune(data)
	if width > 1 {
		// It's a valid encoding. Width cannot be one for a correctly encoded
		// non-ASCII rune.
		return width, data[0:width], nil
	}

	// We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
	// Is the error because there wasn't a full rune to be decoded?
	// FullRune distinguishes correctly between erroneous and incomplete encodings.
	if !atEOF && !utf8.FullRune(data) {
		// Incomplete; get more bytes.
		return 0, nil, nil
	}

	// We have a real UTF-8 encoding error. Return a properly encoded error rune
	// but advance only one byte. This matches the behavior of a range loop over
	// an incorrectly encoded string.
	return 1, errorRune, nil
}

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[0 : len(data)-1]
	}
	return data
}

// ScanLines is a split function for a Scanner that returns each line of
// text, stripped of any trailing end-of-line marker. The returned line may
// be empty. The end-of-line marker is one optional carriage return followed
// by one mandatory newline. In regular expression notation, it is `\r?\n`.
// The last non-empty line of input will be returned even if it has no
// newline.
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\n'); i >= 0 {
		// We have a full newline-terminated line.
		return i + 1, dropCR(data[0:i]), nil
	}
	// If we're at EOF, we have a final, non-terminated line. Return it.
	if atEOF {
		return len(data), dropCR(data), nil
	}
	// Request more data.
	return 0, nil, nil
}

// isSpace reports whether the character is a Unicode white space character.
// We avoid dependency on the unicode package, but check validity of the implementation
// in the tests.
func isSpace(r rune) bool {
	if r <= '\u00FF' {
		// Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
		switch r {
		case ' ', '\t', '\n', '\v', '\f', '\r':
			return true
		case '\u0085', '\u00A0':
			return true
		}
		return false
	}
	// High-valued ones.
	if '\u2000' <= r && r <= '\u200a' {
		return true
	}
	switch r {
	case '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
		return true
	}
	return false
}

// ScanWords is a split function for a Scanner that returns each
// space-separated word of text, with surrounding spaces deleted. It will
// never return an empty string. The definition of space is set by
// unicode.IsSpace.
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	// Skip leading spaces.
	start := 0
	for width := 0; start < len(data); start += width {
		var r rune
		r, width = utf8.DecodeRune(data[start:])
		if !isSpace(r) {
			break
		}
	}
	// Scan until space, marking end of word.
	for width, i := 0, start; i < len(data); i += width {
		var r rune
		r, width = utf8.DecodeRune(data[i:])
		if isSpace(r) {
			return i + width, data[start:i], nil
		}
	}
	// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	// Request more data.
	return start, nil, nil
}

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var s string
	fmt.Fscanf(reader, "%s\n", &s)
	b := []byte(s)

	var leftCount, rightCount, maxPair, maxCount int

	for i := 0; i < len(b); i++ {
		if s[i] == '(' {
			leftCount++
		} else if s[i] == ')' {
			rightCount++
		}
		if leftCount < rightCount {
			if leftCount > maxPair {
				maxPair = leftCount
				maxCount = 0
			}
			if leftCount == maxPair {
				maxCount++
			}
			leftCount, rightCount = 0, 0
		}
	}
	if rightCount > maxPair {
		maxPair = rightCount
		maxCount = 0
	}
	if rightCount == maxPair {
		maxCount++
	}
	if maxPair == 0 {
		fmt.Printf("0 1")
	} else {
		fmt.Printf("%d %d", maxPair*2, maxCount)
	}

}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	s, _ := reader.ReadString('\n')
	a, b := solve(s)

	fmt.Sprintf("%d %d\n", a, b)
}

func solve(s string) (int, int) {
	n := len(s)
	dp := make([]int, n)

	st := make([]int, n)
	var p int

	for i := 0; i < n; i++ {
		dp[i] = -1
		if s[i] == '(' {
			st[p] = i
			p++
			continue
		}
		if s[i] == ')' {
			if p == 0 {
				continue
			}
			dp[i] = st[p-1]
			p--
			if dp[i] > 0 && dp[dp[i]-1] >= 0 {
				dp[i] = dp[dp[i]-1]
			}
		}
	}

	var best int
	var cnt = 1
	for i := 0; i < n; i++ {
		if dp[i] < 0 {
			continue
		}
		if i-dp[i]+1 > best {
			best = i - dp[i] + 1
			cnt = 1
		} else if i-dp[i]+1 == best {
			cnt++
		}
	}

	return best, cnt
}

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

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

  max, count := 0, 1
  line, _ := reader.ReadString('\n')
  s := strings.TrimSpace(line)
  starts := make([]int, len(s))
  depth := 0
  for pos, rune := range s {
    if rune == '(' {
      depth++
      starts[depth] = pos
    } else if depth == 0 {
      starts[0] = pos+1
    } else {
      depth--
      length := pos + 1 - starts[depth]
      if length == max {
        count++
      } else if length > max {
        max = length
        count = 1
      }
    }
  }
  writer.WriteString(fmt.Sprintf("%d %d\n", max, count))
}

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

func scan(args ...interface{}) (int, error) {
	return fmt.Fscan(stdin, args...)
}

func printf(format string, args ...interface{}) {
	fmt.Fprintf(stdout, format, args...)
}

var s string

func main() {
	for true {
		if _, err := scan(&s); err != nil {
			break
		}
		n := len(s)
		longest := 0
		count := 1
		var leftBraceStack []int
		stackI := 0
		for i := 0; i < n; i++ {
			if s[i] == '(' {
				if stackI == len(leftBraceStack) {
					leftBraceStack = append(leftBraceStack, i)
				} else {
					leftBraceStack[stackI] = i
				}
				stackI++
			} else {
				if stackI > 0 {
					length := i - leftBraceStack[stackI - 1] + 1
					stackI--
					if length == longest {
						count++
					} else if (length > longest) {
						longest = length
						count = 1
					}
				}
			}
		}
		printf("%d %d\n", longest, count)
		stdout.Flush()
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol5C(reader io.Reader, writer io.Writer) {
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var s string
	Fscan(in, &s)

	maxLen := map[int]int{0: 1}
	size, pairCnt := 0, 0
	for _, c := range s {
		if c == '(' {
			size++
		} else {
			size--
			if size >= 0 {
				pairCnt++
				maxLen[2*pairCnt]++
			} else {
				size, pairCnt = 0, 0
			}
		}
	}
	ans := 0
	for l := range maxLen {
		if l > ans {
			ans = l
		}
	}
	Fprintln(out, ans, maxLen[ans])
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol5C(reader io.Reader, writer io.Writer) {
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var s string
	Fscan(in, &s)
	s += "$"

	maxLen := map[int]int{0: 1}
	cnt := 0
	size := 0
	for _, c := range s {
		if c == '(' {
			size++
			cnt++
		} else if c == ')' {
			size--
			if size < 0 {
				size = 0
				if cnt > 0 {
					maxLen[cnt]++
					cnt = 0
				}
			} else {
				cnt++
			}
		} else {
			if size == 0 && cnt > 0 {
				maxLen[cnt]++
			}
		}
	}
	ans := 0
	for l := range maxLen {
		if l > ans {
			ans = l
		}
	}
	Fprintln(out, ans, maxLen[ans])
}

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

package main

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

func mx(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}
func main() {
	depth, current, max := 0, 0, 0
	counts := make(map[int]int)
	counts[0] = 1
	source := []rune(nextWord())
	for i, x := range source {
		if x == '(' {
			depth++
		} else if x == ')' {
			if depth > 0 {
				depth--
				current++
				if depth == 0 {
					if i < len(source) - 1 && source[i + 1] == '(' {
						continue
					}
					max = mx(max, current)
					if _, ex := counts[current]; ex {
						counts[current]++
					} else {
						counts[current] = 1
					}
					current = 0
				}
			}
		}
		if i % 100 == 0 {
			runtime.GC()
		}
	}
	max = mx(max, current)
	if _, ex := counts[current]; ex && current > 0 {
		counts[current]++
	} else {
		counts[current] = 1
	}
	printf("%d %d\n", max * 2, counts[max])
}

var lineScanner *bufio.Scanner
var wordScanner *bufio.Scanner

func init() {
	lineScanner = bufio.NewScanner(os.Stdin)
	wordScanner = bufio.NewScanner(strings.NewReader(""))
	wordScanner.Split(bufio.ScanWords)
}
func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

func nextWord() string {
	for !wordScanner.Scan() {
		if err := wordScanner.Err(); err != nil {
			panic(err)
		}
		line, err := nextLine()
		if err != nil {
			return ""
		}
		wordScanner = bufio.NewScanner(strings.NewReader(line))
		wordScanner.Split(bufio.ScanWords)
	}
	return wordScanner.Text()
}

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

func nextInt64() int64 {
	res, err := strconv.ParseInt(nextWord(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func nextFloat64() float64 {
	res, err := strconv.ParseFloat(nextWord(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

package main

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

func mx(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}
func main() {
	r := bufio.NewReaderSize(os.Stdin, 2000000)
	src, _ := r.ReadString(byte('\n'))
	source := []rune(src)
	d := make([]int, len(source))
	t := 0
	m := 0
	for i, x := range source {
		if x == '(' {
			t++
			d[i] = t
		} else {
			d[i] = t
			if t > 0 {
				t--
			}
		}
		m = mx(m, d[i])
	}
	//for i := m; i >= 0; i-- {
	//	for _, x := range d {
	//		if x == i {
	//			fmt.Print(x)
	//		} else {
	//			fmt.Print(" ")
	//		}
	//	}
	//	fmt.Println()
	//}

	l := make([]int, m + 1)
	prev := d[len(d) - 1]
	maxlen := 0
	lencount := make(map[int]int)
	for i := len(d) - 1; i >= 0; i-- {
		if d[i] < prev {
			if l[d[i]] > 0 {
				l[d[i]] += l[d[i + 1]]
			}
			cl := l[d[i + 1]]
			if cl % 2 != 0 {
				cl--
			}
			if _, ok := lencount[cl]; ok {
				lencount[cl]++
			} else {
				lencount[cl] = 1
			}
			maxlen = mx(maxlen, cl)
			l[d[i + 1]] = 0
		}
		l[d[i]]++
		prev = d[i]
	}
	if source[0] == '(' {
		cl := l[d[0]]
		if cl % 2 != 0 {
			cl--
		}
		if _, ok := lencount[cl]; ok {
			lencount[cl]++
		} else {
			lencount[cl] = 1
		}
		maxlen = mx(maxlen, cl)
	}
	if maxlen == 0 {
		fmt.Println("0 1")
	} else {
		fmt.Printf("%d %d\n", maxlen, lencount[maxlen])
	}
}

var lineScanner *bufio.Scanner
var wordScanner *bufio.Scanner

func init() {
	lineScanner = bufio.NewScanner(os.Stdin)
	wordScanner = bufio.NewScanner(strings.NewReader(""))
	wordScanner.Split(bufio.ScanWords)
}
func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

func nextWord() string {
	for !wordScanner.Scan() {
		if err := wordScanner.Err(); err != nil {
			panic(err)
		}
		line, err := nextLine()
		if err != nil {
			return ""
		}
		wordScanner = bufio.NewScanner(strings.NewReader(line))
		wordScanner.Split(bufio.ScanWords)
	}
	return wordScanner.Text()
}

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

func nextInt64() int64 {
	res, err := strconv.ParseInt(nextWord(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func nextFloat64() float64 {
	res, err := strconv.ParseFloat(nextWord(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

package main

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

func mx(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}
func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Recovered", r)
		}
	}()
	source := []rune(nextWord())
	d := make([]int, len(source))
	t := 0
	m := 0
	for i, x := range source {
		if x == '(' {
			t++
			d[i] = t
		} else {
			d[i] = t
			if t > 0 {
				t--
			}
		}
		m = mx(m, d[i])
	}
	//for i := m; i >= 0; i-- {
	//	for _, x := range d {
	//		if x == i {
	//			fmt.Print(x)
	//		} else {
	//			fmt.Print(" ")
	//		}
	//	}
	//	fmt.Println()
	//}

	l := make([]int, m + 1)
	prev := d[len(d) - 1]
	maxlen := 0
	lencount := make(map[int]int)
	for i := len(d) - 1; i >= 0; i-- {
		if d[i] < prev {
			if l[d[i]] > 0 {
				l[d[i]] += l[d[i + 1]]
			}
			cl := l[d[i + 1]]
			if cl % 2 != 0 {
				cl--
			}
			if _, ok := lencount[cl]; ok {
				lencount[cl]++
			} else {
				lencount[cl] = 1
			}
			maxlen = mx(maxlen, cl)
			l[d[i + 1]] = 0
		}
		l[d[i]]++
		prev = d[i]
	}
	if source[0] == '(' {
		cl := l[d[0]]
		if cl % 2 != 0 {
			cl--
		}
		if _, ok := lencount[cl]; ok {
			lencount[cl]++
		} else {
			lencount[cl] = 1
		}
		maxlen = mx(maxlen, cl)
	}
	if maxlen == 0 {
		fmt.Println("0 1")
	} else {
		fmt.Printf("%d %d\n", maxlen, lencount[maxlen])
	}
}

var lineScanner *bufio.Scanner
var wordScanner *bufio.Scanner

func init() {
	lineScanner = bufio.NewScanner(os.Stdin)
	wordScanner = bufio.NewScanner(strings.NewReader(""))
	wordScanner.Split(bufio.ScanWords)
}
func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

func nextWord() string {
	for !wordScanner.Scan() {
		if err := wordScanner.Err(); err != nil {
			panic(err)
		}
		line, err := nextLine()
		if err != nil {
			return ""
		}
		wordScanner = bufio.NewScanner(strings.NewReader(line))
		wordScanner.Split(bufio.ScanWords)
	}
	return wordScanner.Text()
}

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

func nextInt64() int64 {
	res, err := strconv.ParseInt(nextWord(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func nextFloat64() float64 {
	res, err := strconv.ParseFloat(nextWord(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

package main

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

func mx(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}
func main() {
	depth, current, max := 0, 0, 0
	counts := make(map[int]int)
	counts[0] = 1
	for i, x := range []rune(nextWord()) {
		if x == '(' {
			depth++
		} else if x == ')' {
			if depth > 0 {
				depth--
				current++
				if depth == 0 {
					max = mx(max, current)
					if _, ex := counts[current]; ex {
						counts[current]++
					} else {
						counts[current] = 1
					}
					current = 0
				}
			}
		}
		if i % 100 == 0 {
			runtime.GC()
		}
	}
	printf("%d %d\n", max * 2, counts[max])
}

var lineScanner *bufio.Scanner
var wordScanner *bufio.Scanner

func init() {
	lineScanner = bufio.NewScanner(os.Stdin)
	wordScanner = bufio.NewScanner(strings.NewReader(""))
	wordScanner.Split(bufio.ScanWords)
}
func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

func nextWord() string {
	for !wordScanner.Scan() {
		if err := wordScanner.Err(); err != nil {
			panic(err)
		}
		line, err := nextLine()
		if err != nil {
			return ""
		}
		wordScanner = bufio.NewScanner(strings.NewReader(line))
		wordScanner.Split(bufio.ScanWords)
	}
	return wordScanner.Text()
}

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

func nextInt64() int64 {
	res, err := strconv.ParseInt(nextWord(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func nextFloat64() float64 {
	res, err := strconv.ParseFloat(nextWord(), 64)
	if err != nil {
		panic(err)
	}
	return res
}


Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length.Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line.Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left.Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders.

The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 5000, n ≥ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≤ si ≤ m), and one real number xi (0 ≤ xi ≤ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≤ i < n).

Output a single integer — the minimum number of plants to be replanted.

NoteIn the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1.In the second test case, the species are already in the correct order, so no replanting is needed.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF269B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	var n int
	var s string
	Fscan(in, &n, &s)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i], &s)
	}
	dp := []int{}
	for _, v := range a {
		if i := sort.SearchInts(dp, v+1); i < len(dp) {
			dp[i] = v
		} else {
			dp = append(dp, v)
		}
	}
	Fprint(_w, n-len(dp))
}

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


A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You are given an integer $$$n$$$. Your goal is to construct and print exactly $$$n$$$ different regular bracket sequences of length $$$2n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 50$$$).

For each test case, print $$$n$$$ lines, each containing a regular bracket sequence of length exactly $$$2n$$$. All bracket sequences you output for a testcase should be different (though they may repeat in different test cases). If there are multiple answers, print any of them. It can be shown that it's always possible.

package main

import "fmt"

func GenDepth(depth int) []string {
	ret := make([]string, 0, depth)
	for i := 0; i < depth; i++ {
		var s string
		for j := 0; j < depth-i; j++ {
			s += "()"
		}
		for k := 0; k < i; k++ {
			s = "(" + s + ")"
		}
		//fmt.Println(s)
		ret = append(ret, s)
	}
	return ret
}

func main() {
	var t, n int
	var res []string
	fmt.Scanln(&t)
	for i := 0; i < t; i++ {
		fmt.Scanln(&n)
		res = append(res, GenDepth(n)...)
	}
	for _, elem := range res {
		fmt.Println(elem)
	}
}

package main

import (
	"fmt"
	"strings"
)

//A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
//
//You are given an integer 𝑛. Your goal is to construct and print exactly 𝑛 different regular bracket sequences of length 2𝑛.
//
//Input
//The first line contains one integer 𝑡 (1≤𝑡≤50) — the number of test cases.
//
//Each test case consists of one line containing one integer 𝑛 (1≤𝑛≤50).
//
//Output
//For each test case, print 𝑛 lines, each containing a regular bracket sequence of length exactly 2𝑛. All bracket sequences you output for a testcase should be different (though they may repeat in different test cases). If there are multiple answers, print any of them. It can be shown that it's always possible.

func main() {
	var t, n int
	mp := make(map[int][]string)
	for fmt.Scan(&t); t > 0; t-- {
		fmt.Scan(&n)
		if arr, ok := mp[n]; ok {
			for _, v := range arr {
				fmt.Println(v)
			}
		} else {
			ans := generateParenthesis(n)
			mp[n] = ans
			for _, v := range ans {
				fmt.Println(v)
			}
		}
	}
}

func generateParenthesis(n int) []string {
	s := []byte(strings.Repeat("(", n) + strings.Repeat(")", n))
	ans := []string{string(s)}
	for i := 1; i < n; i++ {
		s[i], s[2*n-1-i] = s[2*n-1-i], s[i]
		ans = append(ans, string(s))
		s[i], s[2*n-1-i] = s[2*n-1-i], s[i]
	}
	return ans
}

package main

import "fmt"

// InsertNodeToTree ...
func InsertNodeToTree(L int, H int, R int, T string, N int, j *int) {
	if H == 0 {
		*j = *j + 1
		fmt.Println(T)
		return
	}

	if R > 0 && R-L > 0 && *j < N {
		InsertNodeToTree(L, H-1, R-1, T+")", N, j)
	}

	if L > 0 && *j < N {
		InsertNodeToTree(L-1, H-1, R, T+"(", N, j)
	}
	return
}

func main() {
	var t, n, j int
	fmt.Scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		fmt.Scanf("%d\n", &n)
		j = 0
		InsertNodeToTree(n, 2*n, n, "", n, &j)
	}
}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)

		for j:=n;j>0;j--{
			for k:=1;k<=j;k++{
				fmt.Fprintf(out,"(")
			}
			for k:=1;k<=j;k++{
				fmt.Fprintf(out,")")
			}
			for k:=n;k>j;k--{
				fmt.Fprintf(out,"()")
			}
			fmt.Fprintln(out,)
		}
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		var buf bytes.Buffer
		for i := 0; i < n; i++ {
			buf.WriteString("()")
		}

		s := buf.String()
		fmt.Fprintln(out, s)
		var pos int
		for i := 0; i < n-1; i++ {
			buf.Reset()

			buf.WriteString(s[:pos])
			buf.WriteString("(())")
			buf.WriteString(s[pos+4:])
			fmt.Fprintln(out, buf.String())
			pos += 2
		}
	}
}

package main

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

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

	for test := parseInt(getString(reader)); test > 0; test-- {
		n := parseInt(getString(reader))
		permutations := make([]string, 0, n)
		baseArray := make([]byte, 0, 2*n)
		for i := 0; i < n; i++ {
			baseArray = append(baseArray, byte('('), byte(')'))
		}
		permutations = append(permutations, string(baseArray))
		for i := 1; i < n; i++ {
			baseArray[2*i] = byte(')')
			baseArray[2*i-1] = byte('(')
			permutations = append(permutations, string(baseArray))
		}
		for i := 0; i < n; i++ {
			writer.WriteString(fmt.Sprintln(permutations[i]))
		}
	}
	writer.Flush()
}

func parseInt(str string) int {
	var res int
	size := len(str)
	for i := 0; i < size; i++ {
		digit := int(str[i] - '0')
		for j := (i + 1); j < size; j++ {
			digit = digit<<3 + digit<<1
		}
		res += digit
	}
	return res
}

func getString(in *bufio.Reader) string {
	res, _ := in.ReadString('\n')
	res = strings.ReplaceAll(res, "\n", "")
	res = strings.ReplaceAll(res, "\r", "")
	res = strings.TrimSpace(res)
	return res
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	t, _ := reader.ReadString('\n')
	t = strings.TrimSpace(t)
	total, _ := strconv.Atoi(t)
	open := "("
	close := ")"
	for x := 0; x < total; x++ {
		n, _ := reader.ReadString('\n')
		n = strings.TrimSpace(n)
		nn, _ := strconv.Atoi(n)
		for i := 0; i < nn; i++ {
			for j := 0; j < i+1; j++ {
				fmt.Print(open)
			}
			for j := 0; j < i+1; j++ {
				fmt.Print(close)
			}
			for j := 0; j < nn-(i+1); j++ {
				fmt.Print(open, close)
			}
			fmt.Printf("\n")
		}
	}
}

package main

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

type CF1574A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1574A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1574A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1574A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1574A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1574A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1574A
Date: 6/12/21
User: epradere
URL: https://codeforces.com/problemset/problem/1574/A
Problem: CF1574A
**/
func (in *CF1574A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()

		for i := 0; i < n; i++ {
			str := ""
			cont := 0
			ws := false
			for j := 0; j < 2*n; j++ {
				if cont <= i && !ws {
					str += "("
					cont++
				} else if ws && cont <= 0 {
					if -cont%2 == 0 {
						str += "("
					} else {
						str += ")"
					}
					cont--
				} else {
					ws = true
					str += ")"
					cont--
				}

			}
			fmt.Println(str)

		}
	}
}

func NewCF1574A(r *bufio.Reader) *CF1574A {
	return &CF1574A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1574A(bufio.NewReader(os.Stdin)).Run()
}

package main

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

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

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		for i := n; i >= 1; i-- {
			for j := 0; j < i; j++ {
				fmt.Print("(")
			}
			for j := 0; j < i; j++ {
				fmt.Print(")")
			}
			for j := 0; j < n-i; j++ {
				fmt.Print("()")
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"log"
	"strings"
)

func main() {
	t := readInt();
	for cases := 0; cases < t; cases++ {
		n := readInt();

		init := strings.Repeat("(", n) + strings.Repeat(")", n); // ((()))
		fmt.Println(init);

		current := []rune(init);
		for i := n-1; i >= 1; i-- {
			current[i], current[i + 1] =  current[i + 1], current[i];
			fmt.Println(string(current));
		}
	}
}

func readInt() int {
	var t int;
	_, err := fmt.Scanf("%d\n", &t)
	if err != nil {
		log.Fatal(err);
	}
	return t;
}

package main

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

func RegularBracket() {
	// Codeforces 1574A
	// Construct exactly n different regular bracket sequences of length 2n.

	sc := bufio.NewScanner(os.Stdin)
	nested := func(i int) string {
		result := make([]byte, 2*i)
		for j := 0; j < i; j++ {
			result[j] = '('
			result[i+j] = ')'
		}
		return string(result)
	}
	brackets := make([][]string, 51)
	brackets[1] = []string{"()"}
	for i := 2; i < len(brackets); i++ {
		brackets[i] = make([]string, i)
		brackets[i][0] = nested(i)
		for j := 1; j < len(brackets[i]); j++ {
			brackets[i][j] = brackets[i-1][j-1] + "()"
		}
	}
	for tcs := ScanPosInt(sc); tcs > 0; tcs-- {
		n := ScanPosInt(sc)
		for _, solution := range brackets[n] {
			fmt.Println(solution)
		}
	}
}

func main() {
	RegularBracket()
}

func ScanPosInt(sc *bufio.Scanner) (n int) {
	sc.Scan()
	buf := sc.Bytes()
	for _, v := range buf {
		n = n*10 + int(v-'0')
	}
	return
}

package main

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

func Problem1574A(r io.Reader, w io.Writer) {
	in := bufio.NewReader(r)
	out := bufio.NewWriter(w)
	defer out.Flush()

	t := 0
	fmt.Fscanln(in, &t)

	for tcNo := 1; tcNo <= t; tcNo++ {
		n := 0
		fmt.Fscanln(in, &n)

		result := make([]string, 0)
		for i := 0; i < n; i++ {
			temp := strings.Repeat("()", n-i-1) + strings.Repeat("(", i+1) + strings.Repeat(")", i+1)
			result = append(result, temp)
		}
		fmt.Fprintln(out, strings.Join(result, "\n"))
	}
}

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

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		solve()

	}
}

func solve() {
	var n int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		for j := 0; j <= i; j++ {
			fmt.Printf("(")
		}
		for j := 0; j <= i; j++ {
			fmt.Printf(")")
		}
		for j := i + 1; j < n; j++ {
			fmt.Printf("()")
		}
		fmt.Println()
	}

}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for t > 0 {
		var n int
		fmt.Scan(&n)
		var s string
		for i := 0; i < n; i++ {
			s += "("
		}
		for i := 0; i < n; i++ {
			s += ")"
		}
		r := []rune(s)
		fmt.Println(string(r))
		ant := n
		for i := 0; i < n-1; i++ {
			r[ant-1], r[ant] = r[ant], r[ant-1]
			fmt.Println(string(r))
			ant -= 1
		}
		t -= 1
	}
}

package main

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

func main() {

	r := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(r, &n)

		solve(n)
	}
}

func solve(n int) {
	//2 * n

	for i := n; i >= 1; i-- {

		for j := 0; j < i; j++ {
			fmt.Print("(")
		}

		for j := 0; j < n - i; j++ {
			fmt.Print(")(")
		}

		for j := 0; j < i; j++ {
			fmt.Print(")")
		}

		fmt.Println()
	}
}

package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 1024*1024)

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

	for t := 0; t < T; t++ {
		var n int
		fmt.Fscanf(r, "%d\n", &n)

		var gen func(k int) []string
		gen = func(k int) []string {
			if k == 2 {
				return []string{"()"}
			} else {
				x := gen(k - 2)
				res := []string{}

				for _, v := range x {
					res = append(res, "()"+v)
					res = append(res, "("+v+")")
				}

				if len(res) < n {
					return res
				}

				return res[:n]
			}
		}

		x := gen(n * 2)

		for i := 0; i < n; i++ {
			fmt.Println(x[i])
		}
	}
}

package main

import (
	"fmt"
	"os"
)

func ReadInput() []string {
	var t int
	fmt.Fscan(os.Stdin, &t)
	var res []string = make([]string, 0, t)
	for i := 0; i < t; i++ {
		var l int
		fmt.Fscan(os.Stdin, &l)
		var s string
		fmt.Fscan(os.Stdin, &s)
		res = append(res, s)
	}
	return res
}

func main() {
	Sslice := ReadInput()
	//fmt.Println(Sslice)
	for i := 0; i < len(Sslice); i++ {
		var s string
		OtherRow := Sslice[i]
		for j := 0; j < len(OtherRow); j++ {
			switch OtherRow[j] {
			case 'U':
				s += "D"
			case 'D':
				s += "U"
			default:
				s += string(OtherRow[j])
			}
		}
		fmt.Println(s)
	}
}

package main

import "fmt"

// InsertNodeToTree ...
func InsertNodeToTree(L int, H int, R int, T string, N int, j *int) {
	if H == 0 {
		*j = *j + 1
		fmt.Println(T)
		return
	}

	if R > 0 && R-L > 0 && *j < N {
		InsertNodeToTree(L, H-1, R-1, T+")", N, j)
	}

	if L > 0 && *j < N {
		InsertNodeToTree(L-1, H-1, R, T+"(", N, j)
	}
	return
}

func main() {
	var t, n, j int
	fmt.Scanf("%d", &t)
	for i := 0; i < t; i++ {
		fmt.Scanf("%d", &n)
		j = 0
		InsertNodeToTree(n, 2*n, n, "", n, &j)
	}
}


There are $$$n$$$ lanterns in a row. The lantern $$$i$$$ is placed in position $$$i$$$ and has power equal to $$$p_i$$$.Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the $$$i$$$-th lantern is turned to the left, it illuminates all such lanterns $$$j$$$ that $$$j \in [i - p_i, i - 1]$$$. Similarly, if it is turned to the right, it illuminates all such lanterns $$$j$$$ that $$$j \in [i + 1, i + p_i]$$$.Your goal is to choose a direction for each lantern so each lantern is illuminated by at least one other lantern, or report that it is impossible.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of lanterns. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$0 \le p_i \le n$$$) — the power of the $$$i$$$-th lantern. The sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print the answer as follows: If it is possible to direct all lanterns so that each lantern is illuminated, print YES in the first line and a string of $$$n$$$ characters L and/or R (the $$$i$$$-th character is L if the $$$i$$$-th lantern is turned to the left, otherwise this character is R) in the second line. If there are multiple answers, you may print any of them. If there is no answer, simply print NO for that test case.

package main

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

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

	tc := readNum(reader)

	var buf bytes.Buffer

	for tc > 0 {
		tc--

		n := readNum(reader)
		P := readNNums(reader, n)
		res := solve(n, P)

		if len(res) == 0 {
			buf.WriteString("NO\n")
			continue
		}
		buf.WriteString("YES\n")
		buf.WriteString(res)
		buf.WriteByte('\n')
	}

	fmt.Print(buf.String())
}

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

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

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

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

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

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

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

	return i
}

const INF = 1 << 30

func solve(n int, P []int) string {
	L := make([]int, n)
	R := make([]int, n)

	for i := 0; i < n; i++ {
		L[i] = max(1, i-P[i]+1)
		R[i] = min(n, i+P[i]+1)
	}

	sx := make([]int, 2*n)

	for i := n; i < 2*n; i++ {
		sx[i] = R[i-n]
	}

	for i := n - 1; i > 0; i-- {
		sx[i] = max(sx[i<<1], sx[(i<<1)|1])
	}

	getMax := func(l, r int) int {
		var res int
		l += n
		r += n
		for l < r {
			if l&1 == 1 {
				res = max(res, sx[l])
				l++
			}
			if r&1 == 1 {
				r--
				res = max(res, sx[r])
			}
			l >>= 1
			r >>= 1
		}
		return res
	}

	nn := n + 1
	sn := make([]int, 2*nn)
	for i := 0; i < len(sn); i++ {
		sn[i] = INF
	}

	update := func(p int, v int) {
		p += nn
		sn[p] = min(sn[p], v)
		for p > 1 {
			sn[p>>1] = min(sn[p], sn[p^1])
			p >>= 1
		}
	}

	get := func(l, r int) int {
		res := INF
		l += nn
		r += nn
		for l < r {
			if l&1 == 1 {
				res = min(res, sn[l])
				l++
			}
			if r&1 == 1 {
				r--
				res = min(res, sn[r])
			}
			l >>= 1
			r >>= 1
		}
		return res
	}

	dp := make([]int, n+1)
	par := make([]int, n+1)
	for i := 0; i <= n; i++ {
		dp[i] = -INF
	}
	dp[0] = 0
	par[0] = -1

	update(0, 0)

	for i := 1; i <= n; i++ {
		j := i - 1
		k := L[j] - 1
		// find the min m that dp[m] >= k
		m := get(k, n+1)
		if m < INF {
			nval := max(getMax(m, i-1), i-1)
			if nval > dp[i] {
				dp[i] = nval
				par[i] = m
			}
		}
		if dp[j] >= i && max(dp[j], R[j]) > dp[i] {
			dp[i] = max(dp[j], R[j])
			par[i] = -1
		}
		if dp[j] > dp[i] {
			dp[i] = dp[j]
			par[i] = -1
		}
		update(dp[i], i)
	}

	if dp[n] != n {
		return ""
	}
	res := make([]byte, n)
	cur := n
	for cur > 0 {
		if par[cur] < 0 {
			res[cur-1] = 'R'
			cur--
			continue
		}
		diff := cur - par[cur]
		res[cur-1] = 'L'
		cur--
		for diff > 1 {
			res[cur-1] = 'R'
			cur--
			diff--
		}
	}
	return string(res)
}

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

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