In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.

The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.

NoteIn the first sample, the train can take the route  and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/601/A

package main

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

type Edge struct {
	from int
	to   int
}

type QueueItem struct {
	town int
	d    int
}

func bfs(n int, matrix [][]int, flag int) int {
	queue := []QueueItem{{1, 0}}
	visited := make(map[int]bool)
	visited[1] = true
	for len(queue) > 0 {
		current := queue[0]
		queue = queue[1:]
		if current.town == n {
			return current.d
		}
		for v := 1; v <= n; v++ {
			if !visited[v] && matrix[current.town-1][v-1] == flag {
				visited[v] = true
				queue = append(queue, QueueItem{v, current.d + 1})
			}
		}
	}
	return -1
}

func createMatrix(n int, edges []Edge) [][]int {
	adjMatrix := make([][]int, n)
	for i := 0; i < n; i++ {
		adjMatrix[i] = make([]int, n)
	}
	for _, edge := range edges {
		adjMatrix[edge.to-1][edge.from-1] = 1
		adjMatrix[edge.from-1][edge.to-1] = 1
	}
	return adjMatrix
}

func Solve(n int, edges []Edge) int {
	matrix := createMatrix(n, edges)
	if matrix[0][n-1] == 1 {
		return bfs(n, matrix, 0)
	}
	return bfs(n, matrix, 1)
}

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

	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	edges := make([]Edge, m)
	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d %d\n", &edges[i].from, &edges[i].to)
	}

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


There are n students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the i-th student ai minutes to finish his/her independent piece.If students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum ai in the group minus the minimum ai in the group. Note that a group containing a single student has an imbalance of 0. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most k?Two divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.

The first line contains two space-separated integers n and k (1 ≤ n ≤ 200, 0 ≤ k ≤ 1000) — the number of students and the maximum total imbalance allowed, respectively. The second line contains n space-separated integers ai (1 ≤ ai ≤ 500) — the time it takes the i-th student to complete his/her independent piece of work.

Print a single integer, the number of ways the students can form groups. As the answer may be large, print its value modulo 109 + 7.

NoteIn the first sample, we have three options:   The first and second students form a group, and the third student forms a group. Total imbalance is 2 + 0 = 2.  The first student forms a group, and the second and third students form a group. Total imbalance is 0 + 1 = 1.  All three students form their own groups. Total imbalance is 0. In the third sample, the total imbalance must be 0, so each student must work individually.


Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.

A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.

On a single line print the answer to the problem. If such number does not exist, then you should print -1.

NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.

package main

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

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

func diminish(count []int, k int) bool {
	for d := k; d < 10; d += 3 {
		if count[d] > 0 {
			count[d] -= 1
			return true
		}
	}
	return false
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n := scanInt(scanner)
	count := make([]int, 10)
	sum := 0
	for i := 0; i < n; i++ {
		x := scanInt(scanner)
		count[x] += 1
		sum += x
	}
	if count[0] == 0 {
		writer.WriteString("-1\n")
		return
	}
	if sum%3 == 1 {
		if !diminish(count, 1) {
			if !diminish(count, 2) || !diminish(count, 2) {
				writer.WriteString("0\n")
				return
			}
		}
	} else if sum%3 == 2 {
		if !diminish(count, 2) {
			if !diminish(count, 1) || !diminish(count, 1) {
				writer.WriteString("0\n")
				return
			}
		}
	}
	max := 0
	for d := 0; d < 10; d++ {
		if count[d] > 0 {
			max = d
		}
	}
	if max == 0 {
		writer.WriteString("0\n")
		return
	}
	for d := 9; d >= 0; d-- {
		for i := 0; i < count[d]; i++ {
			writer.WriteString(fmt.Sprintf("%d", d))
		}
	}
	writer.WriteString("\n")
}


You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.

The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.

Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).

package main

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

type point struct {
	x, y int64
}

func counterclockwiseTurn(a, b, c point) bool {
	ab := point{b.x - a.x, b.y - a.y}
	ac := point{c.x - a.x, c.y - a.y}
	return ab.x*ac.y-ab.y*ac.x > 0
}

func convexHull(points []point) []point {
	sort.Slice(points, func(i, j int) bool {
		if points[i].x == points[j].x {
			return points[i].y < points[j].y
		}
		return points[i].x < points[j].x
	})

	var lower []point
	for i := len(points) - 1; i >= 0; i-- {
		for len(lower) >= 2 && counterclockwiseTurn(lower[len(lower)-2], lower[len(lower)-1], points[i]) {
			lower = lower[:len(lower)-1]
		}
		lower = append(lower, points[i])
	}

	var upper []point
	for i := range points {
		for len(upper) >= 2 && counterclockwiseTurn(upper[len(upper)-2], upper[len(upper)-1], points[i]) {
			upper = upper[:len(upper)-1]
		}
		upper = append(upper, points[i])
	}

	return append(lower[:len(lower)-1], upper[:len(upper)-1]...)
}

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

func readPoints() []point {
	var n int
	fmt.Fscan(in, &n)
	a := make([]point, n)
	for i := range a {
		fmt.Fscan(in, &a[i].x, &a[i].y)
	}
	return a
}

func solve() bool {
	a := readPoints()
	b := readPoints()
	hull := convexHull(append(b, a...))
	if len(hull) != len(a) {
		return false
	}
	start := 0
	for start < len(hull) && hull[start] != a[0] {
		start++
	}
	if start == len(hull) {
		return false
	}
	for i := range a {
		if a[i] != hull[(i+start)%len(hull)] {
			return false
		}
	}
	return true
}

func main() {
	if solve() {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


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

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

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

package main

import "fmt"

type Matrix struct {
	x [][]uint64
}

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

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

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

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

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

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


This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each.As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball.The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies?Polycarp can throw his fire ball into an archer if the latter is already killed.

The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has.

In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order.

package main

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

var n, a, b int

var best = 999999
var ans []int

func getCount(health, damage int) int {
	if health%damage == 0 {
		return health / damage
	} else {
		return (health / damage) + 1
	}
}

func dfs(layer int, h []int, solution []int, slen int) {
	if slen >= best {
		return
	}

	if len(h) == 2 {
		ca, cb := getCount(h[0], a), getCount(h[1], b)
		if ca < cb {
			ca = cb
		}
		if slen+ca < best {
			best = slen + ca
			ans = make([]int, best)
			for i := 0; i < slen; i++ {
				ans[i] = solution[i]
			}
			for i := 0; i < ca; i++ {
				ans[slen+i] = layer + 1
			}
		}
		return
	}

	count0 := getCount(h[0], b)
	count1 := getCount(h[1], a)
	count2 := getCount(h[2], b)

	for i := count0; true; i++ {
		h0, h1, h2 := h[0], h[1], h[2]

		h[0] = 0
		if h1 >= a*i {
			h[1] = h1 - a*i
		} else {
			h[1] = 0
		}
		if h2 >= b*i {
			h[2] = h2 - b*i
		} else {
			h[2] = 0
		}
		for j := 0; j < i; j++ {
			solution[slen+j] = layer + 2
		}
		dfs(layer+1, h[1:], solution, slen+i)

		h[0], h[1], h[2] = h0, h1, h2
		if i > count0 && i > count1 && i > count2 {
			break
		}
	}
}

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

	fmt.Fscanf(reader, "%d %d %d\n", &n, &a, &b)
	h := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d ", &h[i])
		h[i]++
	}
	dfs(0, h, make([]int, 128, 128), 0)
	fmt.Printf("%d\n", best)
	for i := 0; i < best; i++ {
		fmt.Printf("%d ", ans[i])
	}
}


There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:   alloc n — to allocate n bytes of the memory and return the allocated block's identifier x;  erase x — to erase the block with the identifier x;  defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.

The first line of the input data contains two positive integers t and m (1 ≤ t ≤ 100;1 ≤ m ≤ 100), where t — the amount of operations given to the memory manager for processing, and m — the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 ≤ n ≤ 100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment.

Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.

