package main

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

/*
8
2 1 3 3
1 1 1 1
1 1 2 1
1 2 2 2
1 2 2 3
1 1 3 3
1 1 5 4
2 2 3 4
---
YES		AABCCC
NO		ABC
YES		ABCC
YES		ABBCC
NO		ABBCC
NO		ABCCC
YES		ABCCCCC
YES		AABBCCC

C		-> 0
CC		-> 1
CCC		-> 2
CCCC	-> 3
CCCCC	-> 4
========
4
3 3 3 6
3 3 3 7
1 1 7 6
1 1 7 7
---
YES 	AAABBBCCC
NO
YES		ABCCCCCCC
NO

ABACA 		-> 0
ABACAA		-> 1
ABACABACA	-> 0
ABACABACAA	-> 1
========
5
4 1 1 0
4 1 1 1
4 1 1 2
4 1 1 3
4 1 1 4
---
NO
YES
YES
YES
NO
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var a, b, c, m int
	scanf("%d %d %d %d\n", &a, &b, &c, &m)

	maxAbc := max(a, b, c)
	minCnt := maxAbc - (sum(a, b, c) - maxAbc) - 1
	maxCnt := a + b + c - 3

	if m >= minCnt && m <= maxCnt {
		fmt.Fprintln(writer, "YES")
	} else {
		fmt.Fprintln(writer, "NO")
	}
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func sum(nums ...int) (sum int) {
	for _, num := range nums {
		sum += num
	}
	return
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := 5; i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int) []int {
	factors := []int{1}

	sqrtA := int(math.Sqrt(float64(num)))

	for ftr := 2; ftr <= sqrtA; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > sqrtA {
		factors = append(factors, num)
	}

	return factors
}

package main

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

func main() {

	r := bufio.NewReader(os.Stdin)

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

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

		fmt.Println(solve(a, b, c, m))
	}
}

func solve(a, b, c, m int) string {
	max := a + b + c - 3

	var arr []int
	arr = append(arr, a, b, c)
	sort.Ints(arr)

	var min int

	if arr[2] > arr[0] + arr[1] + 1 {
		min = arr[2] - (arr[0] + arr[1] + 1)

	} else {
		min = 0
	}

	if m < min || m > max {
		return "NO"
	}

	return "YES"
}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })

func MIN(x, y int64) int64 {
	if x > y {
		return y
	} else {
		return x
	}
}

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

func MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

func MAX(x, y int64) int64 {
	if x > y {
		return x
	} else {
		return y
	}
}

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}
}

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

func MODULE(x, y int) int {
	if x > y {
		return x - y
	} else {
		return y - x
	}
}

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

func Sum(n, m int) int {
	var ans int

	if n == 1 {
		return 0
	} else {
		for i := 2; i < n; i++ {
			ans = (ans + Sum(i, m)) % m
		}
		for j := 2; j < n+1; j++ {
			ans = (ans + Sum(n/j, m)) % m
		}
		return ans
	}
}

func ChangeStringToDate(x string) (t time.Time, err error) {
	t, err = time.Parse("2006-01-02", x)
	return
}

func DiffrenceBetweenTwoDates(first, second time.Time) int64 {
	date := first
	date2 := second
	k := date.Unix() - date2.Unix()
	return k
}

func Union(a, b []int) []int {
	m := make(map[int]bool)

	for _, item := range a {
		m[item] = true
	}

	for _, item := range b {
		if _, ok := m[item]; !ok {
			a = append(a, item)
		}
	}
	return a
}

// for o := 0; o < t; o++ {
// 	var a, b, c int
// 	fmt.Fscan(input, &a, &b, &c)

// 	A := a % 2
// 	B := b % 2
// 	C := c % 2
// 	if A+B+C == 0 {
// 		fmt.Println(0)
// 	}
// 	if A+B+C == 1 {
// 		if A == 1 {
// 			fmt.Println(1)
// 		}
// 		if B == 1 {
// 			if a >= 2 {
// 				fmt.Println(0)
// 			} else {
// 				fmt.Println(2)
// 			}
// 		}
// 		if C == 1 {
// 			if a > 0
// 			fmt.Println(1)
// 		}
// 	}
// 	if A+B+C == 2 {

// 	}
// 	if A+B+C == 3 {
// 		fmt.Println(0)
// 	}

// }

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

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var a, b, c, m int
		fmt.Fscan(input, &a, &b, &c, &m)

		NumberOfBlocks := a + b + c - m
		minBlock := 0
		if a > 0 {
			minBlock++
		}
		if b > 0 {
			minBlock++
		}
		if c > 0 {
			minBlock++
		}

		var maxBloxk int
		if a+b >= c && b+c >= a && a+c >= b {
			maxBloxk = a + b + c
		} else {
			q := MAXX(MAXX(a, b), c)
			maxBloxk = 2*(a+b+c-q) + 1
		}

		if NumberOfBlocks >= minBlock && NumberOfBlocks <= maxBloxk {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}

}

package main

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

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

	t := 0
	fmt.Fscanln(in, &t)
	for tcNo := 1; tcNo <= t; tcNo++ {
		a, b, c, m := 0, 0, 0, 0
		fmt.Fscanln(in, &a, &b, &c, &m)

		minM := 0
		lettersCount := []int{a, b, c}
		sort.Ints(lettersCount)

		minM = lettersCount[2] - lettersCount[1] - lettersCount[0] - 1
		if minM < 0 {
			minM = 0
		}

		maxM := 0

		if a > 1 {
			maxM += a - 1
		}
		if b > 1 {
			maxM += b - 1
		}
		if c > 1 {
			maxM += c - 1
		}

		if m >= minM && m <= maxM {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

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

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		z := make([]int, 3)
		var m int
		fmt.Fscan(in, &z[0], &z[1], &z[2], &m)

		sort.Ints(z)
		high := (z[0] - 1) + (z[1] - 1) + (z[2] - 1)
		low := z[2] - (z[0] + z[1] + 1)
		if m >= low && m <= high {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

package main

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

/*
1
2 1 3 3
---
YES - AABCCC

C		-> 0
CC		-> 1
CCC		-> 2
CCCC	-> 3
CCCCC	-> 4
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var a, b, c, m int
	scanf("%d %d %d %d\n", &a, &b, &c, &m)

	pairCnt := a + b + c - 3

	if m > pairCnt {
		fmt.Fprintln(writer, "NO")
		return
	}

	fmt.Fprintln(writer, "YES")
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := 5; i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int) []int {
	factors := []int{1}

	sqrtA := int(math.Sqrt(float64(num)))

	for ftr := 2; ftr <= sqrtA; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > sqrtA {
		factors = append(factors, num)
	}

	return factors
}

package main

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

/*

 */

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var a, b, c, m int
	scanf("%d %d %d %d\n", &a, &b, &c, &m)

	pairCnt := a/2 + b/2 + c/2

	if m > pairCnt {
		fmt.Fprintln(writer, "NO")
		return
	}

	fmt.Fprintln(writer, "YES")
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := 5; i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int) []int {
	factors := []int{1}

	sqrtA := int(math.Sqrt(float64(num)))

	for ftr := 2; ftr <= sqrtA; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > sqrtA {
		factors = append(factors, num)
	}

	return factors
}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })

func MIN(x, y int64) int64 {
	if x > y {
		return y
	} else {
		return x
	}
}

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

func MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

func MAX(x, y int64) int64 {
	if x > y {
		return x
	} else {
		return y
	}
}

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}
}

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

func MODULE(x, y int) int {
	if x > y {
		return x - y
	} else {
		return y - x
	}
}

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

func Sum(n, m int) int {
	var ans int

	if n == 1 {
		return 0
	} else {
		for i := 2; i < n; i++ {
			ans = (ans + Sum(i, m)) % m
		}
		for j := 2; j < n+1; j++ {
			ans = (ans + Sum(n/j, m)) % m
		}
		return ans
	}
}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var a, b, c, m int
		fmt.Fscan(input, &a, &b, &c, &m)

		ARR := make([]int, 0)
		ARR = append(ARR, a)
		ARR = append(ARR, b)
		ARR = append(ARR, c)

		sort.Ints(ARR)

		minim := ARR[2] - ARR[1] - 1
		maxim := 0
		for i := 0; i < 3; i++ {
			if ARR[i] > 0 {
				maxim = maxim + ARR[i] - 1
			}
		}
		if m >= minim && m <= maxim {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })

func MIN(x, y int64) int64 {
	if x > y {
		return y
	} else {
		return x
	}
}

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

func MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

func MAX(x, y int64) int64 {
	if x > y {
		return x
	} else {
		return y
	}
}

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}
}

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

func MODULE(x, y int) int {
	if x > y {
		return x - y
	} else {
		return y - x
	}
}

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

