package main

import(
	"fmt"
	"sort"
	"os"
	"bufio"
	// "math"
	// "strconv"
	// "strings"
)

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

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

func toInt(buf []byte) (o int) {
    for _, v := range buf {
        o = o*10 + int(v-'0')
    }
    return
}

type pair struct {
	first int
	second int
}

type pairs []pair

func (a pairs) Len() int {return len(a)}
func (a pairs) Swap(i,j int) {a[i], a[j] = a[j], a[i]}
func (a pairs) Less(i,j int) bool {
	return a[i].first < a[j].first
	if a[i].first > a[j].first {
		return false
	}
	return a[i].second <= a[j].second
}

var points [2][]pair
var g [100005][]int
var used,used_x,used_y [100005]bool
var diff_x,diff_y []int
var cycle_found bool
var MD int64 = 1000000007

func deg(d int) int64 {
	if d == 0 {
		return 1
	}
	t := deg(d / 2)
	t *= t
	t %= MD
	if d % 2 == 1 {
		t = t * 2 % MD
	}
	return t
}

func dfs(v,p int) {
	used[v] = true
	if !used_x[points[0][v-1].first] {
		used_x[points[0][v-1].first] = true
		diff_x = append(diff_x, points[0][v-1].first)
	}
	if !used_y[points[0][v-1].second] {
		used_y[points[0][v-1].second] = true
		diff_y = append(diff_y, points[0][v-1].second)
	}
	for i:= range g[v] {
		to := g[v][i]
		if to == p {
			continue
		}
		if used[to] {
			cycle_found = true
			continue
		}
		dfs(to,v)
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	n := toInt(scanner.Bytes())
	mp := make(map[pair]int)
	for i:=1;i<=n;i++ {
		scanner.Scan()
		x := toInt(scanner.Bytes())
		scanner.Scan()
		y := toInt(scanner.Bytes())
		mp[pair{x,y}] = i
		points[0] = append(points[0], pair{x,y})
		points[1] = append(points[1], pair{y,x})
	}
	sort.Sort(pairs(points[0]))
	sort.Sort(pairs(points[1]))
	for i:= range points[0] {
		if i > 0 {
			if points[0][i].first == points[0][i - 1].first {
				x := mp[points[0][i]]
				y := mp[points[0][i - 1]]
				g[x] = append(g[x], y)
				g[y] = append(g[y], x)
				//fmt.Println(">>",x,y)
			}
		}
	}

	for i:= range points[1] {
		if i > 0 {
			if points[1][i].first == points[1][i - 1].first {
				x := mp[pair{points[1][i].second, points[1][i].first}]
				y := mp[pair{points[1][i - 1].second, points[1][i - 1].first}]
				g[x] = append(g[x], y)
				g[y] = append(g[y], x)
				//fmt.Println(">>",x,y)
			}
		}
	}

	var ans int64
	ans = 1

	for i:= 1;i<= n;i++ {
		if !used[i] {
			cycle_found = false
			for j:= range diff_x {
				used_x[diff_x[j]] = false
			}
			for j:= range diff_y {
				used_y[diff_y[j]] = false
			}
			diff_x = nil
			diff_y = nil
			dfs(i,i)
			res := deg(len(diff_x) + len(diff_y))
			//fmt.Println(res)
			if !cycle_found {
				res--
			}
			if res < 0 {
				res += MD
			}
			ans = ans * res % MD
		}
	}
	fmt.Println(ans)
}

You are given n distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing.You consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo 109 + 7.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of points. n lines follow. The (i + 1)-th of these lines contains two integers xi, yi ( - 109 ≤ xi, yi ≤ 109) — coordinates of the i-th point. It is guaranteed that all points are distinct.

Print the number of possible distinct pictures modulo 109 + 7.

NoteIn the first example there are two vertical and two horizontal lines passing through the points. You can get pictures with any subset of these lines. For example, you can get the picture containing all four lines in two ways (each segment represents a line containing it). The first way:      The second way:      In the second example you can work with two points independently. The number of pictures is 32 = 9.

package main

import(
	"fmt"
	"sort"
	"os"
	"bufio"
	// "math"
	// "strconv"
	// "strings"
)

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

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

func toInt(buf []byte) (o int) {
    for _, v := range buf {
        o = o*10 + int(v-'0')
    }
    return
}

type pair struct {
	first int
	second int
}

type pairs []pair

func (a pairs) Len() int {return len(a)}
func (a pairs) Swap(i,j int) {a[i], a[j] = a[j], a[i]}
func (a pairs) Less(i,j int) bool {
	return a[i].first < a[j].first
	if a[i].first > a[j].first {
		return false
	}
	return a[i].second <= a[j].second
}

var points [2][]pair
var pts [100005]pair
var g [100005][]int
var used [100005]bool
var diff_x,diff_y []int
var cycle_found bool
var MD int64 = 1000000007
var used_x,used_y map[int]bool
var n,x,y int

func deg(d int) int64 {
	if d == 0 {
		return 1
	}
	t := deg(d / 2)
	t *= t
	t %= MD
	if d % 2 == 1 {
		t = t * 2 % MD
	}
	return t
}

func dfs(v,p int) {
	used[v] = true
	if !used_x[pts[v].first] {
		used_x[pts[v].first] = true
		diff_x = append(diff_x, pts[v].first)
	}
	if !used_y[pts[v].second] {
		used_y[pts[v].second] = true
		diff_y = append(diff_y, pts[v].second)
	}
	for i:= range g[v] {
		to := g[v][i]
		if to == p {
			continue
		}
		if used[to] {
			cycle_found = true
			continue
		}
		dfs(to,v)
	}
}

func main() {
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d\n", &n)
	mp := make(map[pair]int)
	used_x = make(map[int]bool)
	used_y = make(map[int]bool)
	for i:=1;i<=n;i++ {
		fmt.Fscanf(in, "%d %d\n",&x,&y)
		mp[pair{x,y}] = i
		pts[i] = pair{x,y}
		points[0] = append(points[0], pair{x,y})
		points[1] = append(points[1], pair{y,x})
	}
	sort.Sort(pairs(points[0]))
	sort.Sort(pairs(points[1]))
	for i:= range points[0] {
		if i > 0 {
			if points[0][i].first == points[0][i - 1].first {
				x := mp[points[0][i]]
				y := mp[points[0][i - 1]]
				g[x] = append(g[x], y)
				g[y] = append(g[y], x)
				//fmt.Println(">>",x,y)
			}
		}
	}

	for i:= range points[1] {
		if i > 0 {
			if points[1][i].first == points[1][i - 1].first {
				x := mp[pair{points[1][i].second, points[1][i].first}]
				y := mp[pair{points[1][i - 1].second, points[1][i - 1].first}]
				g[x] = append(g[x], y)
				g[y] = append(g[y], x)
				//fmt.Println(">>",x,y)
			}
		}
	}

	var ans int64
	ans = 1

	for i:= 1;i<= n;i++ {
		if !used[i] {
			cycle_found = false
			for j:= range diff_x {
				used_x[diff_x[j]] = false
			}
			for j:= range diff_y {
				used_y[diff_y[j]] = false
			}
			diff_x = nil
			diff_y = nil
			dfs(i,i)
			//fmt.Println(len(diff_x),len(diff_y))
			res := deg(len(diff_x) + len(diff_y))
			if !cycle_found {
				res--
			}
			if res < 0 {
				res += MD
			}
			ans = ans * res % MD
		}
	}
	fmt.Println(ans)
}


package main

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

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

	t, m := readTwoNums(reader)

	manager := NewManager(m)

	var buf bytes.Buffer

	for t > 0 {
		t--
		s, _ := reader.ReadBytes('\n')

		if s[0] == 'a' {
			var n int
			readInt(s, len("alloc "), &n)
			id := manager.Alloc(n)

			if id < 0 {
				buf.WriteString("NULL\n")
			} else {
				buf.WriteString(fmt.Sprintf("%d\n", id))
			}
		} else if s[0] == 'e' {
			var x int
			readInt(s, len("erase "), &x)
			ok := manager.Erase(x)
			if !ok {
				buf.WriteString("ILLEGAL_ERASE_ARGUMENT\n")
			}
		} else {
			manager.Defragment()
		}
	}

	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
}