6 10
alloc 5
alloc 3
erase 1
alloc 6
defragment
alloc 6

package main

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

type Block struct {
	id        int
	length    int
	nextBlock *Block
}

func printMemory(mem *Block) {
	for p := mem; p != nil; p = p.nextBlock {
		fmt.Printf("id=%d length=%d\n", p.id, p.length)
	}
}

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

	var t, m int
	fmt.Fscanf(reader, "%d %d\n", &t, &m)
	nextId := 1
	memory := &Block{0, m, nil}

	for i := 0; i < t; i++ {
		var op string
		var x int
		fmt.Fscanf(reader, "%s", &op)
		switch op {
		case "alloc":
			fmt.Fscanf(reader, " %d\n", &x)
			flag := false
			for p := memory; p != nil; p = p.nextBlock {
				if p.id == 0 {
					for q := p.nextBlock; q != nil && q.id == 0; q = p.nextBlock {
						p.nextBlock = q.nextBlock
						p.length += q.length
					}
				} else {
					continue
				}
				if p.length == x {
					p.id = nextId
					nextId++
					fmt.Printf("%d\n", p.id)
					flag = true
					break
				} else if p.length > x {
					q := &Block{0, p.length - x, p.nextBlock}
					p.length = x
					p.nextBlock = q
					p.id = nextId
					nextId++
					fmt.Printf("%d\n", p.id)
					flag = true
					break
				}
			}
			if !flag {
				fmt.Printf("NULL\n")
			}
		case "erase":
			fmt.Fscanf(reader, " %d\n", &x)
			flag := false
			for p := memory; p != nil; p = p.nextBlock {
				if p.id == x && p.id != 0 {
					p.id = 0
					flag = true
				}
			}
			if !flag {
				fmt.Printf("ILLEGAL_ERASE_ARGUMENT\n")
			}
		case "defragment":
			fmt.Fscanf(reader, "\n")
			for p := memory; p != nil && p.nextBlock != nil; p = p.nextBlock {
				if p.id != 0 {
					continue
				}
				for q := p.nextBlock; q != nil; q = p.nextBlock {
					if p.id == 0 && q.id == 0 {
						p.length += q.length
						p.nextBlock = q.nextBlock
					} else if p.id == 0 && q.id != 0 {
						p.id, q.id = q.id, p.id
						p.length, q.length = q.length, p.length
						break
					} else {
						break
					}
				}
			}
		}
	}
}