func Sum(n, m int) int {
	var ans int

	if n == 1 {
		return 0
	} else {
		for i := 2; i < n; i++ {
			ans = (ans + Sum(i, m)) % m
		}
		for j := 2; j < n+1; j++ {
			ans = (ans + Sum(n/j, m)) % m
		}
		return ans
	}
}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var a, b, c, m int
		fmt.Fscan(input, &a, &b, &c, &m)

		ARR := make([]int, 0)
		ARR = append(ARR, a)
		ARR = append(ARR, b)
		ARR = append(ARR, c)

		sort.Ints(ARR)

		minim := ARR[2] - ARR[1] - 1
		maxim := a + b + c - 3
		if m >= minim && m <= maxim {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

	t := 0
	fmt.Fscanln(in, &t)
	for tcNo := 1; tcNo <= t; tcNo++ {
		a, b, c, m := 0, 0, 0, 0
		fmt.Fscanln(in, &a, &b, &c, &m)

		lettersCount := []int{a, b, c}
		for len(lettersCount) > 1 {
			sort.Ints(lettersCount)
			lettersCount[len(lettersCount)-2] = lettersCount[len(lettersCount)-1] - lettersCount[len(lettersCount)-2]
			lettersCount = lettersCount[:len(lettersCount)-1]
		}
		minM := lettersCount[0] - 1

		maxM := 0

		if a > 1 {
			maxM += a - 1
		}
		if b > 1 {
			maxM += b - 1
		}
		if c > 1 {
			maxM += c - 1
		}

		if m >= minM && m <= maxM {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

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

package main

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

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

	t := 0
	fmt.Fscanln(in, &t)
	for tcNo := 1; tcNo <= t; tcNo++ {
		a, b, c, m := 0, 0, 0, 0
		fmt.Fscanln(in, &a, &b, &c, &m)

		pairsCount := 0
		if a > 1 {
			pairsCount += a - 1
		}
		if b > 1 {
			pairsCount += b - 1
		}
		if c > 1 {
			pairsCount += c - 1
		}
		if pairsCount >= m {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

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

package main

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

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

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

		if a/2+b/2+c/2 >= m {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}


package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	var cf, cm [366]int
	for i := 0; i < n; i++ {
		var g string
		var a, b int
		fmt.Scanf("%s%d%d\n", &g, &a, &b)
		for j := a - 1; j < b; j++ {
			if g[0] == 'M' {
				cm[j]++
			} else {
				cf[j]++
			}
		}
	}
	ans := 0
	for i := 0; i < len(cf); i++ {
		if 2*min(cf[i], cm[i]) > ans {
			ans = 2 * min(cf[i], cm[i])
		}
	}
	fmt.Println(ans)
}

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

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	male := make([]int, 366)
	female := make([]int, 366)
	for i := 0; i < n; i++ {
		var g string
		var a, b int
		fmt.Scan(&g, &a, &b)
		s := male
		if g == "F" {
			s = female
		}
		for j := a - 1; j < b; j++ {
			s[j]++
		}
	}
	ans := 0
	for i := range male {
		min := male[i]
		if female[i] < min {
			min = female[i]
		}
		if ans < min {
			ans = min
		}
	}
	fmt.Println(ans * 2)
}

package main

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

func main() {
	const days_of_year int = 366

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

	days := make([][2]int, days_of_year+1)

	reader := bufio.NewReader(os.Stdin)
	re := regexp.MustCompile(`\r?\n`)
	for i := 0; i < n; i++ {
		if s, err := reader.ReadString('\n'); err != nil {
			if err == io.EOF {
				break
			}
			return
		} else {
			s = re.ReplaceAllString(s, "")

			idx := 0 // 0 for Female
			if s[0] == 'M' {
				idx = 1
			}

			ss := strings.Split(s, " ")
			if len(ss) != 3 {
				return
			}

			start, err := strconv.Atoi(ss[1])
			if err != nil {
				return
			}
			end, err := strconv.Atoi(ss[2])
			if err != nil {
				return
			}

			for j := start; j <= end; j++ {
				days[j][idx] += 1
			}
		}
	}

	max_half := 0
	for i := 1; i <= days_of_year; i++ {
		m := min(days[i][0], days[i][1])
		if m > max_half {
			max_half = m
		}
	}

	fmt.Println(max_half * 2)
}

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

package main

import "fmt"

func main() {
  var n int

  fmt.Scanf("%d\n", &n)

  males := [367]int{}
  females := [367]int{}

  var a, b int
  var g string

  for i := 0; i < n; i++ {
    fmt.Scanf("%s %d %d\n", &g, &a, &b)
    if g == "F" {
      for j := a; j <= b; j++ {
        females[j]++
      }
    } else {
      for j := a; j <= b; j++ {
        males[j]++
      }
    }
  }

  var maxVal int = 0
  for i := 0; i < 367; i++ {
    localMin := 5001
    if males[i] < females[i] {
      localMin = males[i]
    } else {
      localMin = females[i]
    }

    if maxVal < localMin {
      maxVal = localMin
    }
  }

  fmt.Println(maxVal * 2)
}

package main

import "fmt"

var n int

type Node struct {
	sex byte
	a, b int
}
var l []Node

func gao(d int) int {
	f := 0
	m := 0
	for _, v := range l {
		if v.a <= d && d <= v.b {
			if v.sex == 'F' { f++ }
			if v.sex == 'M' { m++ }
		}
	}
	if f < m { return f }
	return m
}

func main() {
	fmt.Scanf("%d\n", &n)
	for i := 0; i < n; i++ {
		var node Node
		fmt.Scanf("%c%d%d\n", &node.sex, &node.a, &node.b)
		l = append(l, node)
	}

	ans := 0
	for d := 1; d <= 366; d++ {
		tmp := gao(d) * 2
		if tmp > ans {
			ans = tmp
		}
	}
	fmt.Println(ans)
}

package main

import "fmt"

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

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

	var gender byte
	var s, e int
	count_m := make([]int, 367, 367)
	count_f := make([]int, 367, 367)

	for i := 0; i < n; i++ {
		fmt.Scanf("%c %d %d\n", &gender, &s, &e)
		if gender == 'M' {
			for j := s; j <= e; j++ {
				count_m[j]++
			}
		} else {
			for j := s; j <= e; j++ {
				count_f[j]++
			}
		}
	}

	ans := 0
	for i := 1; i < 367; i++ {
		m := min(count_m[i], count_f[i])
		if m+m > ans {
			ans = m + m
		}
	}

	fmt.Println(ans)
}

package main

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

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

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

	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < n; i++ {
		if s, err := reader.ReadString('\n'); err != nil {
			if err == io.EOF {
				break
			} else {
				return
			}
		} else {
			for j := 0; j < n; j++ {
				if s[j] == 'C' {
					cake[i][j] = 1
				}
			}
		}
	}

	var pairs int = 0
	for i := 0; i < n; i++ {
		cnt := 0
		for j := 0; j < n; j++ {
			cnt += int(cake[i][j])
		}
		if cnt > 1 {
			pairs += (cnt * (cnt - 1) / 2)
		}
	}
	for i := 0; i < n; i++ {
		cnt := 0
		for j := 0; j < n; j++ {
			cnt += int(cake[j][i])
		}
		if cnt > 1 {
			pairs += (cnt * (cnt - 1) / 2)
		}
	}

	fmt.Println(pairs)
}

package main

import "fmt"

func main() {
  var n int

  fmt.Scanf("%d\n", &n)

  males := [367]int{}
  females := [367]int{}

  var a, b int
  var g string

  for i := 0; i < n; i++ {
    fmt.Scanf("%s %d %d\n", &g, &a, &b)
    if g == "F" {
      for j := a; j <= b; j++ {
        females[j]++
      }
    } else {
      for j := a; j <= b; j++ {
        males[j]++
      }
    }
  }

  var maxVal int = 0
  for i := 0; i < 367; i++ {
    localMax := -1
    if males[i] > females[i] {
      localMax = males[i]
    } else {
      localMax = females[i]
    }

    if localMax > maxVal {
      maxVal = localMax
    }
  }

  fmt.Println(maxVal + 1)
}

package main

import "fmt"

func main() {
  var n int

  fmt.Scanf("%d\n", &n)

  males := [367]int{}
  females := [367]int{}

  var a, b int
  var g string

  for i := 0; i < n; i++ {
    fmt.Scanf("%s %d %d\n", &g, &a, &b)
    if g == "F" {
      for j := a; j <= b; j++ {
        females[j]++
      }
    } else {
      for j := a; j <= b; j++ {
        males[j]++
      }
    }
  }

  var maxVal int = 0
  for i := 0; i < 367; i++ {
    localMax := -1
    if males[i] > females[i] {
      localMax = males[i]
    } else {
      localMax = females[i]
    }

    if localMax > maxVal {
      maxVal = localMax
    }
  }

  fmt.Println(maxVal * 2)
}

package main

import "fmt"

func main() {
  var n int

  fmt.Scanf("%d\n", &n)

  males := [367]int{}
  females := [367]int{}

  var a, b int
  var g string

  for i := 0; i < n; i++ {
    fmt.Scanf("%s %d %d\n", &g, &a, &b)
    if g == "F" {
      for j := a; j <= b; j++ {
        females[j]++
      }
    } else {
      for j := a; j <= b; j++ {
        males[j]++
      }
    }
  }

  var maxVal int = 0
  for i := 0; i < 367; i++ {
    if males[i] != females[i] {
      continue
    }

    if maxVal < males[i] {
      maxVal = males[i]
    }
  }

  fmt.Println(maxVal * 2)
}

package main

import "fmt"

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

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

	var gender byte
	var s, e int
	count_m := make([]int, 367, 367)
	count_f := make([]int, 367, 367)

	for i := 0; i < n; i++ {
		fmt.Scanf("%c %d %d", &gender, &s, &e)
		if gender == 'M' {
			for j := s; j <= e; j++ {
				count_m[j]++
			}
		} else {
			for j := s; j <= e; j++ {
				count_f[j]++
			}
		}
	}

	ans := 0
	for i := 1; i < 367; i++ {
		m := min(count_m[i], count_f[i])
		if m+m > ans {
			ans = m + m
		}
	}

	fmt.Println(ans)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	var cf, cm [366]int
	for i := 0; i < n; i++ {
		var g string
		var a, b int
		fmt.Scanf("%s%d%d\n", &g, &a, &b)
		for j := a - 1; j < b; j++ {
			if g[0] == 'M' {
				cm[j]++
			} else {
				cf[j]++
			}
		}
	}
	ans := 0
	for i := 0; i < len(cf); i++ {
		if cf[i] == cm[i] && 2*cf[i] > ans {
			ans = 2 * cf[i]
		}
	}
	fmt.Println(ans)
}