type Node struct {
	next *Node
	sz   int
	pos  int
	id   int
}

func NewNode(pos int, sz int) *Node {
	node := new(Node)
	node.pos = pos
	node.sz = sz
	return node
}

type Manager struct {
	free *Node
	used *Node
	mem  map[int]int
	p    int
	tot  int
}

func NewManager(m int) Manager {
	free := new(Node)
	free.next = NewNode(0, m)
	used := new(Node)
	mem := make(map[int]int)
	return Manager{free, used, mem, 0, m}
}

func (this *Manager) Alloc(n int) int {
	head := this.free

	for head.next != nil && head.next.sz < n {
		head = head.next
	}

	if head.next == nil {
		return -1
	}

	tmp := head.next
	pos := tmp.pos

	var tmp2 *Node

	if tmp.sz > n {
		tmp.sz -= n
		tmp.pos += n
		tmp2 = NewNode(pos, n)
	} else {
		head.next = tmp.next
		tmp2 = tmp
	}

	head = this.used

	for head.next != nil && head.next.pos < pos {
		head = head.next
	}

	tmp2.next = head.next

	head.next = tmp2

	this.p++
	this.mem[this.p] = pos
	tmp2.id = this.p

	return this.p
}

func (this *Manager) Erase(x int) bool {
	if pos, found := this.mem[x]; !found {
		return false
	} else {
		delete(this.mem, x)
		head := this.used
		//remove it from used
		for head.next != nil && head.next.pos < pos {
			head = head.next
		}

		if head.next == nil || head.next.pos > pos || head.next.id != x {
			return false
		}

		tmp := head.next
		head.next = tmp.next

		// put back as free
		head = this.free

		for head.next != nil && head.pos < pos {
			head = head.next
		}

		if head != this.free && head.pos+head.sz == pos {
			head.sz += tmp.sz
			return true
		}

		tmp.id = -1
		tmp.next = head.next
		head.next = tmp

		if tmp.next != nil && tmp.pos+tmp.sz == tmp.next.pos {
			tmp.sz += tmp.next.sz
			tmp.next = tmp.next.next
		}

		return true
	}
}