[{'input': '6 10\r\nalloc 5\r\nalloc 3\r\nerase 1\r\nalloc 6\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\n2\r\nNULL\r\n3\r\n']}, {'input': '6 1\r\ndefragment\r\nalloc 10\r\nalloc 1\r\nerase -1\r\nerase 1\r\nerase 1\r\n', 'output': ['NULL\r\n1\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '14 100\r\nalloc 99\r\nalloc 1\r\nalloc 1\r\nerase 2\r\nalloc 1\r\nerase 4\r\nerase 1\r\nalloc 100\r\nalloc 1\r\nalloc 99\r\ndefragment\r\nerase 4\r\nalloc 100\r\nalloc 99\r\n', 'output': ['1\r\n2\r\nNULL\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n4\r\nNULL\r\nNULL\r\nNULL\r\n']}, {'input': '26 25\r\ndefragment\r\nerase 1\r\nerase -1560200883\r\nalloc 44\r\ndefragment\r\nalloc 75\r\nalloc 22\r\ndefragment\r\nerase 4\r\ndefragment\r\nalloc 57\r\nalloc 53\r\nerase 4\r\nerase -1639632026\r\nerase -2121605039\r\nerase 3\r\nalloc 51\r\nalloc 65\r\ndefragment\r\nerase 2\r\nerase 4\r\nalloc 52\r\nerase 3\r\ndefragment\r\nerase -1842529282\r\nerase 3\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n1\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '22 9\r\nerase 1\r\nalloc 6\r\nalloc 65\r\nerase 1\r\nalloc 87\r\nerase -1638927047\r\nalloc 5\r\nerase 2\r\nalloc 70\r\ndefragment\r\nalloc 20\r\nalloc 48\r\nerase -69401977\r\nalloc 20\r\ndefragment\r\nerase 7\r\ndefragment\r\nerase 9\r\nerase 7\r\nerase 4\r\ndefragment\r\nalloc 66\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '12 40\r\nerase 1\r\nalloc 21\r\nalloc 5\r\nalloc 7\r\ndefragment\r\ndefragment\r\nerase 2\r\nalloc 83\r\nerase 4\r\ndefragment\r\nalloc 59\r\ndefragment\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\n2\r\n3\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '38 18\r\nalloc 72\r\nerase 2\r\nalloc 50\r\ndefragment\r\nerase 3\r\ndefragment\r\nalloc 43\r\nalloc 41\r\ndefragment\r\ndefragment\r\nalloc 26\r\nalloc 46\r\nalloc 16\r\nalloc 15\r\ndefragment\r\ndefragment\r\nalloc 95\r\nerase 7\r\nerase 7\r\nerase 5\r\nerase 2\r\nerase 9\r\nerase 7\r\nalloc 43\r\ndefragment\r\nerase 7\r\ndefragment\r\nalloc 48\r\nalloc 77\r\nerase 10\r\nerase 11\r\nalloc 16\r\nalloc 84\r\nerase 1\r\ndefragment\r\nalloc 86\r\ndefragment\r\nerase 13\r\n', 'output': ['NULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nNULL\r\n1\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '37 74\r\nalloc 11\r\ndefragment\r\nerase 1\r\ndefragment\r\nerase 2\r\ndefragment\r\nalloc 90\r\nerase 3\r\nerase 2\r\nerase 3\r\nerase 1\r\nerase 1\r\nalloc 38\r\nalloc 19\r\nerase 1\r\nerase 3\r\ndefragment\r\nalloc 93\r\nerase 5\r\nerase 4\r\nalloc 66\r\nalloc 71\r\nerase 5\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\nerase 7\r\nalloc 47\r\nerase -95616683\r\nerase 2\r\nalloc 28\r\nalloc 32\r\nerase 11\r\nalloc 50\r\ndefragment\r\ndefragment\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n4\r\n5\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '16 49\r\nerase -751005193\r\ndefragment\r\nalloc 37\r\nalloc 82\r\nerase 3\r\nerase 1\r\nalloc 80\r\nalloc 51\r\ndefragment\r\nalloc 74\r\nerase 1\r\nalloc 91\r\ndefragment\r\ndefragment\r\nalloc 98\r\ndefragment\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '42 98\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 5\r\nalloc 66\r\ndefragment\r\nerase 3\r\nalloc 53\r\ndefragment\r\nerase 4\r\nerase 2\r\nalloc 70\r\nerase 3\r\ndefragment\r\ndefragment\r\nerase 2\r\nerase 3\r\nerase -1327931832\r\nalloc 93\r\nalloc 64\r\nerase 7\r\nerase 6\r\nerase 3\r\nalloc 61\r\nalloc 12\r\nalloc 65\r\nerase 2\r\nalloc 46\r\nerase 11\r\nerase 9\r\nerase 9\r\nerase 6\r\nalloc 2\r\nalloc 78\r\ndefragment\r\nerase 13\r\nerase 6\r\nerase 10\r\nalloc 53\r\nalloc 46\r\n', 'output': ['1\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n4\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '19 46\r\nalloc 21\r\nerase 2\r\nerase 1\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nalloc 40\r\nerase 1\r\ndefragment\r\ndefragment\r\nalloc 68\r\nerase -388966015\r\nalloc 85\r\nalloc 53\r\nerase 4\r\ndefragment\r\nalloc 49\r\nalloc 88\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '44 46\r\nalloc 28\r\nalloc 36\r\ndefragment\r\nerase -937404236\r\nalloc 71\r\ndefragment\r\nalloc 81\r\nalloc 51\r\nerase 3\r\ndefragment\r\nalloc 48\r\nerase 1\r\ndefragment\r\nalloc 36\r\ndefragment\r\ndefragment\r\nerase 1\r\ndefragment\r\ndefragment\r\nerase -1173350787\r\nalloc 94\r\nerase 5\r\ndefragment\r\nerase 9\r\nalloc 98\r\nerase 7\r\ndefragment\r\nerase 5\r\nerase 1\r\ndefragment\r\nerase 2\r\ndefragment\r\nerase 4\r\ndefragment\r\nerase 9\r\nalloc 8\r\ndefragment\r\nerase 9\r\ndefragment\r\ndefragment\r\ndefragment\r\nerase 1\r\nalloc 70\r\nerase 9\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '26 25\r\nalloc 25\r\nerase 1\r\nalloc 24\r\nerase 2\r\nalloc 23\r\nerase 3\r\nalloc 24\r\nerase 4\r\nalloc 24\r\nerase 5\r\nalloc 21\r\nerase 6\r\nalloc 24\r\nerase 7\r\nalloc 25\r\nerase 8\r\nalloc 25\r\nerase 9\r\nalloc 24\r\nerase 10\r\nalloc 25\r\nerase 11\r\nalloc 25\r\nerase 12\r\nalloc 25\r\nerase 13\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n']}, {'input': '22 9\r\nalloc 9\r\nerase 1\r\nalloc 9\r\nerase 2\r\nalloc 9\r\nerase 3\r\nalloc 9\r\nerase 4\r\nalloc 9\r\nerase 5\r\nalloc 9\r\nerase 6\r\nalloc 9\r\nerase 7\r\nalloc 9\r\nerase 8\r\nalloc 9\r\nerase 9\r\nalloc 9\r\nerase 10\r\nalloc 9\r\nerase 11\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n']}, {'input': '7 6\r\nalloc 1\r\nalloc 2\r\nalloc 3\r\nerase 1\r\ndefragment\r\nerase 3\r\nalloc 4\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n']}, {'input': '3 1\r\nerase -1\r\nerase 0\r\nerase -2147483648\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '7 100\r\nalloc 100\r\nerase 2147483647\r\nerase 1\r\nalloc 50\r\nalloc 50\r\nerase 3\r\nerase -2147483648\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '12 10\r\nalloc 6\r\nalloc 2\r\nerase 1\r\nalloc 4\r\nalloc 2\r\nerase 3\r\nalloc 2\r\nalloc 3\r\nalloc 1\r\nalloc 1\r\nalloc 1\r\nalloc 1\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\nNULL\r\n6\r\n7\r\n8\r\n9\r\n']}, {'input': '8 50\r\nalloc 51\r\ndefragment\r\nalloc 100\r\ndefragment\r\nerase 1\r\nalloc 50\r\ndefragment\r\nalloc 50\r\n', 'output': ['NULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\n']}, {'input': '10 10\r\nalloc 10\r\nerase -1\r\nerase 1\r\nalloc 5\r\nerase -1\r\nalloc 5\r\nerase 0\r\nalloc 5\r\nerase 0\r\nalloc 5\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '16 10\r\nalloc 10\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 10\r\nerase 1\r\nerase 2\r\nalloc 6\r\ndefragment\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nerase 3\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nNULL\r\n']}, {'input': '16 10\r\nalloc 10\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 10\r\nerase 1\r\nerase 2\r\nalloc 6\r\ndefragment\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nerase 2\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\n4\r\n']}]


There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

The first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

package main

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

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

	n, k := readTwoNums(reader)

	H := readNNums(reader, n)

	a, b := solve(n, k, H)
	var buf bytes.Buffer

	buf.WriteString(fmt.Sprintf("%d %d\n", a, len(b)))

	for i := 0; i < len(b); i++ {
		buf.WriteString(fmt.Sprintf("%d %d\n", b[i][0], b[i][1]))
	}

	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') {
			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 N_INF = -(10000000)

func solve(n, k int, H []int) (a int, b [][]int) {
	get := func(l, r int, arr []int) int {
		res := N_INF

		l += n
		r += n

		for l < r {
			if l&1 == 1 {
				res = max(res, arr[l])
				l++
			}
			if r&1 == 1 {
				r--
				res = max(res, arr[r])
			}
			l >>= 1
			r >>= 1
		}
		return res
	}

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

	for i := n; i < 2*n; i++ {
		x[i] = H[i-n]
		y[i] = -H[i-n]
	}

	for i := n - 1; i > 0; i-- {
		x[i] = max(x[2*i], x[2*i+1])
		y[i] = max(y[2*i], y[2*i+1])
	}

	getDiff := func(i, j int) int {
		xx := get(i, j, x)
		yy := -get(i, j, y)
		return xx - yy
	}

	check := func(l int) bool {
		for i := 0; i+l <= n; i++ {
			d := getDiff(i, i+l)
			if d <= k {
				return true
			}
		}
		return false
	}

	var left, right = 0, n + 1

	for left < right {
		mid := (left + right) / 2
		if !check(mid) {
			right = mid
		} else {
			left = mid + 1
		}
	}
	a = right - 1

	for i := 0; i+a <= n; i++ {
		d := getDiff(i, i+a)
		if d <= k {
			b = append(b, []int{i + 1, i + a})
		}
	}
	return
}

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


Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:#define macro_name macro_valueAfter the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.One of the main problems arising while using macros — the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.Let's consider the following example. Say, we declared such a #define construction:#define sum x + yand further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise — suspicious.Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".

The first line contains the only number n (0 ≤ n ≤ 100) — the amount of #define constructions in the given program. Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax: #define name expression where   name — the macro name,  expression — the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.  All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction. Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions. The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol. The length of any line from the input file does not exceed 100 characters.

Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".

4
#define sum  x + y
#define mul  a * b
#define div  a / b
#define expr sum + mul * div * mul
expr

3
#define SumSafe   (a+b)
#define DivUnsafe  a/b
#define DenominatorUnsafe  a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)

package main

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

var macro2Op map[string]string

func check(num0, num1, op string) error {
	op0, ok0 := macro2Op[num0]
	op1, ok1 := macro2Op[num1]

	if ok0 {
		if op0 == "fail" {
			return errors.New("fail")
		}
		if (op == "*" || op == "/") && (op0 == "+" || op0 == "-") {
			return errors.New("fail")
		}
	}

	if ok1 {
		if op1 == "fail" {
			return errors.New("fail")
		}
		if (op == "-" && (op1 == "-" || op1 == "+")) || (op == "/" && (op1 == "/" || op1 == "*")) ||
			((op == "*" || op == "/") && (op1 == "+" || op1 == "-")) {
			return errors.New("fail")
		}
	}
	return nil
}

func getOp(tokens []string) string {

	if len(tokens) == 1 {
		rank, ok := macro2Op[tokens[0]]
		if ok {
			return rank
		} else {
			return "()"
		}
	}

	op := make([]string, 10000, 10000)
	num := make([]string, 10000, 10000)
	opPointer, numPointer := 0, 0
	ret := ""

	for i := 0; i < len(tokens); i++ {
		if tokens[i] == "(" {
			op[opPointer] = "("
			opPointer++
		} else if tokens[i] == "+" || tokens[i] == "-" {
			for opPointer != 0 {
				if op[opPointer-1] == "*" || op[opPointer-1] == "/" || op[opPointer-1] == "+" || op[opPointer-1] == "-" {
					err := check(num[numPointer-2], num[numPointer-1], op[opPointer-1])
					if err != nil {
						return "fail"
					}
					ret = op[opPointer-1]
					numPointer--
					num[numPointer-1] = "1"
					opPointer--
				} else {
					break
				}
			}
			op[opPointer] = tokens[i]
			opPointer++
		} else if tokens[i] == "*" || tokens[i] == "/" {
			for opPointer != 0 {
				if op[opPointer-1] == "*" || op[opPointer-1] == "/" {
					err := check(num[numPointer-2], num[numPointer-1], op[opPointer-1])
					if err != nil {
						return "fail"
					}
					ret = op[opPointer-1]
					numPointer--
					num[numPointer-1] = "1"
					opPointer--
				} else {
					break
				}
			}
			op[opPointer] = tokens[i]
			opPointer++
		} else if tokens[i] == ")" {
			for opPointer != 0 {
				if op[opPointer-1] == "*" || op[opPointer-1] == "/" || op[opPointer-1] == "+" || op[opPointer-1] == "-" {
					err := check(num[numPointer-2], num[numPointer-1], op[opPointer-1])
					if err != nil {
						return "fail"
					}
					numPointer--
					num[numPointer-1] = "1"
					opPointer--
				} else if op[opPointer-1] == "(" {
					opPointer--
					break
				}
			}
			rank, ok := macro2Op[num[numPointer-1]]
			if ok && rank == "fail" {
				return rank
			} else {
				num[numPointer-1] = "1"
			}
			ret = "()"
		} else {
			num[numPointer] = tokens[i]
			numPointer++
		}
	}
	for opPointer != 0 {
		err := check(num[numPointer-2], num[numPointer-1], op[opPointer-1])
		if err != nil {
			return "fail"
		}
		ret = op[opPointer-1]
		numPointer--
		num[numPointer-1] = "1"
		opPointer--
	}

	return ret
}

func tokenize(s string) []string {
	tokens := make([]string, 0, 200)
	b := []byte(s)
	token := make([]byte, 0, 100)
	for i := 0; i < len(b); i++ {
		if b[i] == '(' || b[i] == ')' ||
			b[i] == '+' || b[i] == '-' || b[i] == '*' || b[i] == '/' ||
			b[i] == '\r' || b[i] == '\n' || b[i] == ' ' {
			if len(token) != 0 {
				tokens = append(tokens, string(token))
				token = make([]byte, 0, 100)
			}
			if b[i] != ' ' && b[i] != '\r' && b[i] != '\n' {
				tokens = append(tokens, string([]byte{b[i]}))
			}
		} else {
			token = append(token, b[i])
		}
	}
	return tokens
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	macro2Op = map[string]string{}

	for i := 0; i < n; i++ {
		var macro string
		s, _ := reader.ReadString('\n')

		s = strings.TrimLeft(s, " #")
		s = strings.TrimPrefix(s, "define")
		s = strings.TrimLeft(s, " ")
		fmt.Sscanf(s, "%s", &macro)
		s = strings.TrimPrefix(s, macro)
		tokens := tokenize(s)
		macro2Op[macro] = getOp(tokens)
	}

	testexpr, _ := ioutil.ReadAll(reader)
	expr := string(testexpr) + "\n"
	ts := tokenize(expr)
	rank := getOp(ts)
	if rank == "fail" {
		fmt.Printf("Suspicious")
	} else {
		fmt.Printf("OK")
	}
}

[{'input': '1\r\n#define sum x + y\r\n1 * sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum  (x + y)\r\nsum - sum\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define sum  x + y\r\n#define mul  a * b\r\n#define div  a / b\r\n#define expr sum + mul * div * mul\r\nexpr\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define SumSafe   (a+b)\r\n#define DivUnsafe  a/b\r\n#define DenominatorUnsafe  a*b\r\n((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)\r\n', 'output': ['Suspicious\r\n']}, {'input': '0\r\naa + b - c * (ddd * eee / fff * a / b * c + d - b + c - (a + b)) - d\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n#define a b\r\n#define c d\r\na + b + c + d + 1234567 -10*(2-2+1000*1000*1000*1000*1000)\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n  #  define  macros    (  x  +  y  ) \r\n # define  Macros (x+y)\r\nmacros/Macros\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n#define A v\r\n#define a v/v/v\r\nv/A\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n#define A v\r\n#define a v/v/v\r\nv/a\r\n', 'output': ['Suspicious\r\n']}, {'input': '2\r\n#define A v\r\n#define a v/v/v\r\nv/(a)\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define a x*y\r\nc/a\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define a b*c\r\na/a*a\r\n', 'output': ['Suspicious\r\n']}, {'input': '3\r\n#define mul  x*y\r\n#define bad  x/mul\r\n#define good x/(mul)\r\ngood\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define mult   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nsum+difference+(sum)*(difference)-mult+mult*division+division*mult+division/(mult+sum-(difference))\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(difference/division)+sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(difference)*sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(sum)/multiplication\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nsum/(multiplication)\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n#define res (0-difference)\r\nsum+res*multiplication\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\ndivision/(multiplication/(division)/DIVISION/(sum-division-multiplication-(difference)))\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define sum  x + y\r\n#define SomeBad  (2 * sum)\r\n#define SomePossiblyGood  0 * SomeBad + (x + x - 2*x) * SomeBad\r\nSomePossiblyGood\r\n', 'output': ['Suspicious\r\n']}, {'input': '2\r\n#define a  0\r\n#define b  (a-a)*(x/x-1)\r\nb-b/b*b\r\n', 'output': ['Suspicious\r\n']}, {'input': '2\r\n#define fkdsjfslkjfsdk x/0\r\n#define fkdsjfslkjfsdksdds 0/(0-0)\r\nfkdsjfslkjfsdk + fkdsjfslkjfsdks + fkdsjfslkjfsdkssds\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define null x/0\r\n#define some x/x\r\n#define bad 1/x\r\nbad/0+0/bad+0/0*bad\r\n', 'output': ['Suspicious\r\n']}, {'input': '3\r\n#define MWjGY x+x*53 *x\r\n#define ovqZ 2/926+x/A\r\n#define uU 55-qRj*A*2\r\nx*A/x-A\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define zz 5+7/x*x*9\r\n#define mlTL 6+x/7+x/x\r\n#define DUO 7*7-x+zz\r\n#define IH 6*4-x+x\r\n67/(5)-IH\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define Oc 9/51+65+vN\r\n#define gga 53/ 94/x/x\r\n#define ArB x/x/9-77-8\r\n#define j 76-6/93+vN\r\n#define cALNN Oc+60499\r\n8*6-66/x*x\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define fSdvwOj (W)*W+73\r\n#define NAZjc 7695*55-x\r\n#define AHGGglVwch (6-a-W)\r\n((5))+W+W\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define m bJJD +x \r\n#define yYkQNzjR (x*19)-892\r\n#define MNvfxqfbq (x-6*x/8)\r\n#define nJZdvO 8/4 *m/m\r\n 9+m/x+x\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define Sl x*7-(x)/O\r\n#define srAOHccTln 3+x*2*O\r\n#define OFAZk 239751817\r\n#define JYWrOEgazV (x-O/4)-x\r\n#define XsOZvalgOh 89905879/7\r\nx/Sl-(Sl)\r\n', 'output': ['Suspicious\r\n']}, {'input': '3\r\n#define uYdw ((9-x-3) )\r\n#define fy (((x+21)))\r\n#define nY ((2+x)-46)\r\n141141432\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define GCvqH (58 )-(x)\r\n#define g ((x/x+x))\r\n#define spst hQTJ\r\n#define i GCvqH\r\n(((x+6)))\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define rg (67)+((x))\r\n#define ya x-(6/x)*rg\r\n#define anTxe 10*ya*(x)\r\n#define xcmo ((x)*(vT))\r\n#define eg ((vT)) -ya\r\n((x*(Ii)))\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define T ((b/1 +1))\r\n#define pm (s)-43-(s)\r\n#define jkNBpvDZl ((x ))/65\r\n(((58*7)))\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define cJitUt 21/(4)+4+4\r\n#define zHwBOLIvF 4*((41/x))\r\n#define GbtYVo (E)+(x+3)\r\n#define zTcZBaby (58)+x-x+x\r\n(E+E)/8 *4\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define mBURKdeKvy 266693986\r\n#define nWi ( ((x))-4)\r\n#define iYreeOt ((7/x+42))\r\n#define laLzP ((aB/35)) \r\n#define dXjRJ (((B*hX)))\r\n(1*2+(67))\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define UVMQLGvEqOxaAgRkvJH tBd\r\n#define QoAsBMaUcJzXai x/x-hm/83+8*8/5/hm /x/hm\r\n#define QtxtzEHCmidm 75 +491928441\r\n((x)/VUpYoEdDUtLFanGyqfQR  )\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define efemx 2/1*3*69+81+10/690445104\r\n#define AyjrEzAjMKZpRPfCOaO 21*9+( j*40+3*4)*ND+w-j*j+x*55\r\n#define YkJkHcNhXcci 85*3215/40/365819568\r\n#define MUzvOZSXJujI 9-4/j*j-7-w*23*5+j+9-9*ND*2/37\r\nND/j*28 -1* ND+22889023/j/j/j\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define QNUkjqPcGWF 6*4/908975666-7/10-x*7\r\n#define xqwhNWiiMaZOcmgiXYY 3936*(e*5*H+2)-TsA+(e)/1-25\r\n#define tRsSqfqJt ((uT*82/e)+e/(23+(45)-9)+(50))\r\n#define DtIOWRkYe (8*3/9)*e*x *60041512*2-(e)\r\n#define qgPgxja (4/x+e/uT*16358009- 6/13*5)\r\ne+x*e/84/x+uT*H\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define lTCUUO JQmj\r\n#define oUeQMB (12*x+x+x)-75-(79/1)-(7)*1/mr\r\n#define LAQu xwvBtky\r\n8654 *1*5-mr-3*J/oUeQMB/x/6/9\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define VLuQIO 1-x/33+ Fk+wS/35-wS-(x*iz )\r\n#define BCIsIR 5*(wS)/x/iz/1+x-x-4-x/68/x/8*x\r\n#define QPUpmTiB 21-x/895912506+2\r\n#define wcZLUIqJS 7/65-x*61-(24+iz)+x+315670+x/x\r\nBCIsIR/VLuQIO\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define FDmMYOENCOKmYwYlOl 6-(L)/((((ud/x))/ud-26*8-5))\r\n#define QkopKBjKdJxhc (6)*4/7-L/781844832  \r\n#define UjgTieUBXTSTbiLFAhkV 3*1*(52)/6-6*65/x+((L-56))+x+x\r\n#define yWVYDuqliezpKLwnI 8/4+1+88+97946+(1)-((68))-L/L\r\n#define AvvED 719901121+95/2/78/1-10+37\r\n(1*x+ 528176190+17/ud)\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define e x *R/5+(x)+4/18/x*R/x-8+1+R\r\n#define GgGqGYjXoJjIezAVu (( 491563947*R))*9-e-3/4\r\n#define XgznGUWMxQwh (8/R+4*(e)+10/4*x+24*R+21)-224\r\n (82493582)\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define MrKSTrKhPLeJqOcEPvv (x+x/x)/Qdf-x-x-(2/23)+9442-x\r\n#define zPHUgmIYE 10- 7*x/x+VwRUuIRezDR*80\r\n#define OsfThxasHeFZCEZTfD 271456028-(x*x)-8+2*x*x*x+(x)\r\n#define zVYasB x/x -x-(51)-x*x*((x))  /x \r\n(x/64-x*( (5+x+x)-(37)/3*22))\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define WREol (fcdGZaLzhiFpVQmhHO)\r\n#define lDTNxcMqPPP 3+(57)/x/91540-x*71-x*6-((1))\r\n#define afFJVBkr ((12*x-8+9 *lDlx+7+lDlx))\r\n#define mYEizEWrNtRSQNCcDQrn 732480960+9+x-78-x/1+12*x\r\n#define IZTmjheAahbNSNFa ((x-x*7+407643063 ))\r\nXQvMxLNpQnhpimNhAkfX\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define Mc x+x*55231- x/x/x+35/x*(5*(x)) -5*x*(1-2-(29/1))\r\n#define afSVLCdjvylSu bgqv/6+4*x*((Mc/1318/x-8-4)-Mc/Mc/(9))\r\n#define ZOSV (1+2/x+6* 174806683)-x/x*Mc+52*x-x\r\nbgqv-x-6*x/72/(x )/afSVLCdjvylSu\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define RJIiiGQqn dmpWFcrqQeM+V-o* 55/9*o-o/V*V*o\r\n#define ElDZlrtzDkeKgsX 498718105* 3/(y)/(4)-(5*x)*1\r\n#define qwKl jHqPHX\r\n#define qXzAZkCuchBYR  (qy*qwKl-6+5*1+2)-7-3+(38)-o*4/4-1-V*x/6+1*x/o\r\no*((V))-o+2+((((2*V)/V-o*V/4)))/o*33+y/7  -x+x \r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define WTovyGexUNjGMRJv (MQG*18-6)/x/x*x/x-x*akNyw*x+x-x/2/x*20\r\n#define hpextyhVCa 70*x/67-x*87931-(497612505-7*x-MQG)-x\r\n#define MRkKnCXFt x-5-21962-x/sOmThNSS/x/6-4+(65+57+x+x+7-7+x/x)\r\n#define ajsczBLLklBSqqh nGj-38*9 *x/47/8*5/5-72/x*x-x*x*31  /7-44-3+64\r\n#define jgqfv WTovyGexUNjGMRJv\r\n  4+338/x*x+13 -795*3-74*2/4+563-x/76401438/83025\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define G u+13-35348/2-(u/u)-u/u*u*(OC)-OC -u-u/u*u/9 \r\n#define RNRQ G*G*u+G/755750/G/G +((u-6*G+6)*2)- 5*96+5/u*275-u\r\n#define Zg 94363/u*u-41+Gm*G-81/5-1-G*G*x-(5517*5/4)*21 +75\r\n406690013/WM*G+(u+u)*Zg+2\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define RMWAZhIp x*x+12+94*12*5*1-x-141915293\r\n#define EeguG 9-55+x/29+x+x/E*8*81/x-x*75-4*17-81/x/6+619978*x*x\r\n#define HvUYEvQTyYmBGvqHSb 454574730/644135926*x/23+E-sy/14\r\n#define BqMGcT x/(43)+819897061-x*(7/x)-(x)+sy-E-x*79-E+(x)/6/63\r\n76+3/x/8*x+E-76+sy-sy+9*6/66/sy-77+x-x*sy+E/50/64\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define cbt ((((d))+9-3+ (d)/d/6*SDDNqj*50/d+d-m+8/d/1)) \r\n#define gLrUE 18+ 70*d/3-d*d-d/35 +33-5/9+d-d*387+d-1\r\n#define AvjmK 9-d-8+(d+m+5/2/x*d+1)/x/d-5-2*(m)+d+17/d+ 4/52/8\r\n#define SjrJ 90/7/5/d+ 254877982+(m) *x-19\r\n#define PlykoqfDbwxR  540304590 +d*x/11-(m+d-d-4)*(d-3-1)/d\r\nd-2+1+46-29620+9-(9*3 /d)*6*m/d+9+(1670)/cbt/d+d\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define BuAiJLgAlkj x-3+419032556/409023036-(17*84)+x+8+A\r\n#define wU 516506880\r\n#define HeyDGlnaGxBaHjzelvF iRSPqHfgHw/4-(99)*(I)+A+I-9*46*x\r\nI/CRklg-HeyDGlnaGxBaHjzelvF/3+5 \r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define SOlTohcPGckDyF ((D)/G-83+KHGSuJFLHqD/5)\r\n#define KEUXeOYpg 9+x-8-8/x/9-65-6+4+55*x-58/x+84+D*2-7+D/x-x*G/4-2\r\n#define YZl (1/67*x*6/2*G)-D/1595107*D+6/x*1+D+3/9/x/26-6+9 \r\n#define gCatFsZn uBBqilYclMhpVfKKTkGK\r\n(28682537+ YZl*(4*52)  )*x/8- gCatFsZn*x/54/7\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define iiXEqDYeyVmIYsOaO fj/x-9-6/x*x+ 1/ 7*2-x -x+9+235*23*Ww+x-2*K+2-x/70\r\n#define XVgLzhoTUxoBr ( x+x/x/x*6-x)* x+K/24206-2 /5/8-x-7/Ww/K-x+6 \r\n#define QdfRBaJk 470551685-(  54-x)-30\r\n#define gEJcAGnF x+x-x+(x/x+9)/x-41-1/fj/1157561+x/x -x/26/x+K*x\r\n#define lO 7-1*(x*58 )-K*fj  /722113691/x/K+2\r\n2+4*85/86/x*27 /49252-x*x/6-83-7/x+x+K-lO+8-K-x\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nr-sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x+y\r\nr*sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x-y\r\nr-sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nr*sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x*y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nr-sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nr*sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x/y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nr-sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nr*sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum*r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum/r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum*r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum/r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum*r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum/r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum*r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum/r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define x 3/2\r\n2*x\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n   #    define     sum     1000000000   +   1000000000       +     1000000000      \r\n    #    define      a    b     +      45    *   sum    \r\n       a       \r\n', 'output': ['Suspicious\r\n']}]


There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.  King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.

The first line contains number n, which is the number of knights at the round table (3 ≤ n ≤ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.

Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".

package main

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	mood := make([]int, n)
	for i := 0;i < n - 1;i ++ {
		fmt.Fscanf(reader, "%d ", &mood[i])
	}
	fmt.Fscanf(reader, "%d\n", &mood[n - 1])
	for i := 1;2 * i < n;i ++ {
		if n % i != 0 {
			continue
		}
		for j := 0;j < i;j ++ {
			ok := 1
			for k := j;k < n; k += i {
				ok *= mood[k]
			}
			if ok == 1 {
				fmt.Printf("YES")
				return
			}
		}
	}
	fmt.Printf("NO")
	return
}


Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes P1 watt per minute. T1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to P2 watt per minute. Finally, after T2 minutes from the start of the screensaver, laptop switches to the "sleep" mode and consumes P3 watt per minute. If Tom moves the mouse or touches the keyboard when the laptop is in the second or in the third mode, it switches to the first (normal) mode. Tom's work with the laptop can be divided into n time periods [l1,r1],[l2,r2],...,[ln,rn]. During each interval Tom continuously moves the mouse and presses buttons on the keyboard. Between the periods Tom stays away from the laptop. Find out the total amount of power consumed by the laptop during the period [l1,rn].

The first line contains 6 integer numbers n, P1, P2, P3, T1, T2 (1≤n≤100,0≤P1,P2,P3≤100,1≤T1,T2≤60). The following n lines contain description of Tom's work. Each i-th of these lines contains two space-separated integers li and ri (0≤li<ri≤1440, ri<li+1 for i<n), which stand for the start and the end of the i-th period of work.

let data = '';

const solve = () => {
    /**
     * Three rings to the elven-kings under the sky,
     * Seven for the dwarf-lords in their halls of stone,
     * Nine for mortal men doomed to die...
     */
    let mithrandir = 0;

    const [
        _,
        activeStateCost,
        screensaverCost,
        sleepStateCost,
        fromActiveToScreensaverDuration,
        fromScreensaverToSleepStateDuration,
        ...periods
    ] = data
        .trim()
        .split(/\n| /)
        .map(el => +el);

    const inactivePeriods = [];
    const activePeriods = [];

    activePeriods.push(periods[1] - periods[0]);

    for(let i=2; i<periods.length; i+=2) {
        activePeriods.push(periods[i+1] - periods[i]);
        inactivePeriods.push(periods[i] - periods[i-1]);
    }

    mithrandir += activePeriods.reduce((sum, val) => sum += val * activeStateCost, 0);
    mithrandir += inactivePeriods.reduce((holder, val) => {
        let sum = 0;
        if(val - fromActiveToScreensaverDuration > 0) {
            sum += fromActiveToScreensaverDuration * activeStateCost;
            val -= fromActiveToScreensaverDuration;

            if(val - fromScreensaverToSleepStateDuration > 0) {
                sum += fromScreensaverToSleepStateDuration * screensaverCost;
                val -= fromScreensaverToSleepStateDuration;

                if(val > 0) {
                    sum += val * sleepStateCost;
                }
            } else {
                sum += val * screensaverCost;
            }
        } else {
            sum += val * activeStateCost;
        }

        return sum + holder;
    }, 0);

    console.log(mithrandir);
}

process.stdin.on('data', c => data += c);
process.stdin.on('end', solve);


Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?

The first line contains the only integer n (1≤n≤100) — the number of cookie bags Anna and Maria have. The second line contains n integers ai (1≤ai≤100) — the number of cookies in the i-th bag.

Print in the only line the only number — the sought number of ways. If there are no such ways print 0.

In the first sample Olga should take the only bag so that the twins ended up with the even number of cookies.
In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies — 5+3=8 ways in total.
In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2*9+99=117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies.

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    var k = lines[1].split(' ');
    var even = 0;
    var odd = 0;
    for(var j = 0; j < n; j++){
        if(k[j] % 2 === 0){
            even++;
        }else{
            odd++;
        }
    }
    if(odd % 2 == 1){
        console.log(odd);
    }else{
        console.log(even);
    }
});


Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.