package main

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

var scanner *bufio.Scanner

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

type Block struct {
  Pos, Size int
}
type Blocks []*Block
func (blocks Blocks) Len() int {
  return len(blocks)
}
func (blocks Blocks) Swap(i, j int) {
  blocks[i], blocks[j] = blocks[j], blocks[i]
}
func (blocks Blocks) Less(i, j int) bool {
  return blocks[i].Pos < blocks[j].Pos
}

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

  var q, n int
  line, _ := reader.ReadString('\n')
  fmt.Sscanf(line, "%d %d", &q, &n)
  free := map[int]int{ 0: n }
  reserved := map[int]*Block{}
  lastId := 0
  for qi := 0; qi < q; qi++ {
    line, _ = reader.ReadString('\n')
    tokens := strings.Split(strings.TrimSpace(line), " ")
    //--- Allocate a block
    if tokens[0] == "alloc" {
      size, _ := strconv.Atoi(tokens[1])
      allocated := false
      for pos := 0; pos < n; pos++ {
        if free[pos] >= size {
          lastId++
          block := Block{ pos, size }
          reserved[lastId] = &block
          //writer.WriteString(fmt.Sprintf("allocated: pos = %d, size = %d\n",
          //    block.Pos, block.Size))
          free[pos+size] = free[pos]-size
          free[pos] = 0
          allocated = true
          break
        }
      }
      if !allocated {
        writer.WriteString("NULL\n")
      } else {
        writer.WriteString(fmt.Sprintf("%d\n", lastId))
      }
    //--- Erase a block
    } else if tokens[0] == "erase" {
      id, _ := strconv.Atoi(tokens[1])
      block, found := reserved[id]
      if !found {
        writer.WriteString("ILLEGAL_ERASE_ARGUMENT\n")
      } else {
        delete(reserved, id)
        tail := block.Pos + block.Size
        block.Size += free[tail]
        free[tail] = 0
        head := block.Pos
        for pos := head-1; pos >= 0; pos-- {
          if pos+free[pos] == head {
            head = pos
            block.Size += free[head]
            break
          }
        }
        free[head] = block.Size
        //writer.WriteString(fmt.Sprintf("freed: pos = %d, size = %d\n",
        //    head, block.Size))
      }
    //--- Shift blocks to the left
    } else {
      blocks := []*Block{}
      for _, block := range reserved {
        blocks = append(blocks, block)
      }
      sort.Sort(Blocks(blocks))
      tail := 0
      for _, block := range blocks {
        free[block.Pos + block.Size] = 0
        block.Pos = tail
        tail += block.Size
      }
      free[tail] = n-tail
    }
  }
}