func (this *Manager) Defragment() {
	head := this.used
	var sz int

	for head.next != nil {
		cur := head.next
		cur.pos = sz
		sz += cur.sz
		head = head.next
	}

	if this.tot > sz {
		this.free.next = NewNode(sz, this.tot-sz)
	} else {
		this.free.next = nil
	}
}

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']}]


package main

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

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

	n, a, b := readThreeNums(reader)

	h := readNNums(reader, n)

	res := solve(n, a, b, h)

	var buf bytes.Buffer

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

	for i := 0; i < len(res); i++ {
		buf.WriteString(fmt.Sprintf("%d ", res[i]))
	}
	fmt.Println(buf.String())
}

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

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

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

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

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') {
			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 H = 17
const INF = 10000

func solve(n int, a int, b int, h []int) []int {
	for i := 0; i < n; i++ {
		h[i]++
	}
	if n == 3 {
		var res []int
		for h[0] > 0 || h[1] > 0 || h[2] > 0 {
			h[0] = max(0, h[0]-b)
			h[1] = max(0, h[1]-a)
			h[2] = max(0, h[2]-b)
			res = append(res, 2)
		}
		return res
	}
	dp := make([][][]int, n)
	for i := 0; i < n; i++ {
		dp[i] = make([][]int, h[i]+1)
		for j := 0; j <= h[i]; j++ {
			dp[i][j] = make([]int, 1+(H+a-1)/a)
			for k := 0; k < len(dp[i][j]); k++ {
				dp[i][j][k] = INF
			}
		}
	}
	dp[0][h[0]][0] = 0

	for i := 1; i < n-1; i++ {
		for j := 0; j <= h[i-1]; j++ {
			for k := 0; k < len(dp[i-1][j]); k++ {
				if dp[i-1][j][k] >= INF {
					continue
				}
				//first: need to make sure attacks at this archer can make h[i-1] to be zero
				for kk := 0; kk < len(dp[i][j]); kk++ {
					jj := max(0, h[i]-b*k-a*kk)
					if kk*b >= j {
						dp[i][jj][kk] = min(dp[i][jj][kk], dp[i-1][j][k]+kk)
					}
				}
			}
		}
	}

	for j := 0; j <= h[n-2]; j++ {
		for k := 0; k < len(dp[n-2][j]); k++ {
			if dp[n-2][j][k] >= INF {
				continue
			}
			if k*b >= h[n-1] {
				dp[n-1][0][0] = min(dp[n-1][0][0], dp[n-2][j][k])
			}
		}
	}
	best := dp[n-1][0][0]
	res := make([]int, 0, best)

	for i := n - 2; i > 0; i-- {
		var found = false
		for j := 0; j <= h[i] && !found; j++ {
			for k := 0; k < len(dp[i][j]) && !found; k++ {
				if dp[i][j][k] == best {
					for x := 0; x < k; x++ {
						res = append(res, i+1)
					}
					best -= k
					found = true
				}
			}
		}
	}

	return res
}

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

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

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


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("-1\n")
				return
			}
		}
	} else if sum%3 == 2 {
		if !diminish(count, 2) {
			if !diminish(count, 1) || !diminish(count, 1) {
				writer.WriteString("-1\n")
				return
			}
		}
	}
	for d := 9; d >= 0; d-- {
		for i := 0; i < count[d]; i++ {
			writer.WriteString(fmt.Sprintf("%d", d))
		}
	}
	writer.WriteString("\n")
}

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