The first line contains two integers n and m — the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b — the numbers of students tied by the i-th lace (1≤a,b≤n,a≠b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.

Print the single number — the number of groups of students that will be kicked out from the club.

In the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});

process.stdin.on("end", (_) => {
  inputString = inputString
    .trim()
    .split("\n")
    .map((string) => {
      return string.trim();
    });

  main();
});

function readline() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {

       let [n,m] = readline().split(" ").map(x=>+x);

         let matrix = [];
  for (let i = 0; i < m; i++) {
    matrix.push(
      readline()
        .split(" ")
        .map((x) => x)
    );
  }

       studentsAndShoelaces(n,m,matrix);

}
 let graph = {};
let counter = 0;

function studentsAndShoelaces(n, m, studentsConnections) {
  graph = {};
  counter = 0;

  for (let i = 0; i < m; i++) {
    const [a, b] = studentsConnections[i];

    graph[a] ? graph[a].push(b) : (graph[a] = [b]);

    graph[b] ? graph[b].push(a) : (graph[b] = [a]);
  }

  removeSingles();

  console.log(counter);
}

function removeSingles() {
  let toRemoveNodes = [];
  for (const node in graph) {
    if (graph[node].length === 1) {
      toRemoveNodes.push(node);

      delete graph[node];
    }
  }

  if (toRemoveNodes.length) {
    for (const node in graph) {
      graph[node] = graph[node].filter((x) => !toRemoveNodes.includes(x));
    }
    counter++;

    toRemoveNodes = [];

    removeSingles();
  } else {
    return;
  }
}


Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.Now Petya wants to know for each friend i the number of a friend who has given him a gift.