package main

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

type block struct {
	i, sz int
}
func main() {
	t, m, s := nextInt(), nextInt(), 1
	mem := make([]*block, 1)
	mem[0] = &block{0, m}
	for i := 0; i < t; i++ {
		op := nextWord()
		switch op {
		case "defragment":
			newMem := make([]*block, 0)
			sz := 0
			for _, b := range mem {
				if b.i != 0 {
					sz += b.sz
					newMem = append(newMem, b)
				}
			}
			if m - sz > 0 {
				mem = append(newMem, &block{0, m - sz})
			}
		case "alloc":
			sz, _ := strconv.Atoi(nextWord())
			allocated := false
			for i, b := range mem {
				if b.i == 0 && b.sz >= sz {
					allocated = true
					b.sz -= sz
					newMem := make([]*block, i)
					copy(newMem, mem)
					newMem = append(newMem, &block{s, sz})
					if b.sz > 0 {
						mem = append(newMem, mem[i:]...)
					} else {
						mem = append(newMem, mem[i + 1:]...)
					}
					printf("%d\n", s)
					s++
					break
				}
			}
			if !allocated {
				printf("NULL\n")
			}
		case "erase":
			idx, _ := strconv.Atoi(nextWord())
			deleted := false
			for i, b := range mem {
				if idx == 0 {
					break
				}
				if b.i == idx {
					deleted = true
					b.i = 0
					if i > 0 && mem[i - 1].i == 0 {
						mem[i - 1].sz += b.sz
						mem = append(mem[:i], mem[i + 1:]...)
					} else if len(mem) > i + 1 && mem[i + 1].i == 0 {
						mem[i + 1].sz += b.sz
						mem = append(mem[:i], mem[i + 1:]...)
					}
				}
			}
			if !deleted {
				printf("ILLEGAL_ERASE_ARGUMENT\n")
			}
		}
	}
}

var lineScanner *Scanner
var wordScanner *Scanner

func init() {
	lineScanner = NewScanner(os.Stdin)
	wordScanner = NewScanner(strings.NewReader(""))
	wordScanner.Split(ScanWords)
}

func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Split functions

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

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

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

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

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

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

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

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

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

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

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

package main

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

func isFitBetween(list []int, size int, amount int) (int,int) {
	counter := 0
	starter := 0

	for i := 0; i < size; i++ {
		if list[i] == 0 {
			counter++
		} else {
			starter = i + 1
			counter = 0
		}

		if counter == amount {
			return starter, i
		}
	}

	return -1,-1
}

func firstEmpty(list []int, size int) int {
	last := -1
	for i := size - 1; i >= 0; i-- {
		if list[i] == 0 {
			last = i
		} else {
			break
		}
	}
	return last
}

func mark(list []int, size int, number int, start int, amount int) []int {
	for i := start; i < start + amount; i++ {
		list[i] = number
	}
	return list
}

func delete(list []int, size int, number int) []int {
	resulter := false
	for i := 0; i < size; i++ {
		if list[i] == number {
			list[i] = 0
			resulter = true
		}
	}

	if number < 1 || resulter == false {
		fmt.Println("ILLEGAL_ERASE_ARGUMENT")
	}

	return list
}

func swap(list []int, size int, swap1 int, swap2 int) []int {
	temp := list[swap1]
	list[swap1] = list[swap2]
	list[swap2] = temp

	return list
}

func defragment(list []int, size int) []int {
	counter := true

	for counter {
		counter = false
		for i := 0; i < size - 1; i++ {
			if list[i] == 0 && list[i + 1] != 0 {
				list = swap(list, size, i, i+1)
				counter = true
			}
		}
	}

	return list
}

func main() {
	bio := bufio.NewReader(os.Stdin)
	input1, _, _ := bio.ReadLine()
	firstLineArray := strings.Split(string(input1), " ")

	lineCount,_ := strconv.Atoi(firstLineArray[0])
	size,_ := strconv.Atoi(firstLineArray[1])

	identifier := 0

	list := make([]int, size)

	inputList := make([]string, lineCount)

	for i := 0; i < size; i++ {
		list[i] = 0
	}

	for i := 0; i < lineCount; i++ {
		input, _, _ := bio.ReadLine()
		inputList[i] = string(input)
	}

	for i := 0; i < lineCount; i++ {
		inputSplit := strings.Split(inputList[i], " ")

		if inputSplit[0] == "alloc" {
			alloc, _ := strconv.Atoi(inputSplit[1])

			isFit1, isFit2 := isFitBetween(list, size, alloc)

			if isFit1 == -1 || isFit2 == -1 {
				fmt.Println("NULL")
			} else {
				identifier++
				list = mark(list, size, identifier, isFit1, alloc)
				fmt.Println(identifier)
			}
		} else if inputSplit[0] == "erase" {
			erase, _ := strconv.Atoi(inputSplit[1])

			list = delete(list, size, erase)
		} else if inputSplit[0] == "defragment" {
			list = defragment(list, size)
		}
	}
}

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

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]*Node
	p    int
	tot  int
}