package main

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

type Node struct {
	max int
	min int
}

var n int
var h [100000]int

func create(tree []*Node, l int, r int, index int) {
	if l == r {
		tree[index] = &Node{h[l], h[r]}
		return
	}
	mid := (l + r) / 2
	create(tree, l, mid, index*2+1)
	create(tree, mid+1, r, index*2+2)
	max, min := tree[index*2+1].max, tree[index*2+1].min
	if max < tree[index*2+2].max {
		max = tree[index*2+2].max
	}
	if min > tree[index*2+2].min {
		min = tree[index*2+2].min
	}
	tree[index] = &Node{max, min}
}

func query(tree []*Node, l int, r int, index int, lIndex int, rIndex int) (int, int) {
	if l == lIndex && r == rIndex {
		return tree[index].max, tree[index].min
	}
	mid := (l + r) / 2
	if rIndex <= mid {
		return query(tree, l, mid, index*2+1, lIndex, rIndex)
	}
	if lIndex >= mid+1 {
		return query(tree, mid+1, r, index*2+2, lIndex, rIndex)
	}
	max, min := query(tree, l, mid, index*2+1, lIndex, mid)
	max1, min1 := query(tree, mid+1, r, index*2+2, mid+1, rIndex)
	if max < max1 {
		max = max1
	}
	if min > min1 {
		min = min1
	}
	return max, min
}

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

	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d ", &h[i])
	}
	tree := make([]*Node, 1000000)
	create(tree, 0, n-1, 0)

	lp, rp := 0, 0
	best := 0
	var solu []*Node
	for rp != n {
		max, min := query(tree, 0, n-1, 0, lp, rp)
		if max-min > k {
			lp++
		} else if best == rp-lp+1 {
			solu = append(solu, &Node{rp, lp})
			rp++
		} else if best < rp-lp+1 {
			best = rp - lp + 1
			solu = make([]*Node, 0, 100000)
			solu = append(solu, &Node{rp, lp})
			rp++
		} else {
			rp++
		}
	}

	writer := bytes.NewBuffer(make([]byte, 0, 12000000))
	fmt.Fprintf(writer, "%d %d\n", best, len(solu))
	for i := 0; i < len(solu); i++ {
		fmt.Fprintf(writer, "%d %d\n", solu[i].min+1, solu[i].max+1)
	}
	writer.WriteTo(os.Stdout)

}

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
}