The first line contains one integer n (1≤n≤100) — the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi — the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.

Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main (){
  let n = readline()
  let friends = readline().split(" ").map(i => parseInt(i))
  let answer = new Array(n)
  for (let i = 0; i < n; i++) {
    answer[friends[i]-1] = i+1
  }
  answer = answer.join(" ")
  print(answer)
}


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1,a2,...,an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1≤n≤5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1≤ai≤5000,1≤i≤n).

Print the only number — the minimum number of changes needed to get the permutation.

The first sample contains the permutation, which is why no replacements are required.
In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.
In the third sample we can replace the second element with number 4 and the fourth element with number 2.

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\nâå¥å âåºå');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException âThere is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var N = nextInt();
	var list = nextIntArray(N);
	var count = new Array(5001).fill(0);
	for(var i = 0; i < N; i++){
		count[list[i]]++;
	}
	var output = 0;
	for(var i = 1; i <= N; i++){
		if(count[i] == 0){
			output++;
		}
	}
	myout(output);
}


A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

The first input line contains the only integer n (2≤n≤100) which represents the number of soldiers in the line. The second line contains integers a1,a2,...,an (1≤ai≤100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1,a2,...,an are not necessarily different.

Print the only integer — the minimum number of seconds the colonel will need to form a line-up the general will like.

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main (){
  let n = parseInt(readline())
  let soldiers = readline().split(" ").map(height => parseInt(height))

  let maxIndex = 0;
  let minIndex = 0;
  let maxHeight = soldiers[0];
  let minHeight = soldiers[0];

  for (let i = 1; i < n; i++) {
    if (soldiers[i] > maxHeight) {
      maxHeight = soldiers[i];
      maxIndex = i;
    }

    if (soldiers[i] <= minHeight) {
      minHeight = soldiers[i];
      minIndex = i;
    }
  }

  let res = 0

  if (maxIndex < minIndex) res = (n-1) - minIndex + maxIndex
  if (maxIndex > minIndex) res = (n-1) - minIndex + maxIndex - 1

  print(res)

}


Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.Your task is to find the number of successful students in the group.

The first input line contains two integers n and m (1≤n,m≤100) — the number of students and the number of subjects, correspondingly. Next n lines each containing m characters describe the gradebook. Each character in the gradebook is a number from 1 to 9. Note that the marks in a rows are not sepatated by spaces.

Print the single number — the number of successful students in the given group.

In the first sample test the student number 1 is the best at subjects 1 and 3, student 2 is the best at subjects 1 and 2, but student 3 isn't the best at any subject.
In the second sample test each student is the best at at least one subject.

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
const students = [];
let n, m;

rl.on('line', (d) => {
  if (c === 0) {
    [n, m] = d.split(' ').map(Number);
    c++;
    return;
  }

  const marks = d;
  students.push(marks);
  c++;
});

rl.on('close', () => {
  const bests = new Set();
  for (let i = 0; i < students[0].length; i++) {
    let best = 0;
    for (let j = 0; j < students.length; j++) {
      if (students[j][i] > best) {
        best = students[j][i];
      }
    }

    for (let z = 0; z < students.length; z++) {
      if (students[z][i] === best) {
        bests.add(z);
      }
    }
  }

  console.log(bests.size);
});


Sherlock Holmes and Dr. Watson played some game on a checkered board n×n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8+3+6+7=24, sum of its row numbers equals 9+5+3+2=19, and 24>19.

The first line contains an integer n (1≤n≤30). Each of the following n lines contain n space-separated integers. The j-th number on the i-th line represents the number on the square that belongs to the j-th column and the i-th row on the board. All number on the board are integers from 1 to 100.

Print the single number — the number of the winning squares.

In the first example two upper squares are winning.
In the third example three left squares in the both middle rows are winning:
5 7 8 4
9 5 3 2
1 6 6 4
9 5 7 3

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\nâå¥å âåºå');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException âThere is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var N = nextInt();
	var list = new Array(N);
	for(var i = 0; i < N; i++){
		list[i] = new Array(N);
		for(var j = 0; j < N; j++){
			var v = nextInt();
			list[i][j] = {
				v : v,
				y : v,
				x : v
			};
		}
	}
	for(var i = 0; i < N; i++){
		for(var j = 1; j < N; j++){
			list[i][j].x += list[i][j - 1].x;
		}
		for(var j = N - 2; j >= 0; j--){
			list[i][j].x = list[i][j + 1].x;
		}
	}
	for(var i = 1; i < N; i++){
		for(var j = 0; j < N; j++){
			list[i][j].y += list[i - 1][j].y;
		}
	}
	for(var i = N - 2; i >= 0; i--){
		for(var j = 0; j < N; j++){
			list[i][j].y = list[i + 1][j].y;
		}
	}
	var count = 0;
	for(var i = 0; i < N; i++){
		for(var j = 0; j < N; j++){
			if(list[i][j].y > list[i][j].x){
				count++;
			}
		}
	}

	myout(count);
}