func NewManager(m int) Manager {
	free := new(Node)
	free.next = NewNode(0, m)
	used := new(Node)
	mem := make(map[int]*Node)
	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
		tmp.next = nil
		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] = tmp2
	tmp2.id = this.p

	return this.p
}

func (this *Manager) Erase(x int) bool {
	if node, 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 != node {
			head = head.next
		}

		if head.next == nil {
			return false
		}

		head.next = node.next
		node.next = nil
		// put back as free
		head = this.free

		for head.next != nil && head.next.pos < node.pos {
			head = head.next
		}
		// head.pos < pos && ( head.next == nil || head.next.pos > pos)

		node.id = -1
		node.next = head.next
		head.next = node

		if head == this.free {
			head = head.next
		}

		for head.next != nil && head.pos+head.sz == head.next.pos {
			head.sz += head.next.sz
			head.next = head.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
	}
}

package main

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

func solve() {
	t := readInt()
	m := readInt()

	mem := make([]int, m)
	xid := 1

	for i := 0; i < t; i++ {
		op := readString()
		if op == "alloc" {
			id := readInt()
			cnt := 0
			idx := 0
			for i, v := range mem {
				if v == 0 {
					if cnt == 0 {
						idx = i
					}
					cnt++
					if cnt == id {
						break
					}
				} else {
					cnt = 0
				}
			}
			if cnt == id {
				for i := 0; i < id; i++ {
					mem[idx+i] = xid
				}
				fmt.Println(xid)
				xid++
			} else {
				fmt.Println("NULL")
			}
		} else if op == "erase" {
			found := false
			id := readInt()
			if id <= 0 {
				fmt.Println("ILLEGAL_ERASE_ARGUMENT")
				continue
			}

			for i, v := range mem {
				if v == id {
					found = true
					mem[i] = 0
				}
			}
			if !found {
				fmt.Println("ILLEGAL_ERASE_ARGUMENT")
			}
		} else if op == "defragment" {
			nmem := make([]int, m)
			n := 0
			for _, v := range mem {
				if v == 0 {
					continue
				}
				nmem[n] = v
				n++
			}
			mem = nmem
		} else {
			panic(op)
		}
	}
}

var scanner *bufio.Scanner

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

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

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

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

package main

import (
	"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
	}
}

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 true
	} else {
		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
	}
}

package main

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

var scanner *bufio.Scanner

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

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  x, o := getI(), getI()
  xPairs := x/2
  if xPairs > o {
    xPairs = o
  }
  x -= 2*xPairs
  o -= xPairs
  oFours := o/3
  if oFours > xPairs {
    oFours = xPairs
  }
  xPairs -= oFours
  o -= 3*oFours
  teams := xPairs + 2*oFours
  if x > 0 && o > 1 {
    x--
    o -= 2
    teams++
  }
  writer.WriteString(fmt.Sprintf("%d\n", teams))
}

package main

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

type block struct {
	i, sz int
}
func main() {
	t, m, s := nextInt(), nextInt(), 1
	mem := make([]*block, 1)
	mem[0] = &block{0, m}
	for i := 0; i < t; i++ {
		op := nextWord()
		switch op {
		case "defragment":
			newMem := make([]*block, 0)
			sz := 0
			for _, b := range mem {
				if b.i != 0 {
					sz += b.sz
					newMem = append(newMem, b)
				}
			}
			if m - sz > 0 {
				mem = append(newMem, &block{0, m - sz})
			}
		case "alloc":
			sz, _ := strconv.Atoi(nextWord())
			allocated := false
			for i, b := range mem {
				if b.i == 0 && b.sz >= sz {
					allocated = true
					b.sz -= sz
					newMem := make([]*block, i)
					copy(newMem, mem)
					newMem = append(newMem, &block{s, sz})
					if b.sz > 0 {
						mem = append(newMem, mem[i:]...)
					} else {
						mem = append(newMem, mem[i + 1:]...)
					}
					printf("%d\n", s)
					s++
					break
				}
			}
			if !allocated {
				printf("NULL\n")
			}
		case "erase":
			idx, _ := strconv.Atoi(nextWord())
			deleted := false
			for i, b := range mem {
				if b.i == idx {
					deleted = true
					b.i = 0
					if i > 0 && mem[i - 1].i == 0 {
						mem[i - 1].sz += b.sz
						mem = append(mem[:i], mem[i + 1:]...)
					} else if len(mem) > i + 1 && mem[i + 1].i == 0 {
						mem[i + 1].sz += b.sz
						mem = append(mem[:i], mem[i + 1:]...)
					}
				}
			}
			if !deleted {
				printf("ILLEGAL_ERASE_ARGUMENT\n")
			}
		}
	}
}