package main

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

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 getRank(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--
					num[numPointer-1] = "1"
					break
				}
			}
			rank, ok := macro2Op[numPointer[numPointer-1]]
			if ok && rank == "fail" {
				return rank
			}
			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
		fmt.Fscanf(reader, "#define %s ", &macro)
		s, _ := reader.ReadString('\n')
		tokens := tokenize(s)
		macro2Op[macro] = getRank(tokens)
	}

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

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']}]


package main

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

type point struct {
	x, y int
}

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

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


package main

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

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

var n, m int
var vType []Type
var edges [][]int

func main() {
	defer out.Flush()
	fmt.Fscan(in, &n, &m)
	vType = make([]Type, n)
	edges = make([][]int, n)
	for i := 0; i < m; i++ {
		var a, b int
		fmt.Fscan(in, &a, &b)
		a--
		b--
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}
	if ok, a, b, c := solve(); ok {
		fmt.Fprintln(out, "Yes")
		fmt.Fprintln(out, strings.Repeat("a", a)+strings.Repeat("b", b)+strings.Repeat("c", c))
	} else {
		fmt.Fprintln(out, "No")
	}
}

func solve() (ok bool, a, b, c int) {
	for v := range edges {
		if len(edges[v]) == n-1 {
			vType[v] = B
		}
	}
	for v := range vType {
		if vType[v] == UNSEEN {
			mark(v, A)
			break
		}
	}
	for v := range vType {
		if vType[v] == UNSEEN {
			mark(v, C)
			break
		}
	}
	for v := range vType {
		switch vType[v] {
		case UNSEEN:
			ok = false
			return
		case A:
			a++
		case B:
			b++
		case C:
			c++
		}
	}
	for v := range vType {
		if vType[v] == A && len(edges[v]) != a-1+b {
			ok = false
			return
		}
		if vType[v] == C && len(edges[v]) != c-1+b {
			ok = false
			return
		}
	}
	ok = true
	return
}

func mark(v int, t Type) {
	if vType[v] != UNSEEN {
		return
	}
	vType[v] = t
	for _, u := range edges[v] {
		mark(u, t)
	}
}

type Type int

const (
	UNSEEN Type = iota
	A
	B
	C
)

One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:   G has exactly n vertices, numbered from 1 to n.  For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.

The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.

In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.

NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.

package main

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

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

var n, m int
var vType []Type
var edges [][]int

func main() {
	defer out.Flush()
	fmt.Fscan(in, &n, &m)
	vType = make([]Type, n)
	edges = make([][]int, n)
	for i := 0; i < m; i++ {
		var a, b int
		fmt.Fscan(in, &a, &b)
		a--
		b--
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}
	if solve() {
		fmt.Fprintln(out, "Yes")
		for v := range vType {
			fmt.Fprint(out, string('a'+vType[v]-1))
		}
		fmt.Fprintln(out)
	} else {
		fmt.Fprintln(out, "No")
	}
}

func solve() bool {
	for v := range edges {
		if len(edges[v]) == n-1 {
			vType[v] = B
		}
	}
	for v := range vType {
		if vType[v] == UNSEEN {
			mark(v, A)
			break
		}
	}
	for v := range vType {
		if vType[v] == UNSEEN {
			mark(v, C)
			break
		}
	}
	var a, b, c int
	for v := range vType {
		switch vType[v] {
		case UNSEEN:
			return false
		case A:
			a++
		case B:
			b++
		case C:
			c++
		}
	}
	for v := range vType {
		if vType[v] == A && len(edges[v]) != a-1+b {
			return false
		}
		if vType[v] == C && len(edges[v]) != c-1+b {
			return false
		}
	}
	return true
}

func mark(v int, t Type) {
	if vType[v] != UNSEEN {
		return
	}
	vType[v] = t
	for _, u := range edges[v] {
		mark(u, t)
	}
}

type Type int

const (
	UNSEEN Type = iota
	A
	B
	C
)


package main

import (
  "fmt"
  "sort"
)

const N = 500000

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

var v, stk [N]int