After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1≤si≤4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?

The first line contains integer n (1≤n≤10^5) — the number of groups of schoolchildren. The second line contains a sequence of integers s1,s2,...,sn (1≤si≤4). The integers are separated by a space, si is the number of children in the i-th group.

Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.

In the first test we can sort the children into four cars like this:
  the third group (consisting of four children),  the fourth group (consisting of three children),  the fifth group (consisting of three children),  the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars.

let input = "";
process.stdin.on("data", (data) => (input += data));
process.stdin.on("end", () => {
  let lines = input.split("\n");
  let n = lines.shift();
  let count = [0, 0, 0, 0, 0];
  lines
    .shift()
    .trim()
    .split(" ")
    .forEach((x) => count[x]++);
  let res = count[4];
  res += Math.floor(count[2] / 2);
  count[2] = count[2] % 2;
  let min13 = Math.min(count[1], count[3]);
  res += min13;
  count[1] -= min13;
  count[3] -= min13;
  if (count[2]) {
    count[1] -= Math.min(2, count[1]);
    res++;
  }
  res += Math.ceil(count[1] / 4);
  res += count[3];
  console.log(res);
});


You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.In a more formal way, you have to find the quantity of tuples (a,b,x,y) such that 1≤a≤b<x≤y≤|s| and substrings s[a... b], s[x... y] are palindromes.A palindrome is a string that can be read the same way from left to right and from right to left. For example, "abacaba", "z", "abba" are palindromes.A substring s[i... j] (1≤i≤j≤|s|) of string s = s1s2... s|s| is a string sisi+1... sj. For example, substring s[2...4] of string s = "abacaba" equals "bac".