var lineScanner *Scanner
var wordScanner *Scanner

func init() {
	lineScanner = NewScanner(os.Stdin)
	wordScanner = NewScanner(strings.NewReader(""))
	wordScanner.Split(ScanWords)
}

func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Split functions

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

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

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

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

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

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

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

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

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

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

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

package main

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

func firstEmpty(list []int, size int) int {
	last := -1
	for i := size - 1; i >= 0; i-- {
		if list[i] == 0 {
			last = i
		} else {
			break
		}
	}
	return last
}

func mark(list []int, size int, number int, start int, amount int) []int {
	for i := start; i < start + amount; i++ {
		list[i] = number
	}
	return list
}

func delete(list []int, size int, number int) []int{
	for i := 0; i < size; i++ {
		if list[i] == number {
			list[i] = 0
		}
	}
	return list
}

func swap(list []int, size int, swap1 int, swap2 int) []int {
	temp := list[swap1]
	list[swap1] = list[swap2]
	list[swap2] = temp

	return list
}

func defragment(list []int, size int) []int {
	counter := true

	for counter {
		counter = false
		for i := 0; i < size - 1; i++ {
			if list[i] == 0 && list[i + 1] != 0 {
				list = swap(list, size, i, i+1)
				counter = true
			}
		}
	}

	return list
}

func main() {
	bio := bufio.NewReader(os.Stdin)
	input1, _, _ := bio.ReadLine()
	firstLineArray := strings.Split(string(input1), " ")

	lineCount,_ := strconv.Atoi(firstLineArray[0])
	size,_ := strconv.Atoi(firstLineArray[1])

	identifier := 0

	list := make([]int, size)

	inputList := make([]string, lineCount)

	for i := 0; i < size; i++ {
		list[i] = 0
	}

	for i := 0; i < lineCount; i++ {
		input, _, _ := bio.ReadLine()
		inputList[i] = string(input)
	}

	for i := 0; i < lineCount; i++ {
		inputSplit := strings.Split(inputList[i], " ")

		if inputSplit[0] == "alloc" {
			alloc, _ := strconv.Atoi(inputSplit[1])

			firstEmptyIndex := firstEmpty(list, size)

			if firstEmptyIndex == -1 || size - firstEmptyIndex < alloc {
				fmt.Println("NULL")
			} else {
				identifier++
				list = mark(list, size, identifier, firstEmptyIndex, alloc)
				fmt.Println(identifier)
			}
		} else if inputSplit[0] == "erase" {
			erase, _ := strconv.Atoi(inputSplit[1])

			list = delete(list, size, erase)
		} else if inputSplit[0] == "defragment" {
			list = defragment(list, size)
		}
	}
}

package main

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

func firstEmpty(list []int, size int) int {
	last := -1
	for i := size - 1; i >= 0; i-- {
		if list[i] == 0 {
			last = i
		} else {
			break
		}
	}
	return last
}

func mark(list []int, size int, number int, start int, amount int) []int {
	for i := start; i < start + amount; i++ {
		list[i] = number
	}
	return list
}

func delete(list []int, size int, number int) []int {
	resulter := false
	for i := 0; i < size; i++ {
		if list[i] == number {
			list[i] = 0
			resulter = true
		}
	}

	if resulter == false {
		fmt.Println("ILLEGAL_ERASE_ARGUMENT")
	}

	return list
}

func swap(list []int, size int, swap1 int, swap2 int) []int {
	temp := list[swap1]
	list[swap1] = list[swap2]
	list[swap2] = temp

	return list
}

func defragment(list []int, size int) []int {
	counter := true

	for counter {
		counter = false
		for i := 0; i < size - 1; i++ {
			if list[i] == 0 && list[i + 1] != 0 {
				list = swap(list, size, i, i+1)
				counter = true
			}
		}
	}

	return list
}

func main() {
	bio := bufio.NewReader(os.Stdin)
	input1, _, _ := bio.ReadLine()
	firstLineArray := strings.Split(string(input1), " ")

	lineCount,_ := strconv.Atoi(firstLineArray[0])
	size,_ := strconv.Atoi(firstLineArray[1])

	identifier := 0

	list := make([]int, size)

	inputList := make([]string, lineCount)

	for i := 0; i < size; i++ {
		list[i] = 0
	}

	for i := 0; i < lineCount; i++ {
		input, _, _ := bio.ReadLine()
		inputList[i] = string(input)
	}

	for i := 0; i < lineCount; i++ {
		inputSplit := strings.Split(inputList[i], " ")

		if inputSplit[0] == "alloc" {
			alloc, _ := strconv.Atoi(inputSplit[1])

			firstEmptyIndex := firstEmpty(list, size)

			if firstEmptyIndex == -1 || size - firstEmptyIndex < alloc {
				fmt.Println("NULL")
			} else {
				identifier++
				list = mark(list, size, identifier, firstEmptyIndex, alloc)
				fmt.Println(identifier)
			}
		} else if inputSplit[0] == "erase" {
			erase, _ := strconv.Atoi(inputSplit[1])

			list = delete(list, size, erase)
		} else if inputSplit[0] == "defragment" {
			list = defragment(list, size)
		}
	}
}

package main

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

func isFitBetween(list []int, size int, amount int) (int,int) {
	counter := 0
	starter := 0

	for i := 0; i < size; i++ {
		if list[i] == 0 {
			counter++
		} else {
			starter = i + 1
			counter = 0
		}

		if counter == amount {
			return starter, i
		}
	}

	return -1,-1
}