func main() {
  var n, top int = 0, 0
  var res int64 = 0
  fmt.Scan(&n)
  for i := 0; i < n; i++ {
    fmt.Scan(&v[i])
    for top >= 2 && stk[top-2] >= stk[top-1] && stk[top-1] <= v[i] {
      res += int64(IntMin(v[i], stk[top-2]))
      top--
    }
    stk[top] = v[i]
    top++
  }
  sort.Sort(sort.IntSlice(stk[:top]))
  for i := 0; i < top-2; i++ {
    res += int64(stk[i])
  }
  fmt.Println(res)
}

Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points. After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.

The first line contains a single integer n (1 ≤ n ≤ 5·105) — the number of elements in the array. The next line contains n integers ai (1 ≤ ai ≤ 106) — the values of the array elements.

In a single line print a single integer — the maximum number of points Artem can get.

package main

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

const N = 500000

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

var v, stk [N]int

func main() {
  r := bufio.NewReader(os.Stdin)
  var n, top int = 0, 0
  var res int64 = 0
  fmt.Fscan(r, &n)
  for i := 0; i < n; i++ {
    fmt.Fscan(r, &v[i])
    for top >= 2 && stk[top-2] >= stk[top-1] && stk[top-1] <= v[i] {
      res += int64(IntMin(v[i], stk[top-2]))
      top--
    }
    stk[top] = v[i]
    top++
  }
  sort.Sort(sort.IntSlice(stk[:top]))
  for i := 0; i < top-2; i++ {
    res += int64(stk[i])
  }
  fmt.Println(res)
}


// Author: sighduck
// URL: https://codeforces.com/problemset/problem/1213/D2

package main

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

const MaxNum = 200001

func Solve(n int, k int, a []int) int {
	divs := make([][]int, MaxNum)
	for _, elem := range a {
		count := 0
		for elem > 0 {
			divs[elem] = append(divs[elem], count)
			elem /= 2
			count += 1
		}
	}
	ans := MaxNum
	for _, d := range divs {
		sort.Ints(d)
		sum := 0
		for i := 0; i < len(d) && i < k; i++ {
			sum += d[i]
		}
		if len(d) >= k && sum < ans {
			ans = sum
		}
	}
	return ans
}

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

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

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

The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.

package main

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

/* solution */

type nodeType struct {
	next [2]*nodeType
	cuts [20]int
	cnt  int
}

func solve() {

	n, k := readInt(), readInt()
	root := &nodeType{}

	for i := 0; i < n; i++ {
		v := readInt()
		digits := make([]int, 0)
		for v > 0 {
			digits = append(digits, v%2)
			v = v / 2
		}
		addToTree(root, digits, len(digits))
	}

	printInt(search(root, k))

}

func search(node *nodeType, k int) int {
	if node == nil || node.cnt < k {
		return 1000000000
	}
	s0 := 0
	rem := k - node.cuts[0]
	for i := 1; rem > 0 && i < 20; i++ {
		if rem > node.cuts[i] {
			s0 += node.cuts[i] * i
			rem -= node.cuts[i]
		} else {
			s0 += rem * i
			rem = 0
		}
	}
	s1, s2 := search(node.next[0], k), search(node.next[1], k)
	return min(s0, min(s1, s2))
}

func addToTree(node *nodeType, digits []int, idx int) {
	node.cnt++
	node.cuts[idx]++
	idx--
	if idx < 0 {
		return
	}
	next := node.next[digits[idx]]
	if next == nil {
		node.next[digits[idx]] = &nodeType{}
		next = node.next[digits[idx]]
	}
	addToTree(next, digits, idx)
}

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

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
		defer f.Close()
	} else {
		f = os.Stdin
	}

	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	reader = bufio.NewScanner(f)

	const maxCapacity = 1024 * 1024
	buf := make([]byte, maxCapacity)
	reader.Buffer(buf, maxCapacity)

	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

func read() string {
	reader.Scan()
	return reader.Text()
}

func readInt() int {
	reader.Scan()
	ret, _ := strconv.Atoi(reader.Text())
	return ret
}

func print(s string) {
	writer.WriteString(s)
	writer.WriteString("\n")
}

func printInt(i int) {
	print(strconv.Itoa(i))
}

func printInt64(i int64) {
	print(strconv.FormatInt(i, 10))
}

func readInt64() int64 {
	reader.Scan()
	ret, _ := strconv.ParseInt(reader.Text(), 10, 64)
	return ret
}