The first line of input contains a non-empty string s which consists of lowercase letters ('a'...'z'), s contains at most 2000 characters.

Output a single number — the quantity of pairs of non-overlapping palindromic substrings of s.
Please do not use the %lld format specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d format specifier.

'use strict';

function solve(s) {
  const n = s.length;
  const f = Array.from({
    length: n
  }, () => new Array(n).fill(0));
  for (let i = 0; i < n; i++) {
    f[i][i] = 1;
    if (s[i] === s[i + 1]) f[i][i + 1] = 1;
  }
  for (let i = n - 1; i >= 0; i--) {
    for (let j = i + 2; j < n; j++) {
      if (s[i] === s[j]) f[i][j] = f[i + 1][j - 1];
    }
  }
  const l = new Array(n);
  {
    for (let i = 0; i < n; i++) {
      l[i] = 1n;
      for (let j = 0; j < i; j++) {
        if (f[j][i]) l[i]++;
      }
    }
  }
  const r = new Array(n);
  {
    const dp = new Array(n);
    for (let i = n - 1; i >= 0; i--) {
      dp[i] = 1n;
      for (let j = i + 1; j < n; j++) {
        if (f[i][j]) dp[i]++;
      }
    }
    for (let i = n - 1; i >= 0; i--) {
      var _r;
      r[i] = ((_r = r[i + 1]) !== null && _r !== void 0 ? _r : 0n) + dp[i];
    }
  }
  let res = 0n;
  for (let i = 0; i < n; i++) {
    var _r2;
    res += l[i] * ((_r2 = r[i + 1]) !== null && _r2 !== void 0 ? _r2 : 0n);
  }
  return res;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const s = await r();
      res[i] = solve(s);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

[{'input': ['aa\r\n'], 'output': ['1\r\n']}, {'input': ['aaa\r\n'], 'output': ['5\r\n']}, {'input': ['abacaba\r\n'], 'output': ['36\r\n']}, {'input': ['aaaaaaaaaa\r\n'], 'output': ['495\r\n']}, {'input': ['aabbb\r\n'], 'output': ['24\r\n']}, {'input': ['abbaa\r\n'], 'output': ['18\r\n']}, {'input': ['bbbbb\r\n'], 'output': ['35\r\n']}, {'input': ['bbaab\r\n'], 'output': ['18\r\n']}, {'input': ['aabba\r\n'], 'output': ['18\r\n']}, {'input': ['aaaaa\r\n'], 'output': ['35\r\n']}, {'input': ['abicabacka\r\n'], 'output': ['57\r\n']}, {'input': ['aiajadabaa\r\n'], 'output': ['87\r\n']}, {'input': ['abacabauabagabaeabacabadabacabbfabacamadabacabaeabacabadabacababcdggdefxeceadaffhecbgpdbeffecdcbfagcbbfgegaggcaffdfiafaeaab\r\n'], 'output': ['20470\r\n']}, {'input': ['abacabadabacabaeabacabadabacabafabacabadabqcabaeoqacabagabacabagefdfdedbbacefhhargbaebbbefabdabdcceddbgcebgdccdccccdbgdecfa\r\n'], 'output': ['23427\r\n']}, {'input': ['abacabafabacabaeabacabadabaqaeatabacabadabacabgeabacabadabacabaeadfgbefcbgbagebgobabaaececaccfeeaeeavbcccwbgecffgfadgagcgfb\r\n'], 'output': ['21454\r\n']}, {'input': ['abacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabadadihfcihdeeegcgdfihcagaigeabegaheddgadbcagheieicdadafaadafeaeihbafccifeifafdhicebgeccbgbdhdcabeghhbebehbbfgfeddfgbdhcbhcfifcgccfihdedafefdhcchbcahgiicgdhahcihdgghchfahahffggedigifhdcbecbhddacdgiahbiffbadhiggagaefihchggfhffhfdcdbfeaabhfhgbbiacag\r\n'], 'output': ['757870\r\n']}, {'input': ['abacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabqdabacabaeabacabadabacabaaciifgeeabgfgfhiadhbfhddihcfeaebfbiiebbcebafegfiefgbagffgchdieicffebaadddcefiibibbhbagfgifieedgeiabhfhbgghiaiegccehgdhaeaafddadgeghidabaeicdhbfghfcciihdgiefaggachefchbddaddafbhhdfhcaebhffbfefabbbbafcdihbcgbfaffieghiiiebhegbcfceidggibdggabaifgedg\r\n'], 'output': ['687296\r\n']}, {'input': ['abacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabpcabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabaeeegbahbcahagefafcedggigbhdaeebfbagfafhdfcdddeaihgdigiaehdabicigbccdacdcbbcfeccdgiibicaifgieigcfbiedebfeddadagibhbdbfeibgbiadgcacfhfbfegbdbheidegcghfhbhcaffbcfhihcbghecfidbdfadgacigfdabhiebibfhfcachcbdcabeedfcffehhidbbihcgahfhdfhbhaciegccagebifh\r\n'], 'output': ['630475\r\n']}, {'input': ['abacabndabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabadabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabayhaghdcfefibhcbccbbfiedcdieghaihagcchhecgdfbdcchhbagebfbiecaibedhhaeidbcgageadeichbhghficaafdbafdbgadgcficdhdgcagiafbahaeffheabfbbgccbfdbfabahiaeabbfggefbafbheeehaebiehibbffehifghadcegdhdagbebeagbedcciibadfcifcedcghacheaihfdfgebcciidbcffgaebgabg\r\n'], 'output': ['619985\r\n']}, {'input': ['abacababcc\r\n'], 'output': ['98\r\n']}, {'input': ['abauabaabd\r\n'], 'output': ['94\r\n']}, {'input': ['abbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbbaaabaabaa\r\n'], 'output': ['79323\r\n']}, {'input': ['bababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbabbbbbaabababbbbbbbaabaabaaabbabbbabbbbabbabaababbbabbb\r\n'], 'output': ['385228\r\n']}, {'input': ['abbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabaabaabbabaaaabbabaaabbaababaababbabaaabbbbabbbaaaabababbbaaabaababb\r\n'], 'output': ['1054380\r\n']}, {'input': ['bababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbbbbbbaaabbaabbbabaabab\r\n'], 'output': ['2840036\r\n']}, {'input': ['bababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababaabbbbbabbabbbaaabbaaababaaaabbbbbbbaaabbbaabaabbaababababbaabbabbabaabbbabbaabababaababbababaaaabababbbaaaaaabbbbbabbbba\r\n'], 'output': ['3678765\r\n']}]


Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches the sum of digits in its second half.But of course, not every ticket can be lucky. Far from it! Moreover, sometimes one look at a ticket can be enough to say right away that the ticket is not lucky. So, let's consider the following unluckiness criterion that can definitely determine an unlucky ticket. We'll say that a ticket is definitely unlucky if each digit from the first half corresponds to some digit from the second half so that each digit from the first half is strictly less than the corresponding digit from the second one or each digit from the first half is strictly more than the corresponding digit from the second one. Each digit should be used exactly once in the comparisons. In other words, there is such bijective correspondence between the digits of the first and the second half of the ticket, that either each digit of the first half turns out strictly less than the corresponding digit of the second half or each digit of the first half turns out strictly more than the corresponding digit from the second half.For example, ticket 2421 meets the following unluckiness criterion and will not be considered lucky (the sought correspondence is 2>1 and 4>2), ticket 0135 also meets the criterion (the sought correspondence is 0<3 and 1<5), and ticket 3754 does not meet the criterion. You have a ticket in your hands, it contains 2n digits. Your task is to check whether it meets the unluckiness criterion.

The first line contains an integer n (1≤n≤100). The second line contains a string that consists of 2n digits and defines your ticket.

In the first line print "YES" if the ticket meets the unluckiness criterion. Otherwise, print "NO" (without the quotes).

let input = "";
process.stdin.on("data", (chunk) => {
  input += chunk;
});
process.stdin.on("end", () => {
  let lines = input.trim().split("\n");
  let n = parseInt(lines[0]);
  let num = lines[1].trim();
  let a = num
    .slice(0, n)
    .split("")
    .map((element) => parseInt(element))
    .sort((a, b) => a - b);
  let b = num
    .slice(n)
    .split("")
    .map((element) => parseInt(element))
    .sort((a, b) => a - b);
  let flag = true;
  if (a[0] > b[0]) {
    for (let i = 1; i < num.length / 2; i++) {
      if (a[i] <= b[i]) {
        flag = false;
        break;
      }
    }
  } else if (a[0] < b[0]) {
    for (let i = 0; i < num.length / 2; i++) {
      if (a[i] >= b[i]) {
        flag = false;
        break;
      }
    }
  } else {
    flag = false;
  }
  if (flag) {
    console.log("YES");
  } else {
    console.log("NO");
  }
});


You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1≤j≤m) of sequence s means that you can choose an arbitrary position i (1≤i≤n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation.Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s.

The first line contains positive integer a. Its length n is positive and doesn't exceed 10^5. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 10^5. The digits in the sequence s are written consecutively without any separators.
The given number a doesn't contain leading zeroes.

Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes.

const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

let firstNum, secondNum;
readline.on('line', function (line) {
    if (line !== "\n") {
        if (!firstNum) {
            firstNum = line;
        } else {
            secondNum = line;
            const num1 = firstNum.split("");
            const num2 = secondNum.split("");
            num2.sort((a, b) => b - a);
            let j = 0;
            for (let i = 0; i < num1.length; i++) {

                if (num1[i] < num2[j]) {
                    num1[i] = num2[j];
                    j++;
                }

                if(j > num2.length){
                    break;
                }
            }

            console.log(num1.join(""));

            process.exit();
        }
    }
});