func firstEmpty(list []int, size int) int {
	last := -1
	for i := size - 1; i >= 0; i-- {
		if list[i] == 0 {
			last = i
		} else {
			break
		}
	}
	return last
}

func mark(list []int, size int, number int, start int, amount int) []int {
	for i := start; i < start + amount; i++ {
		list[i] = number
	}
	return list
}

func delete(list []int, size int, number int) []int {
	resulter := false
	for i := 0; i < size; i++ {
		if list[i] == number {
			list[i] = 0
			resulter = true
		}
	}

	if resulter == false {
		fmt.Println("ILLEGAL_ERASE_ARGUMENT")
	}

	return list
}

func swap(list []int, size int, swap1 int, swap2 int) []int {
	temp := list[swap1]
	list[swap1] = list[swap2]
	list[swap2] = temp

	return list
}

func defragment(list []int, size int) []int {
	counter := true

	for counter {
		counter = false
		for i := 0; i < size - 1; i++ {
			if list[i] == 0 && list[i + 1] != 0 {
				list = swap(list, size, i, i+1)
				counter = true
			}
		}
	}

	return list
}

func main() {
	bio := bufio.NewReader(os.Stdin)
	input1, _, _ := bio.ReadLine()
	firstLineArray := strings.Split(string(input1), " ")

	lineCount,_ := strconv.Atoi(firstLineArray[0])
	size,_ := strconv.Atoi(firstLineArray[1])

	identifier := 0

	list := make([]int, size)

	inputList := make([]string, lineCount)

	for i := 0; i < size; i++ {
		list[i] = 0
	}

	for i := 0; i < lineCount; i++ {
		input, _, _ := bio.ReadLine()
		inputList[i] = string(input)
	}

	for i := 0; i < lineCount; i++ {
		inputSplit := strings.Split(inputList[i], " ")

		if inputSplit[0] == "alloc" {
			alloc, _ := strconv.Atoi(inputSplit[1])

			isFit1, isFit2 := isFitBetween(list, size, alloc)

			if isFit1 == -1 || isFit2 == -1 {
				fmt.Println("NULL")
			} else {
				identifier++
				list = mark(list, size, identifier, isFit1, alloc)
				fmt.Println(identifier)
			}
		} else if inputSplit[0] == "erase" {
			erase, _ := strconv.Atoi(inputSplit[1])

			list = delete(list, size, erase)
		} else if inputSplit[0] == "defragment" {
			list = defragment(list, size)
		}
	}
}

package main

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

func firstEmpty(list []int, size int) int {
	last := -1
	for i := size - 1; i >= 0; i-- {
		if list[i] == 0 {
			last = i
		} else {
			break
		}
	}
	return last
}

func mark(list []int, size int, number int, start int, amount int) []int {
	for i := start; i < start + amount; i++ {
		list[i] = number
	}
	return list
}

func delete(list []int, size int, number int) []int {
	resulter := false
	for i := 0; i < size; i++ {
		if list[i] == number {
			list[i] = 0
			resulter = true
		}
	}

	if resulter == false {
		fmt.Println("ILLEGAL_ERASE_ARGUMENT")
	}

	return list
}

func swap(list []int, size int, swap1 int, swap2 int) []int {
	temp := list[swap1]
	list[swap1] = list[swap2]
	list[swap2] = temp

	return list
}

func getNextIdentifier(list []int, size int) int {
	maxValue := list[0]

	for i := 1; i < size; i++ {
		if maxValue < list[i] {
			maxValue = list[i]
		}
	}

	return maxValue + 1
}

func defragment(list []int, size int) []int {
	counter := true

	for counter {
		counter = false
		for i := 0; i < size - 1; i++ {
			if list[i] == 0 && list[i + 1] != 0 {
				list = swap(list, size, i, i+1)
				counter = true
			}
		}
	}

	return list
}

func main() {
	bio := bufio.NewReader(os.Stdin)
	input1, _, _ := bio.ReadLine()
	firstLineArray := strings.Split(string(input1), " ")

	lineCount,_ := strconv.Atoi(firstLineArray[0])
	size,_ := strconv.Atoi(firstLineArray[1])

	list := make([]int, size)

	inputList := make([]string, lineCount)

	for i := 0; i < size; i++ {
		list[i] = 0
	}

	for i := 0; i < lineCount; i++ {
		input, _, _ := bio.ReadLine()
		inputList[i] = string(input)
	}

	for i := 0; i < lineCount; i++ {
		inputSplit := strings.Split(inputList[i], " ")

		if inputSplit[0] == "alloc" {
			alloc, _ := strconv.Atoi(inputSplit[1])

			firstEmptyIndex := firstEmpty(list, size)

			if firstEmptyIndex == -1 || size - firstEmptyIndex < alloc {
				fmt.Println("NULL")
			} else {
				identifier := getNextIdentifier(list, size)
				list = mark(list, size, identifier, firstEmptyIndex, alloc)
				fmt.Println(identifier)
			}
		} else if inputSplit[0] == "erase" {
			erase, _ := strconv.Atoi(inputSplit[1])

			list = delete(list, size, erase)
		} else if inputSplit[0] == "defragment" {
			list = defragment(list, size)
		}
	}
}