package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)
//defer writer.Flush()

const (
	//MaxScanTokenSize = 64 * 1024 // package default
	MaxScanTokenSize = 8 * 1024 * 1024 // 8M
)

func init() {
	scanner.Buffer(make([]byte, 0, MaxScanTokenSize), MaxScanTokenSize)
	scanner.Split(bufio.ScanWords)
}

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

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

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

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

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

func readFloat64() float64 {
	v, _ := strconv.ParseFloat(readString(), 64)
	return v
}

func readFloat64Array(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = readFloat64()
	}
	return res
}

type Edge struct {
	From int
	To int
	Cap int
	Flow int
}

type Graph struct {
	NNode int
	NEdge int
	Edges []Edge
	Nodes [][]int
}

func NewGraph(nNode, nEdge int) *Graph {
	g := &Graph{
		NNode: nNode,
		NEdge: nEdge,
		Edges: make([]Edge, 0, nEdge),
		Nodes: make([][]int, nNode, nNode),
	}
	return g
}

func (g *Graph) AddEdge(from, to, cap, flow int) {
	g.Nodes[from] = append(g.Nodes[from], len(g.Edges))
	g.Edges = append(g.Edges, Edge{from, to, cap, flow})
	g.Nodes[to] = append(g.Nodes[to], len(g.Edges))
	g.Edges = append(g.Edges, Edge{to, from, cap, flow})
}

func (g *Graph) Show() {
	fmt.Printf("n node = %d, n edge = %d\n", g.NNode, g.NEdge)
	for i, cur := range g.Nodes {
		fmt.Printf("[%d]", i)
		for _, next := range cur {
			fmt.Printf(" %d", g.Edges[next].To)
		}
		fmt.Println()
	}
}

type QueueStack struct {
	data []interface{}
}

func (q *QueueStack) size() int {
	return len(q.data)
}

func (q *QueueStack) push(v interface{}) {
	q.data = append(q.data, v)
}

func (q *QueueStack) popFront() interface{} {
	v := q.data[0]
	q.data = q.data[1:]
	return v
}

func (q *QueueStack) pop() interface{} {
	last := len(q.data) - 1
	v := q.data[last]
	q.data = q.data[:last]
	return v
}

func spfa(g *Graph, from, to int) int {
	n := g.NNode
	dist := make([]int, n, n)
	dist[0] = 0
	for i := 1; i < n; i++ {
		dist[i] = n
	}

	q := &QueueStack{}
	q.push(from)
	for q.size() > 0 {
		cur := q.pop().(int)
		for _, ie := range g.Nodes[cur] {
			e := g.Edges[ie]
			if dist[cur] + 1 < dist[e.To] {
				dist[e.To] = dist[cur] + 1
				q.push(e.To)
			}
		}
	}

	return dist[to]
}

func main() {
	defer writer.Flush()

	n, m := readInt(), readInt()

	gFull := make([][]int, n, n)
	for i := 0; i < n; i++ {
		gFull[i] = make([]int, n, n)
	}

	g := NewGraph(n, m)
	for i := 0; i < m; i++ {
		x, y := readInt(), readInt()
		x--
		y--
		g.AddEdge(x, y, 0, 0)
		gFull[x][y] = 1
		gFull[y][x] = 1
	}
	g.Show()

	d1 := spfa(g, 0, n - 1)

	if d1 == n {
		fmt.Fprintf(writer, "-1\n")
		return
	}

	g = NewGraph(n, n * (1 + n) / 2 - m)
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if gFull[i][j] == 0 {
				g.AddEdge(i, j, 0, 0)
			}
		}
	}

	d2 := spfa(g, 0, n - 1)
	if d2 == n {
		fmt.Fprintf(writer, "-1\n")
		return
	}

	ans := d1
	if d1 < d2 {
		ans = d2
	}
	fmt.Fprintf(writer, "%d\n", ans)
}

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


let lines = '';
process.stdin.on('data', c => lines += c);

const solution = () => {
	let line = lines.split('\n');
	let [n, k] = line[0].split(' ').map(v => parseInt(v,10));
	let s = line[1];
	let r = '';
	for(let i = 0; i < n; i++){
		let c = s[i];
		if (i === 0 && c > 1 && k > 0) {
			r += 1;
			k--;
		} else if (i === 0 && n == 1 && k > 0) {
			r += 0;
			k--;
		} else if (i !== 0 && c > 0 && k > 0) {
			r += 0;
			k--;
		} else {
			r += c;
		}
	}

	console.log(r);
	process.exit(0);
}

process.stdin.on('end', solution);

Ania has a large integer $$$S$$$. Its decimal representation has length $$$n$$$ and doesn't contain any leading zeroes. Ania is allowed to change at most $$$k$$$ digits of $$$S$$$. She wants to do it in such a way that $$$S$$$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — the number of digits in the decimal representation of $$$S$$$ and the maximum allowed number of changed digits. The second line contains the integer $$$S$$$. It's guaranteed that $$$S$$$ has exactly $$$n$$$ digits and doesn't contain any leading zeroes.

Output the minimal possible value of $$$S$$$ which Ania can end with. Note that the resulting integer should also have $$$n$$$ digits.

NoteA number has leading zeroes if it consists of at least two digits and its first digit is $$$0$$$. For example, numbers $$$00$$$, $$$00069$$$ and $$$0101$$$ have leading zeroes, while $$$0$$$, $$$3000$$$ and $$$1010$$$ don't have leading zeroes.

const readline = require('readline');

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

var line = 0;
var n, k;
var S;

rl.on('line', (data) => {
	++line;

	var arr = data.split(' ');

	if(line===1) {
		n = parseInt(arr[0]);
		k = parseInt(arr[1]);
	} else {
		S = arr[0];
		var array = S;
		var result = '';
//		console.log(array)

		if(k===0) {
			console.log(S);
		} else if(n===1){
			console.log(0);
		} else {
			var idx=1;
			if(array[0]!=='1'){
				--k;
			}
			result+='1';
			for(; idx<n; idx++) {
				if(k===0) {
//					console.log('K is zero for',array[idx]);
					for(var jj=idx; jj<n; jj++) {
						result+=array[jj];
//							console.log('Added',array[jj])
					}
					idx=n;
					break;
				}

				if(array[idx]==='0') {
					result+=0;
				}else {
//					console.log('Decrement for',array[idx],'K is',k-1);
					--k;
					result+=0;
				}

//				console.log(k+1,'ADDED',array[idx])
			}
			console.log(result);
		}
		line=0;
	}
});


print(function(n, a, m, b) {
	var i, j, d = new Int8Array(1e4);
	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			if (b[j] % a[i] === 0)
				d[b[j] / a[i]]++;

	return Math.max.apply(0, d);

}(+readline(), readline().split(' ').map(Number),
  +readline(), readline().split(' ').map(Number)));

Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  const len1 = +readLine();
  const arr1 = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const len2 = +readLine();
  const arr2 = readLine()
    .split(" ")
    .map((n) => parseInt(n));

  let max = Number.MIN_SAFE_INTEGER;
  let count = 0;

  for (let i = 0; i < len2; i++) {
    const a = arr2[i];
    for (let j = 0; j < len1; j++) {
      const b = arr1[j];
      const div = a / b;
      if (Number.isInteger(div)) {
        if (div > max) {
          max = div;
          count = 0;
        }
        if (div === max) count++;
      }
    }
  }
  console.log(count);
}


var lll = readline().split(' ')
var n = lll[0]
var P1 = lll[1]
var P2 = lll[2]
var P3 = lll[3]
var T1 = lll[4]
var T2 = lll[5]

var ss = []

while (lll = readline()) ss.push(lll.split(' '))

var pows = 0
var pse

for (var i = 0; i < ss.length; i++) {
  var s = ss[i]
  pows += (s[1] - s[0]) * P1
  if (pse) {
    var w = s[0] - pse
    pows += Math.min(w, T1) * P1
    w -= T1
    if (w) {
      pows += Math.min(w, T2) * P2
      w -= T2
      if (w) {
        pows += w * P3
      }
    }
  }
  pse = s[1]
}

print(pows)

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