package main

import (
          "fmt"
          "os"
          "bufio"
          //"time"
       )

func main() {
    //ts := time.Now()
    var n, b, t, d int
    in := bufio.NewReader(os.Stdin)
    out := bufio.NewWriter(os.Stdout)
    defer out.Flush()
    fmt.Fscanf(in, "%d %d\n", &n, &b)
    fmt.Fscanf(in, "%d %d\n", &t, &d)
    currentFirst := 0
    currentLast := 1
    qCount := 1
    var finishTimes [200100]int64
    finishTimes[0] = int64(t + d)
    fmt.Fprintf(out, "%v ", t+d)
    //fmt.Printf("%v ", t+d)
    for i := 1; i < n; i++ {
        fmt.Fscanf(in, "%d %d\n", &t, &d)
        for (int64(t) >= finishTimes[currentFirst]) && (currentFirst < i) {
            currentFirst += 1
            qCount -= 1
        }
        if qCount > b {
            //fmt.Printf("-1 ")
            fmt.Fprintf(out, "-1 ")
            continue
        }
        if currentFirst == i {
            finishTimes[currentLast] = int64(t + d)
        } else {
            finishTimes[currentLast] = finishTimes[currentLast-1] + int64(d)
        }
        //fmt.Printf("%v ", finishTimes[currentLast])
        fmt.Fprintf(out, "%v ", finishTimes[currentLast])
        qCount += 1
        currentLast += 1
    }
    //tf := time.Now()
    //fmt.Printf("\nThe running time = %v\n", tf.Sub(ts))
}

package main

import (
          "fmt"
          "os"
          "bufio"
          //"time"
       )

func main() {
    //ts := time.Now()
    var n, b, t, d int
    in := bufio.NewReader(os.Stdin)
    //out := bufio.NewWriter(os.Stdout)
    fmt.Fscanf(in, "%d %d\n", &n, &b)
    fmt.Fscanf(in, "%d %d\n", &t, &d)
    currentFirst := 0
    currentLast := 1
    qCount := 1
    var finishTimes [200100]int64
    finishTimes[0] = int64(t + d)
    //fmt.Fprintf(out, "%v ", t+d)
    fmt.Printf("%v ", t+d)
    for i := 1; i < n; i++ {
        fmt.Fscanf(in, "%d %d\n", &t, &d)
        for (int64(t) >= finishTimes[currentFirst]) && (currentFirst < i) {
            currentFirst += 1
            qCount -= 1
        }
        if qCount > b {
            fmt.Printf("-1 ")
            continue
        }
        if currentFirst == i {
            finishTimes[currentLast] = int64(t + d)
        } else {
            finishTimes[currentLast] = finishTimes[currentLast-1] + int64(d)
        }
        fmt.Printf("%v ", finishTimes[currentLast])
        qCount += 1
        currentLast += 1
    }
    //tf := time.Now()
    //fmt.Printf("\nThe running time = %v\n", tf.Sub(ts))
}

package main

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

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func ReadInt32() int {
	scanner.Scan()
	ans, _ := strconv.Atoi(scanner.Text())
	return ans
}

func PrintInts(ints ...int) {
	for _, value := range ints {
		writer.WriteString(strconv.Itoa(value))
		writer.WriteByte(' ')
	}
}

func PrintInt64s(ints ...int64) {
	for _, value := range ints {
		s := strconv.FormatInt(value, 10)
		writer.WriteString(s)
		writer.WriteByte(' ')
	}
}

type arr struct {
	data             []int
	fidx, nidx, size int
}

func newArr(sz int) arr {
	return arr{
		data: make([]int, sz, sz),
		fidx: 0,
		nidx: 0,
		size: 0,
	}
}

func (a *arr) add(v int) bool {
	if a.size == len(a.data) {
		return false
	}
	a.data[a.nidx] = v
	a.size++
	a.nidx = ((a.nidx + 1) % len(a.data))
	return true
}

func (a *arr) get() int {
	v := a.data[a.fidx]
	a.fidx = ((a.fidx + 1) % len(a.data))
	a.size--
	return v
}

func (a *arr) remove() {
	a.fidx = ((a.fidx + 1) % len(a.data))
	a.size--
}

func (a *arr) firstval() int {
	if a.size > 0 {
		return a.data[a.fidx]
	} else {
		return -1
	}
}

const bigtm = 100000000 * 1000000001

func main() {
	defer writer.Flush()           // очищает буфер при выходе из функции main
	scanner.Split(bufio.ScanWords) // заставляет scanner считать отдельными токенами слова, разделенные пробелами
	rnum := ReadInt32()
	qsz := ReadInt32()

	queue := newArr(qsz)
	rejected := newArr(rnum)
	proc := false
	var tcur, tfin, treq int64
	var dreq int

	treq = int64(ReadInt32())
	dreq = ReadInt32()

	num := 1
	finished := 1
	for treq < bigtm || proc {
		if proc {
			if treq < tfin {
				if !queue.add(dreq) {
					rejected.add(num)
				}
				if num < rnum {
					treq = int64(ReadInt32())
					dreq = ReadInt32()
					num++
				} else {
					treq = bigtm
				}
			} else {
				PrintInt64s(tfin)
				finished++
				for rejected.firstval() == finished {
					PrintInts(-1)
					rejected.remove()
					finished++
				}
				tcur = tfin
				if queue.size > 0 {
					tfin = tcur + int64(queue.get())
				} else {
					proc = false
				}
			}
		} else {
			tcur = treq
			tfin = tcur + int64(dreq)
			proc = true
			if num < rnum {
				treq = int64(ReadInt32())
				dreq = ReadInt32()
				num++
			} else {
				treq = bigtm
			}
		}
	}
	for j := 0; j < rejected.size; j++ {
		PrintInts(-1)
	}
}

package main

import (
	"bufio"
	"container/list"
	"os"
	"strconv"
)

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)

	var n, b int = readInt(), readInt()
	b++
	var t, d int64
	res := make([]int64, n)
	q := list.New()
	for i := 0; i < n; i++ {
		t, d = readInt64(), readInt64()

		if i == 0 {
			res[i] = t + d
			q.PushBack(res[i])
			continue
		}

		// clear queue from finished tasks
		var next *list.Element
		for e := q.Front(); q.Len() > 0 && e != nil && e.Value.(int64) <= t; e = next {
			next = e.Next()
			q.Remove(e)
		}
		if q.Len() >= b {
			res[i] = -1
		} else if q.Len() == 0 {
			res[i] = t + d
			q.PushBack(res[i])
		} else {
			res[i] = q.Back().Value.(int64) + d
			q.PushBack(res[i])
		}
	}
	for _, v := range res {
		printInt64s(v)
	}
	println()
}

var (
	sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr *bufio.Writer  = bufio.NewWriter(os.Stdout)
)

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

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

func printInts(ints ...int) {
	for _, v := range ints {
		wr.WriteString(strconv.Itoa(v))
		wr.WriteByte(' ')
	}
}
func printInt64s(ints ...int64) {
	for _, v := range ints {
		wr.WriteString(strconv.FormatInt(v, 10))
		wr.WriteByte(' ')
	}
}

func readStr() string {
	sc.Scan()
	return sc.Text()
}

func println() {
	wr.WriteByte('\n')
}

package main

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

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

	var n, b int
	fmt.Fscanf(in, "%d %d\n", &n, &b)

	T := make([]int64, n)
	D := make([]int64, n)
	F := make([]int64, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d %d\n", &T[i], &D[i])
	}

	c := 0
	k := -1

	for i := 0; i < n; {
		t := int64(0)
		if k != -1 {
			t = F[k]
		}

		if t > T[i] {
			if c < b {
				c++

				j := i - 1
				for ; F[j] == -1; j-- {

				}
				F[i] = F[j] + D[i]
			} else {
				F[i] = -1
			}
			i++
		} else {
			if c > 0 {
				for k += 1; F[k] == -1; k++ {
				}
				c--
			} else {
				F[i] = T[i] + D[i]
				k = i
				i++
			}
		}
	}

	for i := 0; i < n; i++ {
		fmt.Printf("%d%s", F[i], " ")
	}

}

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"io"
	"os"
)

func Abs(x int) int {
	switch {
	case x < 0:
		return -x
	case x == 0:
		return 0
	}
	return x
}

func Max(a int64, b int64) int64 {
	if a < b {
		return b
	}
	return a
}

func Scan(args ...interface{}) (e error)             { _, e = fmt.Fscan(in, args...); return }
func Scanf(ft string, args ...interface{}) (e error) { _, e = fmt.Fscanf(in, ft, args...); return }
func Scanln(args ...interface{}) (e error)           { _, e = fmt.Fscanln(in, args...); return }
func Print(args ...interface{})                      { out.WriteString(fmt.Sprint(args...)) }
func Printf(ft string, args ...interface{})          { out.WriteString(fmt.Sprintf(ft, args...)) }
func Println(args ...interface{})                    { out.WriteString(fmt.Sprintln(args...)) }

var (
	//dataIn = "data.in"
	in     = bufio.NewReader(os.Stdin)
	//in, _ = os.Open(dataIn)
	out   = bufio.NewWriter(os.Stdout)
)

type Job struct {
	id     int
	ti, di int64
}

var n, b int

func solve() {
	qu := list.New()
	pre := -1
	cur := &Job{-1, 0, 0}
	for i := 0; i < n; i++ {
		job := Job{id: i}
		Scan(&job.ti, &job.di)

		if cur.id != -1 {
			if cur.ti+cur.di <= job.ti {
				for i := pre + 1; i < cur.id; i++ {
					Print("-1 ")
				}
				Printf("%d ", cur.ti+cur.di)
				pre = cur.id
				cur.id = -1
			}
		}
		if (cur.id == -1 && qu.Len() <= b) || (cur.id != -1 && qu.Len() < b) {
			qu.PushBack(&job)
		}
		if cur.id == -1 && qu.Len() > 0 {
			iJob := qu.Front()
			now := cur.ti + cur.di
			cur = iJob.Value.(*Job)
			cur.ti = Max(cur.ti, now)
			qu.Remove(iJob)
		}
	}

	for cur.id != -1 {
		for i := pre + 1; i < cur.id; i++ {
			Print("-1 ")
		}
		Printf("%d ", cur.ti+cur.di)
		pre = cur.id
		cur.id = -1
		if qu.Len() > 0 {
			iJob := qu.Front()
			now := cur.ti + cur.di
			cur = iJob.Value.(*Job)
			cur.ti = Max(cur.ti, now)
			qu.Remove(iJob)
		}
	}
	for i := pre + 1; i < n; i++ {
		Print("-1 ")
	}
	Println()
	return
}

func main() {
	defer out.Flush()
	for Scan(&n, &b) != io.EOF {
		solve()
	}
	return
}

package main

import (
          "fmt"
          "os"
          "bufio"
          //"time"
       )

func main() {
    //ts := time.Now()
    var n, b, t, d int
    in := bufio.NewReader(os.Stdin)
    out := bufio.NewWriter(os.Stdout)
    fmt.Fscanf(in, "%d %d\n", &n, &b)
    fmt.Fscanf(in, "%d %d\n", &t, &d)
    currentFirst := 0
    currentLast := 1
    qCount := 1
    var finishTimes [200100]int64
    finishTimes[0] = int64(t + d)
    fmt.Fprintf(out, "%v ", t+d)
    for i := 1; i < n; i++ {
        fmt.Fscanf(in, "%d %d\n", &t, &d)
        for (int64(t) >= finishTimes[currentFirst]) && (currentFirst < i) {
            currentFirst += 1
            qCount -= 1
        }
        if qCount > b {
            fmt.Printf("-1 ")
            continue
        }
        if currentFirst == i {
            finishTimes[currentLast] = int64(t + d)
        } else {
            finishTimes[currentLast] = finishTimes[currentLast-1] + int64(d)
        }
        fmt.Fprintf(out, "%v ", finishTimes[currentLast])
        qCount += 1
        currentLast += 1
    }
    //tf := time.Now()
    //fmt.Printf("\nThe running time = %v\n", tf.Sub(ts))
}

package main

import (
          "fmt"
          "os"
          "bufio"
          //"time"
       )

func main() {
    //ts := time.Now()
    var n, b, t, d int
    in := bufio.NewReader(os.Stdin)
    out := bufio.NewWriter(os.Stdout)
    fmt.Fscanf(in, "%d %d\n", &n, &b)
    fmt.Fscanf(in, "%d %d\n", &t, &d)
    currentFirst := 0
    currentLast := 1
    qCount := 1
    var finishTimes [200100]int64
    finishTimes[0] = int64(t + d)
    fmt.Fprintf(out, "%v ", t+d)
    for i := 1; i < n; i++ {
        fmt.Fscanf(in, "%d %d\n", &t, &d)
        for (int64(t) >= finishTimes[currentFirst]) && (currentFirst < i) {
            currentFirst += 1
            qCount -= 1
        }
        if qCount > b {
            fmt.Fprintf(out, "-1 ")
            continue
        }
        if currentFirst == i {
            finishTimes[currentLast] = int64(t + d)
        } else {
            finishTimes[currentLast] = finishTimes[currentLast-1] + int64(d)
        }
        fmt.Fprintf(out, "%v ", finishTimes[currentLast])
        qCount += 1
        currentLast += 1
    }
    //tf := time.Now()
    //fmt.Printf("\nThe running time = %v\n", tf.Sub(ts))
}

package main

import (
	"fmt"
)

type arr struct {
	data             []int
	fidx, nidx, size int
}

func newArr(sz int) arr {
	return arr{
		data: make([]int, sz),
		fidx: 0,
		nidx: 0,
		size: 0,
	}
}

func (a *arr) add(v int) bool {
	if a.size == len(a.data) {
		return false
	}
	a.data[a.nidx] = v
	a.size++
	a.nidx = (a.nidx + 1) % len(a.data)
	return true
}

func (a *arr) get() int {
	v := a.data[a.fidx]
	a.fidx = (a.fidx + 1) % len(a.data)
	a.size--
	return v
}

func (a *arr) remove() {
	a.fidx = (a.fidx + 1) % len(a.data)
	a.size--
}

func (a *arr) firstval() int {
	return a.data[a.fidx]
}

const bigtm = 2000000001

func main() {
	rnum := 0
	qsz := 0
	fmt.Scanln(&rnum, &qsz)

	queue := newArr(qsz)
	rejected := newArr(rnum)
	proc := false
	var tcur, tfin, treq, dreq int

	fmt.Scanln(&treq, &dreq)

	num := 1
	finished := 1
	for treq < bigtm || proc {
		for rejected.size > 0 && (rejected.firstval() == finished) {
			fmt.Print(-1, " ")
			rejected.remove()
			finished++
		}
		if proc {
			if treq < tfin {
				if !queue.add(dreq) {
					rejected.add(num)
				}
				if num < rnum {
					fmt.Scanln(&treq, &dreq)
					num++
				} else {
					treq = bigtm
				}
			} else {
				fmt.Print(tfin, " ")
				finished++
				tcur = tfin
				if queue.size > 0 {
					tfin = tcur + queue.get()
				} else {
					proc = false
				}
			}
		} else {
			tcur = treq
			tfin = tcur + dreq
			proc = true
			if num < rnum {
				fmt.Scanln(&treq, &dreq)
				num++
			} else {
				treq = bigtm
			}
		}
	}
	for j := 0; j < rejected.size; j++ {
		fmt.Print(-1, " ")
	}
}

package main

import (
	"fmt"
)

type arr struct {
	data             []int
	fidx, nidx, size int
}

func newArr(sz int) arr {
	return arr{
		data: make([]int, sz, sz),
		fidx: 0,
		nidx: 0,
		size: 0,
	}
}

func (a *arr) add(v int) bool {
	if a.size == len(a.data) {
		return false
	}
	a.data[a.nidx] = v
	a.size++
	a.nidx = ((a.nidx + 1) % len(a.data))
	return true
}

func (a *arr) get() int {
	v := a.data[a.fidx]
	a.fidx = ((a.fidx + 1) % len(a.data))
	a.size--
	return v
}

func (a *arr) remove() {
	a.fidx = ((a.fidx + 1) % len(a.data))
	a.size--
}

func (a *arr) firstval() int {
	if a.size > 0 {
		return a.data[a.fidx]
	} else {
		return -1
	}
}

const bigtm = 2000000001

func main() {
	rnum := 0
	qsz := 0
	fmt.Scanln(&rnum, &qsz)

	queue := newArr(qsz)
	rejected := newArr(rnum)
	proc := false
	var tcur, tfin, treq, dreq int

	fmt.Scanln(&treq, &dreq)

	num := 1
	finished := 1
	for treq < bigtm || proc {
		if proc {
			if treq < tfin {
				if !queue.add(dreq) {
					rejected.add(num)
				}
				if num < rnum {
					fmt.Scanln(&treq, &dreq)
					num++
				} else {
					treq = bigtm
				}
			} else {
				fmt.Print(tfin, " ")
				finished++
				for rejected.firstval() == finished {
					fmt.Print(-1, " ")
					rejected.remove()
					finished++
				}
				tcur = tfin
				if queue.size > 0 {
					tfin = tcur + queue.get()
				} else {
					proc = false
				}
			}
		} else {
			tcur = treq
			tfin = tcur + dreq
			proc = true
			if num < rnum {
				fmt.Scanln(&treq, &dreq)
				num++
			} else {
				treq = bigtm
			}
		}
	}
	for j := 0; j < rejected.size; j++ {
		fmt.Print(-1, " ")
	}
}

package main

import (
	"fmt"
)

type arr struct {
	data             []int
	fidx, nidx, size int
}

func newArr(sz int) arr {
	return arr{
		data: make([]int, sz),
		fidx: 0,
		nidx: 0,
		size: 0,
	}
}

func (a *arr) add(v int) bool {
	if a.size == len(a.data) {
		return false
	}
	a.data[a.nidx] = v
	a.size++
	a.nidx = ((a.nidx + 1) % len(a.data))
	return true
}

func (a *arr) get() int {
	v := a.data[a.fidx]
	a.fidx = ((a.fidx + 1) % len(a.data))
	a.size--
	return v
}

func (a *arr) remove() {
	a.fidx = ((a.fidx + 1) % len(a.data))
	a.size--
}

func (a *arr) firstval() int {
	return a.data[a.fidx]
}

const bigtm = 2000000001

func main() {
	rnum := 0
	qsz := 0
	fmt.Scanln(&rnum, &qsz)

	queue := newArr(qsz)
	rejected := newArr(rnum)
	proc := false
	var tcur, tfin, treq, dreq int

	fmt.Scanln(&treq, &dreq)

	num := 1
	finished := 1
	for treq < bigtm || proc {
		for rejected.size > 0 && (rejected.firstval() == finished) {
			fmt.Print(-1, " ")
			rejected.remove()
			finished++
		}
		if proc {
			if treq < tfin {
				if !queue.add(dreq) {
					rejected.add(num)
				}
				if num < rnum {
					fmt.Scanln(&treq, &dreq)
					num++
				} else {
					treq = bigtm
				}
			} else {
				fmt.Print(tfin, " ")
				finished++
				tcur = tfin
				if queue.size > 0 {
					tfin = tcur + queue.get()
				} else {
					proc = false
				}
			}
		} else {
			tcur = treq
			tfin = tcur + dreq
			proc = true
			if num < rnum {
				fmt.Scanln(&treq, &dreq)
				num++
			} else {
				treq = bigtm
			}
		}
	}
	for j := 0; j < rejected.size; j++ {
		fmt.Print(-1, " ")
	}
}

package main

import (
	"fmt"
)

type arr struct {
	data             []int
	fidx, nidx, size int
}

func newArr(sz int) arr {
	return arr{
		data: make([]int, sz),
		fidx: 0,
		nidx: 0,
		size: 0,
	}
}

func (a *arr) add(v int) bool {
	if a.size == len(a.data) {
		return false
	}
	a.data[a.nidx] = v
	a.nidx++
	a.size++
	if a.nidx == len(a.data) {
		a.nidx = 0
	}
	return true
}

func (a *arr) get() int {
	v := a.data[a.fidx]
	a.fidx++
	a.size--
	if a.fidx == len(a.data) {
		a.fidx = 0
	}
	return v
}

func (a *arr) remove() {
	a.fidx++
	a.size--
	if a.fidx == len(a.data) {
		a.fidx = 0
	}
}

func (a *arr) firstval() int {
	return a.data[a.fidx]
}

const bigtm = 2000000001

func main() {
	rnum := 0
	qsz := 0
	fmt.Scanln(&rnum, &qsz)

	queue := newArr(qsz)
	rejected := newArr(rnum)
	proc := false
	var tcur, tfin, treq, dreq int

	fmt.Scanln(&treq, &dreq)

	num := 1
	finished := 1
	for treq < bigtm || proc {
		for rejected.size > 0 && (rejected.firstval() == finished+1) {
			fmt.Print(-1, " ")
			rejected.remove()
			finished++
		}
		if proc {
			if treq < tfin {
				if !queue.add(dreq) {
					rejected.add(num)
				}
				if num < rnum {
					fmt.Scanln(&treq, &dreq)
					num++
				} else {
					treq = bigtm
				}
			} else {
				fmt.Print(tfin, " ")
				finished++
				tcur = tfin
				if queue.size > 0 {
					tfin = tcur + queue.get()
				} else {
					proc = false
				}
			}
		} else {
			tcur = treq
			tfin = tcur + dreq
			proc = true
			if num < rnum {
				fmt.Scanln(&treq, &dreq)
				num++
			} else {
				treq = bigtm
			}
		}
	}
	for j := 0; j < rejected.size; j++ {
		fmt.Print(-1, " ")
	}
}

package main

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

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

	var n, b int
	fmt.Fscanf(in, "%d %d\n", &n, &b)

	T := make([]int, n)
	D := make([]int, n)
	F := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d %d\n", &T[i], &D[i])
	}

	c := 0
	k := -1

	for i := 0; i < n; {
		t := 0
		if k != -1 {
			t = F[k]
		}

		if t > T[i] {
			if c < b {
				c++

				j := i - 1
				for ; F[j] == -1; j-- {

				}
				F[i] = F[j] + D[i]
			} else {
				F[i] = -1
			}
			i++
		} else {
			if c > 0 {
				for k += 1; F[k] == -1; k++ {
				}
				c--
			} else {
				F[i] = T[i] + D[i]
				k = i
				i++
			}
		}
	}

	for i := 0; i < n; i++ {
		fmt.Printf("%d%s", F[i], " ")
	}

}

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"io"
	"os"
)

func Abs(x int) int {
	switch {
	case x < 0:
		return -x
	case x == 0:
		return 0
	}
	return x
}

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

func Scan(args ...interface{}) (e error)             { _, e = fmt.Fscan(in, args...); return }
func Scanf(ft string, args ...interface{}) (e error) { _, e = fmt.Fscanf(in, ft, args...); return }
func Scanln(args ...interface{}) (e error)           { _, e = fmt.Fscanln(in, args...); return }
func Print(args ...interface{})                      { out.WriteString(fmt.Sprint(args...)) }
func Printf(ft string, args ...interface{})          { out.WriteString(fmt.Sprintf(ft, args...)) }
func Println(args ...interface{})                    { out.WriteString(fmt.Sprintln(args...)) }

var (
	//dataIn = "data.in"
	in     = bufio.NewReader(os.Stdin)
	//in, _ = os.Open(dataIn)
	out   = bufio.NewWriter(os.Stdout)
)

type Job struct {
	id, ti, di int
}

var n, b int

func solve() {
	qu := list.New()
	pre := -1
	cur := &Job{-1, 0, 0}
	for i := 0; i < n; i++ {
		job := Job{id: i}
		Scan(&job.ti, &job.di)

		if cur.id != -1 {
			if cur.ti+cur.di <= job.ti {
				for i := pre + 1; i < cur.id; i++ {
					Print("-1 ")
				}
				Printf("%d ", cur.ti+cur.di)
				pre = cur.id
				cur.id = -1
			}
		}
		if (cur.id == -1 && qu.Len() <= b) || (cur.id != -1 && qu.Len() < b) {
			qu.PushBack(&job)
		}
		if cur.id == -1 && qu.Len() > 0 {
			iJob := qu.Front()
			now := cur.ti + cur.di
			cur = iJob.Value.(*Job)
			cur.ti = Max(cur.ti, now)
			qu.Remove(iJob)
		}
	}

	for cur.id != -1 {
		for i := pre + 1; i < cur.id; i++ {
			Print("-1 ")
		}
		Printf("%d ", cur.ti+cur.di)
		cur.id = -1
		if qu.Len() > 0 {
			iJob := qu.Front()
			now := cur.ti + cur.di
			cur = iJob.Value.(*Job)
			pre = cur.id
			cur.ti = Max(cur.ti, now)
			qu.Remove(iJob)
		}
	}
	for i := pre + 1; i < n; i++ {
		Print("-1 ")
	}
	Println()
	return
}

func main() {
	defer out.Flush()
	for Scan(&n, &b) != io.EOF {
		solve()
	}
	return
}

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"io"
	"os"
)

func Abs(x int) int {
	switch {
	case x < 0:
		return -x
	case x == 0:
		return 0
	}
	return x
}

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

func Scan(args ...interface{}) (e error)             { _, e = fmt.Fscan(in, args...); return }
func Scanf(ft string, args ...interface{}) (e error) { _, e = fmt.Fscanf(in, ft, args...); return }
func Scanln(args ...interface{}) (e error)           { _, e = fmt.Fscanln(in, args...); return }
func Print(args ...interface{})                      { out.WriteString(fmt.Sprint(args...)) }
func Printf(ft string, args ...interface{})          { out.WriteString(fmt.Sprintf(ft, args...)) }
func Println(args ...interface{})                    { out.WriteString(fmt.Sprintln(args...)) }

var (
	//dataIn = "data.in"
	in     = bufio.NewReader(os.Stdin)
	//in, _ = os.Open(dataIn)
	out   = bufio.NewWriter(os.Stdout)
)

type Job struct {
	id, ti, di int
}

var n, b int

func solve() {
	qu := list.New()
	pre := -1
	cur := &Job{-1, 0, 0}
	for i := 0; i < n; i++ {
		job := Job{id: i}
		Scan(&job.ti, &job.di)

		if cur.id != -1 {
			if cur.ti+cur.di <= job.ti {
				for i := pre + 1; i < cur.id; i++ {
					Print("-1 ")
				}
				Printf("%d ", cur.ti+cur.di)
				pre = cur.id
				cur.id = -1
			}
		}
		if (cur.id == -1 && qu.Len() <= b) || (cur.id != -1 && qu.Len() < b) {
			qu.PushBack(&job)
		}
		if cur.id == -1 && qu.Len() > 0 {
			iJob := qu.Front()
			now := cur.ti + cur.di
			cur = iJob.Value.(*Job)
			cur.ti = Max(cur.ti, now)
			qu.Remove(iJob)
		}
	}

	for cur.id != -1 {
		for i := pre + 1; i < cur.id; i++ {
			Print("-1 ")
		}
		Printf("%d ", cur.ti+cur.di)
		pre = cur.id
		cur.id = -1
		if qu.Len() > 0 {
			iJob := qu.Front()
			now := cur.ti + cur.di
			cur = iJob.Value.(*Job)
			cur.ti = Max(cur.ti, now)
			qu.Remove(iJob)
		}
	}
	for i := pre + 1; i < n; i++ {
		Print("-1 ")
	}
	Println()
	return
}

func main() {
	defer out.Flush()
	for Scan(&n, &b) != io.EOF {
		solve()
	}
	return
}

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"io"
	"os"
)

func Abs(x int) int {
	switch {
	case x < 0:
		return -x
	case x == 0:
		return 0
	}
	return x
}

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

func Scan(args ...interface{}) (e error)             { _, e = fmt.Fscan(in, args...); return }
func Scanf(ft string, args ...interface{}) (e error) { _, e = fmt.Fscanf(in, ft, args...); return }
func Scanln(args ...interface{}) (e error)           { _, e = fmt.Fscanln(in, args...); return }
func Print(args ...interface{})                      { out.WriteString(fmt.Sprint(args...)) }
func Printf(ft string, args ...interface{})          { out.WriteString(fmt.Sprintf(ft, args...)) }
func Println(args ...interface{})                    { out.WriteString(fmt.Sprintln(args...)) }

var (
	//dataIn = "data.in"
	in     = bufio.NewReader(os.Stdin)
	//in, _ = os.Open(dataIn)
	out   = bufio.NewWriter(os.Stdout)
)

type Job struct {
	id, ti, di int
}

var n, b int

func solve() {
	qu := list.New()
	pre := -1
	cur := &Job{-1, 0, 0}
	for i := 0; i < n; i++ {
		job := Job{id: i}
		Scan(&job.ti, &job.di)

		if cur.id != -1 {
			if cur.ti+cur.di <= job.ti {
				for i := pre + 1; i < cur.id; i++ {
					Print("-1 ")
				}
				Printf("%d ", cur.ti+cur.di)
				cur.id = -1
			}
		}
		if (cur.id == -1 && qu.Len() <= b) || (cur.id != -1 && qu.Len() < b) {
			qu.PushBack(&job)
		}
		if cur.id == -1 && qu.Len() > 0 {
			iJob := qu.Front()
			now := cur.ti + cur.di
			cur = iJob.Value.(*Job)
			pre = cur.id
			cur.ti = Max(cur.ti, now)
			qu.Remove(iJob)
		}
	}

	for cur.id != -1 {
		for i := pre + 1; i < cur.id; i++ {
			Print("-1 ")
		}
		Printf("%d ", cur.ti+cur.di)
		cur.id = -1
		if qu.Len() > 0 {
			iJob := qu.Front()
			now := cur.ti + cur.di
			cur = iJob.Value.(*Job)
			pre = cur.id
			cur.ti = Max(cur.ti, now)
			qu.Remove(iJob)
		}
	}
	for i := pre + 1; i < n; i++ {
		Print("-1 ")
	}
	Println()
	return
}

func main() {
	defer out.Flush()
	for Scan(&n, &b) != io.EOF {
		solve()
	}
	return
}


package main

import (

	"fmt"
	"time"
	"os"
	"log"
	"bufio"
	"strconv"
)
type Input struct {
	StartDate time.Time
	OlympiadDate time.Time
	People int
	TimePrepare int
	Live bool
}
func readFile(fileName string)[]Input{
	input := make([]Input, 0)
	var nOlympiad = 0
	var in [4]int
	var k  = 0
	file, err := os.Open(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	scanner.Split(bufio.ScanWords)
	for scanner.Scan() {
		if nOlympiad==0 {
			nOlympiad, err = strconv.Atoi(scanner.Text())
			if err != nil {
				log.Fatal(err)
			}
		}else{
			in[k], err = strconv.Atoi(scanner.Text())
			if err != nil {
				log.Fatal(err)
			}
			k++
			if (k)%4==0{
				startDate:=time.Date(2013, time.Month(in[0]), in[1] - in[3], 0, 0, 0, 1, time.UTC)
				olympiadDate:=time.Date(2013, time.Month(in[0]), in[1], 0, 0, 0, 1, time.UTC)
				input = append(input, Input{startDate,olympiadDate, in[2], in[3],false})
				k=0
			}
		}

	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
	return input
}
func writeFile(fileName string, awenser int){
	f, err := os.Create(fileName ) // creating...
	if err != nil {
		fmt.Printf("error creating file: %v", err)
		return
	}
	defer f.Close()
	_, err = f.WriteString(fmt.Sprintf("%d", awenser)) // writing...
	if err != nil {
		fmt.Printf("error writing string: %v", err)
	}
}
func main() {
	var fileNameIn = "input.txt"
	var fileNameOut = "output.txt"

	input := readFile(fileNameIn)

	var first Input
	var last Input

	//for k := 0; k < len(input); k++ {
	//	fmt.Println("------------input-------------")
	//	fmt.Println(input[k].OlympiadDate.Date())
	//	fmt.Println(input[k].StartDate.Date())
	//	fmt.Println("------------------------------")
	//}
	first = input[0]
	last = input[0]
	for l := 0; l < len(input); l++ {
		if input[l].StartDate.Year() < first.StartDate.Year(){
			first = input[l]
			}else {
			if input[l].StartDate.Year() == first.StartDate.Year() && input[l].StartDate.Month() < first.StartDate.Month(){
				first = input[l]
			}else if input[l].StartDate.Year() == first.StartDate.Year() && input[l].StartDate.Month() == first.StartDate.Month() && input[l].StartDate.Day() <= first.StartDate.Day() {
				first = input[l]
			}
		}
		if input[l].StartDate.Day() > last.StartDate.Day(){
			last = input[l]
		}else if input[l].StartDate.Day() == last.StartDate.Day() && input[l].StartDate.Month() > last.StartDate.Month(){
			last = input[l]
		}else if input[l].StartDate.Day() == last.StartDate.Day() && input[l].StartDate.Month() == last.StartDate.Month() && (input[l].StartDate.Year() >= first.StartDate.Year()){
			last = input[l]
		}
	}
	//fmt.Println("------------first-------------")
	//fmt.Println(first.StartDate.Date())
	//fmt.Println("------------------------------")
	//fmt.Println("------------last--------------")
	//fmt.Println(last.OlympiadDate.Date())
	//fmt.Println("------------------------------")

	var nJury =0
	var nJuryDay =0
	for d := first.StartDate; d.Year() <= last.OlympiadDate.Year(); d = d.AddDate(0, 0, 1) {
		//fmt.Println(d.Date())
		for i:=0;i<len(input);i++{
			if d.Equal(input[i].StartDate){
				input[i].Live=true
			}

			if d.Equal(input[i].OlympiadDate){
				input[i].Live=false
			}
			if input[i].Live{
				nJuryDay+=input[i].People
			}
			//fmt.Println(input[i].Live)
		}
		if nJury<nJuryDay{
			nJury=nJuryDay
		}
		//fmt.Println(nJuryDay)
		//fmt.Println(nJury)
		nJuryDay=0
		if last.OlympiadDate.Equal(d){
			break
		}
	}
	//fmt.Println(nJury)
	writeFile(fileNameOut,nJury)
}

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

type Span struct {
  Id, Start, End, Count int
}

func main() {
  fileIn, _ := os.Open("input.txt")
  fileOut, _ := os.Create("output.txt")
  scanner = bufio.NewScanner(fileIn)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(fileOut)
  defer writer.Flush()

  monthDays := []int{ 0, 31, 28, 31, 30,  31, 30, 31, 31,  30, 31, 30, 31 }
  daysBeforeMonth := make([]int, 13)
  for month := 1; month <= 11; month++ {
    daysBeforeMonth[month+1] = daysBeforeMonth[month] + monthDays[month]
  }

  n := getI()
  spans := make([]*Span, n)
  for ni := 0; ni < n; ni++ {
    m, d, p, t := getI(), getI(), getI(), getI()
    event := daysBeforeMonth[m] + d
    spans[ni] = &Span{ ni+1, event - t, event - 1, p }
  }
  result := 0
  for day := 0; day < 365; day++ {
    need := 0
    for _, span := range spans {
      if span.Start <= day && day <= span.End {
        need += span.Count
      }
    }
    if need > result {
      result = need
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

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

type Span struct {
  Start, End, Count int
}

func main() {
  fileIn, _ := os.Open("input.txt")
  fileOut, _ := os.Create("output.txt")
  scanner = bufio.NewScanner(fileIn)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(fileOut)
  defer writer.Flush()

  monthDays := []int{ 31, 28, 31, 30,  31, 30, 31, 31,  30, 31, 30, 31 }
  daysBeforeMonth := make([]int, 13)
  for month := 1; month <= 11; month++ {
    daysBeforeMonth[month+1] = daysBeforeMonth[month] + monthDays[month]
  }

  n := getI()
  spans := make([]*Span, n)
  for ni := 0; ni < n; ni++ {
    m, d, p, t := getI(), getI(), getI(), getI()
    event := daysBeforeMonth[m] + d
    spans[ni] = &Span{ event - t, event - 1, p }
  }
  result := 0
  for day := 0; day < 365; day++ {
    need := 0
    for _, span := range spans {
      if span.Start <= day && day <= span.End {
        need += span.Count
      }
    }
    if need > result {
      result = need
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

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

type Span struct {
  Start, End, Count int
}

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

  monthDays := []int{ 31, 28, 31, 30,  31, 30, 31, 31,  30, 31, 30, 31 }
  daysBeforeMonth := make([]int, 13)
  for month := 1; month <= 11; month++ {
    daysBeforeMonth[month+1] = daysBeforeMonth[month] + monthDays[month]
  }

  n := getI()
  spans := make([]*Span, n)
  for ni := 0; ni < n; ni++ {
    m, d, p, t := getI(), getI(), getI(), getI()
    event := daysBeforeMonth[m] + d
    spans[ni] = &Span{ event - t, event - 1, p }
  }
  result := 0
  for day := 0; day < 365; day++ {
    need := 0
    for _, span := range spans {
      if span.Start <= day && day <= span.End {
        need += span.Count
      }
    }
    if need > result {
      result = need
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

import (

	"fmt"
	"time"
	"os"
	"log"
	"bufio"
	"strconv"
)
type Input struct {
	StartDate time.Time
	OlympiadDate time.Time
	People int
	TimePrepare int
	Live bool
}
func readFile(fileName string)[]Input{
	input := make([]Input, 0)
	var nOlympiad = 0
	var in [4]int
	var k  = 0
	file, err := os.Open(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	scanner.Split(bufio.ScanWords)
	for scanner.Scan() {
		if nOlympiad==0 {
			nOlympiad, err = strconv.Atoi(scanner.Text())
			if err != nil {
				log.Fatal(err)
			}
		}else{
			in[k], err = strconv.Atoi(scanner.Text())
			if err != nil {
				log.Fatal(err)
			}
			k++
			if (k)%4==0{
				startDate:=time.Date(2013, time.Month(in[0]), in[1] - in[3], 0, 0, 0, 1, time.UTC)
				olympiadDate:=time.Date(2013, time.Month(in[0]), in[1], 0, 0, 0, 1, time.UTC)
				input = append(input, Input{startDate,olympiadDate, in[2], in[3],false})
				k=0
			}
		}

	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
	return input
}
func writeFile(fileName string, awenser int){
	f, err := os.Create(fileName ) // creating...
	if err != nil {
		fmt.Printf("error creating file: %v", err)
		return
	}
	defer f.Close()
	_, err = f.WriteString(fmt.Sprintf("%d", awenser)) // writing...
	if err != nil {
		fmt.Printf("error writing string: %v", err)
	}
}
func main() {
	var fileNameIn = "input.txt"
	var fileNameOut = "output.txt"

	input := readFile(fileNameIn)

	writeFile(fileNameOut,5)

	var first Input
	var last Input

	for k := 0; k < len(input); k++ {
		//fmt.Println("------------input-------------")
		//fmt.Println(input[k].OlympiadDate.Date())
		//fmt.Println(input[k].StartDate.Date())
		//fmt.Println("------------------------------")
		if k==0{
		first = input[k]
		last = input[k]
	}
		for l := 0; l < len(input); l++ {

			if input[l].StartDate.Day() <= input[k].StartDate.Day() && input[l].StartDate.Month() <= input[k].StartDate.Month() && input[l].StartDate.Year() <= input[k].StartDate.Year()&& k != l {
				first = input[l]
			}
			if input[k].StartDate.Day() > input[k].StartDate.Day() && input[l].StartDate.Month() > input[k].StartDate.Month() && input[l].StartDate.Year() > input[k].StartDate.Year()&& k != l {
				last = input[l]
			}
		}
	}
	//fmt.Println("------------first-------------")
	//fmt.Println(first.StartDate.Date())
	//fmt.Println("------------------------------")
	//fmt.Println("------------last--------------")
	//fmt.Println(last.OlympiadDate.Date())
	//fmt.Println("------------------------------")

	var nJury =0
	var nJuryDay =0
	for d := first.StartDate; d.Year() <= last.OlympiadDate.Year(); d = d.AddDate(0, 0, 1) {
		//fmt.Println(d.Date())
		for i:=0;i<len(input);i++{
			if d.Equal(input[i].StartDate){
				input[i].Live=true
			}

			if d.Equal(input[i].OlympiadDate){
				input[i].Live=false
			}
			if input[i].Live{
				nJuryDay+=input[i].People
			}
			//fmt.Println(input[i].Live)
		}
		if nJury<nJuryDay{
			nJury=nJuryDay
		}
		//fmt.Println(nJuryDay)
		//fmt.Println(nJury)
		nJuryDay=0
		if last.OlympiadDate.Equal(d){
			//fmt.Println("FIM")
			break
		}
	}
	//fmt.Println(nJury)
	writeFile(fileNameOut,nJury)
}

package main

import (

	"fmt"
	"time"
	"os"
	"log"
	"bufio"
	"strconv"
)
type Input struct {
	StartDate time.Time
	OlympiadDate time.Time
	People int
	TimePrepare int
	Live bool
}
func readFile(fileName string)[]Input{
	input := make([]Input, 0)
	var nOlympiad = 0
	var in [4]int
	var k  = 0
	file, err := os.Open(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	scanner.Split(bufio.ScanWords)
	for scanner.Scan() {
		if nOlympiad==0 {
			nOlympiad, err = strconv.Atoi(scanner.Text())
			if err != nil {
				log.Fatal(err)
			}
		}else{
			in[k], err = strconv.Atoi(scanner.Text())
			if err != nil {
				log.Fatal(err)
			}
			k++
			if (k)%4==0{
				startDate:=time.Date(2013, time.Month(in[0]), in[1] - in[3], 0, 0, 0, 1, time.UTC)
				olympiadDate:=time.Date(2013, time.Month(in[0]), in[1], 0, 0, 0, 1, time.UTC)
				input = append(input, Input{startDate,olympiadDate, in[2], in[3],false})
				k=0
			}
		}

	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
	return input
}
func writeFile(fileName string, awenser int){
	f, err := os.Create(fileName ) // creating...
	if err != nil {
		fmt.Printf("error creating file: %v", err)
		return
	}
	defer f.Close()
	_, err = f.WriteString(fmt.Sprintf("%d", awenser)) // writing...
	if err != nil {
		fmt.Printf("error writing string: %v", err)
	}
}
func main() {
	var fileNameIn = "input.txt"
	var fileNameOut = "output.txt"

	input := readFile(fileNameIn)

	var first Input
	var last Input

	//for k := 0; k < len(input); k++ {
	//	fmt.Println("------------input-------------")
	//	fmt.Println(input[k].OlympiadDate.Date())
	//	fmt.Println(input[k].StartDate.Date())
	//	fmt.Println("------------------------------")
	//}
	first = input[0]
	last = input[0]
	for l := 0; l < len(input); l++ {
		if input[l].StartDate.Year() < first.StartDate.Year(){
			first = input[l]
			}else {
			if input[l].StartDate.Year() == first.StartDate.Year() && input[l].StartDate.Day() <= first.StartDate.Day() && input[l].StartDate.Month() <= first.StartDate.Month(){
				first = input[l]
			}
		}
		if input[l].StartDate.Day() > last.StartDate.Day(){
			if input[l].StartDate.Day() == last.StartDate.Day() && input[l].StartDate.Month() >= last.StartDate.Month() && (input[l].StartDate.Year() >= first.StartDate.Year()) || input[l].StartDate.Year() > last.StartDate.Year(){
				last = input[l]
			}
		}

	}
	//fmt.Println("------------first-------------")
	//fmt.Println(first.StartDate.Date())
	//fmt.Println("------------------------------")
	//fmt.Println("------------last--------------")
	//fmt.Println(last.OlympiadDate.Date())
	//fmt.Println("------------------------------")

	var nJury =0
	var nJuryDay =0
	for d := first.StartDate; d.Year() <= last.OlympiadDate.Year(); d = d.AddDate(0, 0, 1) {
		//fmt.Println(d.Date())
		for i:=0;i<len(input);i++{
			if d.Equal(input[i].StartDate){
				input[i].Live=true
			}

			if d.Equal(input[i].OlympiadDate){
				input[i].Live=false
			}
			if input[i].Live{
				nJuryDay+=input[i].People
			}
			//fmt.Println(input[i].Live)
		}
		if nJury<nJuryDay{
			nJury=nJuryDay
		}
		//fmt.Println(nJuryDay)
		//fmt.Println(nJury)
		nJuryDay=0
		if last.OlympiadDate.Equal(d){
			break
		}
	}
	//fmt.Println(nJury)
	writeFile(fileNameOut,nJury)
}


package main

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

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

	tc := readNum(reader)

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		res := solve(n, A)
		buf.WriteString(fmt.Sprintf("%d\n", len(res)))
		for i := 0; i < len(res); i++ {
			buf.WriteString(fmt.Sprintf("%d ", res[i]))
		}
		buf.WriteByte('\n')
	}

	fmt.Print(buf.String())
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, A []int) []int {
	// af last, all operations, A should be A[0] <= A[1] <= .... <= A[n-1]
	// and A[i] - A[i-1] <= 1

	res := make([]int, 0, 2*n)
	for !sorted(A) {
		mem := make(map[int]int)

		for _, num := range A {
			mem[num]++
		}

		var mex int

		for mem[mex] > 0 {
			mex++
		}

		if mex == n {
			for i := 0; i < n; i++ {
				if A[i] != i {
					A[i] = mex
					res = append(res, i+1)
					break
				}
			}
		} else {
			A[mex] = mex
			res = append(res, mex+1)
		}
	}

	return res
}

func sorted(arr []int) bool {
	for i := 1; i < len(arr); i++ {
		if arr[i-1] > arr[i] {
			return false
		}
	}
	return true
}

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

var err error

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

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

func add(v []int, ind, x int) {
	for ; ind < len(v); ind += (-ind) & ind {
		v[ind] += x
	}
}

func read(v []int, ind int) (res int) {
	for ; ind > 0; ind -= (-ind) & ind {
		res += v[ind]
	}
	return res
}

func mex(arr []int) int {
	has := make(map[int]bool)
	for _, v := range arr {
		has[v] = true
	}
	for i := 0; ; i++ {
		if !has[i] {
			return i
		}
	}
}

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("in.txt")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

	t := nextInt()
	for ; t > 0; t-- {
		n := nextInt()
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = nextInt()
		}

		moves := []int{}

		for curr := mex(arr); curr < n; curr = mex(arr) {
			moves = append(moves, curr)
			arr[curr] = curr
		}

		for i := 0; i < n; i++ {
			if i == arr[i] {
				continue
			}
			for j := i + 1; j < n; j++ {
				if arr[j] == i {
					moves = append(moves, j)
					arr[j] = mex(arr)
				}
			}
			moves = append(moves, i)
			arr[i] = i
		}

		printf("%d\n", len(moves))
		for _, v := range moves {
			printf("%d ", v+1)
		}
		printf("\n")
	}
}

package main

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

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

	var t, n int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		cnt := map[int]int{}
		for i := range a {
			Fscan(in, &a[i])
			cnt[a[i]]++
		}
		ans := []interface{}{}
		f := func(mex int) bool {
			for i, v := range a {
				if i != v {
					cnt[v]--
					cnt[mex]++
					a[i] = mex
					ans = append(ans, i+1)
					return false
				}
			}
			return true
		}
		for {
			mex := 0
			for ; cnt[mex] > 0; mex++ {
			}
			if mex >= n {
				if f(mex) {
					break
				}
			} else if a[mex] == mex {
				f(mex)
			} else {
				cnt[a[mex]]--
				cnt[mex]++
				a[mex] = mex
				ans = append(ans, mex+1)
			}
		}
		Fprintln(out, len(ans))
		Fprintln(out, ans...)
	}
}

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

package main

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

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

	var t, n int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		cnt := map[int]int{}
		for i := range a {
			Fscan(in, &a[i])
			cnt[a[i]]++
		}
		ans := []interface{}{}
		f := func(mex int) bool {
			for i, v := range a {
				if i != v {
					cnt[v]--
					cnt[mex]++
					a[i] = mex
					ans = append(ans, i)
					return false
				}
			}
			return true
		}
		for {
			mex := 0
			for ; cnt[mex] > 0; mex++ {
			}
			if mex >= n {
				if f(mex) {
					break
				}
			} else if a[mex] == mex {
				f(mex)
			} else {
				cnt[a[mex]]--
				cnt[mex]++
				a[mex] = mex
				ans = append(ans, mex)
			}
		}
		Fprintln(out, len(ans))
		Fprintln(out, ans...)
	}
}

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


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

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 n int
		// fmt.Fscan(input, &n)

		STRING := make([]byte, 0)
		fmt.Fscan(input, &STRING)

		// ARR := make([]int, n)
		// for i := 0; i < n; i++ {
		// 	fmt.Fscan(input, &ARR[i])

		// }
		n := len(STRING)

		begin := string(STRING[0])
		end := string(STRING[n-1])

		if begin == end {
			fmt.Println(string(STRING))
		} else {
			STRING[n-1] = STRING[0]
			fmt.Println(string(STRING))

		}

	}

}

package main

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

var s string

func main() {

	r := bufio.NewReader(os.Stdin)

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

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

		ans := solve()
		fmt.Println(ans)
	}
}

func solve() string {
	//abbbbbaaaaaabbbbabbbb

	var ab int
	var ba int

	for i := 0; i < len(s) - 1; i++ {
		if s[i: i+2] == "ab" {
			ab++
		} else if s[i: i+2] == "ba" {
			ba++
		}
	}

	if ab == ba {
		return s
	}

	if s[0] == 'a' {
		return string('b') + s[1 :]
	}

	return string('a') + s[1 :]
}

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 s string
		fmt.Fscan(in, &s)

		var t1, t2 int
		for i := 0; i < len(s)-1; i++ {
			if s[i:i+2] == "ab" {
				t1++
			}

			if s[i:i+2] == "ba" {
				t2++
			}
		}

		if t1 > t2 {
			if s[0:2] == "ab" {
				s = "b" + s[1:]
			} else {
				s = s[:len(s)-1] + "a"
			}
		} else if t2 > t1 {
			if s[0:2] == "ba" {
				s = "a" + s[1:]
			} else {
				s = s[:len(s)-1] + "b"
			}
		}

		fmt.Fprintln(out, s)
	}
}

package main

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

var (
	input = bufio.NewReader(os.Stdin)
	output = bufio.NewWriter(os.Stdout)
)

func assert(test bool) {
    if !test {panic("assert!")}
}

func main() {
    defer output.Flush()
    //solve()
    //return
	var t int64
	fmt.Fscanln(input, &t)
    for t > 0 {
        t--
        solve()
    }
}

func solve() {
    var s string
    fmt.Fscanln(input, &s)
    sm := make([]int, 0)
    cnt := 1
    mn := int(1e9)
    mpos := -1
    spos := 0
    for i := 1; i < len(s); i++ {
        if s[i] != s[i - 1] {
            sm = append(sm, cnt)
            if cnt < mn {
                mn = cnt
                mpos = spos
                spos = i
            }
            cnt = 1
        }
    }
    sm = append(sm, cnt)
    if cnt < mn {
        mpos = spos
    }
    if len(sm) & 1 == 1 {
        fmt.Fprintln(output, s)
        return
    }
    for i := 0; i < len(s); i++ {
        if i < mpos || i >= mpos + mn {
            fmt.Fprint(output, string(s[i]))
        } else {
            if s[i] == 'a' {
                fmt.Fprint(output, string('b'))
            } else {
                fmt.Fprint(output, string('a'))
            }
        }
    }
    fmt.Fprintln(output)
}

func abs(x int64) int64 {
    if x >= 0 { return x}
    return -x
}

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

package main

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

var T int
var S string
var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func main() {
	defer out.Flush()
	fmt.Fscan(in, &T)
	for ; T > 0; T-- {
		fmt.Fscan(in, &S)
		if S[0] != S[len(S)-1] {
			if S[0] == 'a' {
				fmt.Fprint(out, "b")
			} else {
				fmt.Fprint(out, "a")
			}
			fmt.Fprintln(out, S[1:])
		} else {
			fmt.Fprintln(out, S)
		}
	}
}

package main

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

/*
6
a
aa
bb
abab
baab
ababab
---
a
aa
bb
bbab
baab
baabab
======
2
aaaabaa
baba
---
aaaabaa
aaba
======
2
aaaaab
aaaabb
--
aaaaaa
aaaaba
*/

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

	bld := strings.Builder{}

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

	for ; t > 0; t-- {
		var s string
		scanf("%s\n", &s)

		if len(s) == 1 {
			fmt.Fprintln(&bld, s)
			continue
		}

		abCnt := 0
		baCnt := 0

		for i := 0; i < len(s)-1; i++ {
			if s[i] == 'a' && s[i+1] == 'b' {
				abCnt++
			} else if s[i] == 'b' && s[i+1] == 'a' {
				baCnt++
			}
		}

		newS := []rune(s)

		if abCnt > baCnt {
			if s[0] == 'a' && s[1] == 'b' {
				newS[0] = 'b'
			} else if s[len(s)-2] == 'a' && s[len(s)-1] == 'b' {
				newS[len(s)-1] = 'a'
			} else if s[0] == 'a' && s[1] == 'a' {
				newS[0] = 'b'
			}
		} else if baCnt > abCnt {
			if s[0] == 'b' && s[1] == 'a' {
				newS[0] = 'a'
			} else if s[len(s)-2] == 'b' && s[len(s)-1] == 'a' {
				newS[len(s)-1] = 'b'
			} else if s[0] == 'b' && s[1] == 'b' {
				newS[0] = 'a'
			}
		}

		fmt.Fprintln(&bld, string(newS))
	}

	printf("%s", bld.String())
}

const maxUint = ^uint(0)

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

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

//goland:noinspection GoUnusedType
type pair struct {
	x int64
	y int64
}

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

//goland:noinspection GoUnusedFunction
func printf(f string, a ...interface{}) {
	if _, err := fmt.Fprintf(writer, f, a...); err != nil {
		panic(err)
	}
}

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

//goland:noinspection GoUnusedFunction
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

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

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

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

	for i := 5; i*i <= n; i += 6 {
		if n%i == 0 || n%(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 {
	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))
}

// 00
package main

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

func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var s string
		fmt.Fscan(reader, &s)
		sb := []byte(s)
		if sb[0] != sb[len(s)-1] {
			sb[0] = sb[len(s)-1]
		}
		fmt.Println(string(sb))

	}
}

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		solve()
	}
}
func solve() {
	s := []byte(ReadString())
	if s[0] == s[len(s)-1] {
		println(string(s))
		return
	}
	if s[0] == 'a' {
		s[0] = 'b'
	} else {
		s[0] = 'a'
	}
	println(string(s))
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func ReadString() (s string) { fmt.Fscan(_r, &s); return }
func ReadInt() (i int)       { fmt.Fscan(_r, &i); return }
func ReadInts(n int) (a []int) {
	for ; n > 0; n-- {
		a = append(a, ReadInt())
	}
	return
}
func print(a ...interface{})   { fmt.Fprint(_w, a...) }
func println(a ...interface{}) { fmt.Fprintln(_w, a...) }
func prints(s []int)           { v := fmt.Sprint(s); println(v[1 : len(v)-1]) }

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		solve()
	}
}
func solve() {
	s := []byte(ReadString())
	if ok(s) {
		println(string(s))
		return
	}

	for i := 0; i < len(s); i++ {
		orig := s[i]
		s[i] = 'a'
		if ok(s) {
			println(string(s))
			return
		}
		s[i] = 'b'
		if ok(s) {
			println(string(s))
			return
		}
		s[i] = orig
	}
}

func ok(s []byte) bool {
	c := 0
	for i := 0; i < len(s)-1; i++ {
		if s[i] < s[i+1] {
			c++
		} else if s[i] > s[i+1] {
			c--
		}
	}
	return c == 0
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) (s []int64) {
	for i := 0; i < n; i++ {
		s = append(s, ReadInt64())
	}
	return
}
func print(a ...interface{})            { fmt.Fprint(_w, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(_w, f, a...) }
func println(a ...interface{})          { fmt.Fprintln(_w, a...) }
func prints(s []int)                    { v := fmt.Sprint(s); println(v[1 : len(v)-1]) }

package main

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

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

func solve(s []byte) string {
	var (
		p, q int
		r    = len(s)
	)
	for i := 0; i < r-1; i++ {
		if s[i] == 'a' && s[i+1] == 'b' {
			p++
		}
		if s[i] == 'b' && s[i+1] == 'a' {
			q++
		}
	}
	if p > q {
		s[r-1] = 'a'
	}
	if p < q {
		s[r-1] = 'b'
	}
	return fmt.Sprintf("%s", s)
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		var s []byte
		fmt.Fscan(reader, &s)
		fmt.Println(solve(s))
	}
}

package main

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

/*
6
a
aa
bb
abab
baab
ababab
---
a
aa
bb
bbab
baab
baabab
======
2
aaaabaa
baba
---
aaaabaa
aaba
======
1
aaaaab
--
aaaaaa
*/

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

	bld := strings.Builder{}

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

	for ; t > 0; t-- {
		var s string
		scanf("%s\n", &s)

		if len(s) == 1 {
			fmt.Fprintln(&bld, s)
			continue
		}

		abCnt := 0
		baCnt := 0

		for i := 0; i < len(s)-1; i++ {
			if s[i] == 'a' && s[i+1] == 'b' {
				abCnt++
			} else if s[i] == 'b' && s[i+1] == 'a' {
				baCnt++
			}
		}

		newS := []rune(s)

		if abCnt > baCnt {
			if s[0] == 'a' && s[1] == 'b' {
				newS[0] = 'b'
			} else if s[len(s)-2] == 'a' && s[len(s)-1] == 'b' {
				newS[len(s)-1] = 'a'
			}
		} else if baCnt > abCnt {
			if s[0] == 'b' && s[1] == 'a' {
				newS[0] = 'a'
			} else if s[len(s)-2] == 'b' && s[len(s)-1] == 'a' {
				newS[len(s)-1] = 'b'
			}
		}

		fmt.Fprintln(&bld, string(newS))
	}

	printf("%s", bld.String())
}

const maxUint = ^uint(0)

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

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

//goland:noinspection GoUnusedType
type pair struct {
	x int64
	y int64
}

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

//goland:noinspection GoUnusedFunction
func printf(f string, a ...interface{}) {
	if _, err := fmt.Fprintf(writer, f, a...); err != nil {
		panic(err)
	}
}

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

//goland:noinspection GoUnusedFunction
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

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

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

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

	for i := 5; i*i <= n; i += 6 {
		if n%i == 0 || n%(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 {
	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))
}

package main

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

/*
6
a
aa
bb
abab
baab
ababab
---
a
aa
bb
bbab
baab
baabab
======
2
aaaabaa
baba
---
aaaabaa
aaba
*/

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

	bld := strings.Builder{}

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

	for ; t > 0; t-- {
		var s string
		scanf("%s\n", &s)

		if len(s) == 1 {
			fmt.Fprintln(&bld, s)
			continue
		}

		abCnt := 0
		baCnt := 0

		for i := 0; i < len(s)-1; i++ {
			if s[i] == 'a' && s[i+1] == 'b' {
				abCnt++
			} else if s[i] == 'b' && s[i+1] == 'a' {
				baCnt++
			}
		}

		newS := []rune(s)

		if abCnt > baCnt {
			if newS[0] == 'a' && newS[1] == 'b' {
				newS[0] = 'b'
			}
		} else if baCnt > abCnt {
			if newS[0] == 'b' && newS[1] == 'a' {
				newS[0] = 'a'
			}
		}

		fmt.Fprintln(&bld, string(newS))
	}

	printf("%s", bld.String())
}

const maxUint = ^uint(0)

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

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

//goland:noinspection GoUnusedType
type pair struct {
	x int64
	y int64
}

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

//goland:noinspection GoUnusedFunction
func printf(f string, a ...interface{}) {
	if _, err := fmt.Fprintf(writer, f, a...); err != nil {
		panic(err)
	}
}

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

//goland:noinspection GoUnusedFunction
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

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

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

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

	for i := 5; i*i <= n; i += 6 {
		if n%i == 0 || n%(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 {
	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))
}

// 00
package main

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

func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var s string
		fmt.Fscan(reader, &s)
		sb := []byte(s)
		abs := 0
		bas := 0
		counts := make([]int, len(s))
		for i := 1; i < len(s); i++ {
			if s[i] == 'a' && s[i-1] == 'b' {
				bas++
				counts[i]++
				counts[i-1]++
			}
			if s[i] == 'b' && s[i-1] == 'a' {
				abs++
				counts[i]++
				counts[i-1]++
			}
		}
		for i := 0; i < len(s); i++ {
			if abs == bas {
				break
			} else if abs > bas && counts[i] == 1 && sb[i] == 'a' {
				sb[i] = 'b'
				abs--
			} else if bas > abs && counts[i] == 1 && sb[i] == 'b' {
				sb[i] = 'a'
				bas--
			}
		}
		fmt.Println(string(sb))

	}
}

package main

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

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

func solve(s []byte) string {
	var (
		p, q int
		r    = len(s)
	)
	for i := 0; i < r-1; i++ {
		if s[i] == 'a' && s[i+1] == 'b' {
			p++
		}
		if s[i] == 'b' && s[i+1] == 'a' {
			q++
		}
	}
	if p > q {
		for i := 0; i < r-1; i++ {
			if s[i] == 'a' && s[i+1] == 'b' && (i == r-2 || s[i+2] == 'b') {
				s[i] = 'b'
				break
			}
		}
	}
	if p < q {
		for i := 0; i < r-1; i++ {
			if s[i] == 'b' && s[i+1] == 'a' && (i == r-2 || s[i+2] == 'a') {
				s[i] = 'a'
				break
			}
		}
	}
	return fmt.Sprintf("%s", s)
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		var s []byte
		fmt.Fscan(reader, &s)
		fmt.Println(solve(s))
	}
}

package main

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

var s string

func main() {

	r := bufio.NewReader(os.Stdin)

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

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

		ans := solve()
		fmt.Println(ans)
	}
}

func solve() string {
	//abbbbbaaaaaabbbbabbbb

	var ab int
	var ba int

	for i := 0; i < len(s) - 1; i++ {
		if s[i: i+2] == "ab" {
			ab++
		} else if s[i: i+2] == "ba" {
			ba++
		}
	}

	if ab == ba {
		return s
	}

	return s[1 :]
}


package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

var err error

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("d.in")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

	n := nextInt()
	arr, inds := make([]int, n), make([]int, n)
	for i := range arr {
		arr[i], inds[i] = nextInt(), i
	}

	sort.SliceStable(inds, func(a, b int) bool {
		return arr[inds[a]] < arr[inds[b]]
	})

	for i, v := range inds {
		arr[v] = i
	}

	moves := [][2]int{}
	for i := n - 1; i > 0; i-- {
		curr := [][2]int{}
		for j := 0; j < i; j++ {
			if arr[j] > arr[i] {
				curr = append(curr, [2]int{j, i})
			}
		}
		sort.Slice(curr, func(a, b int) bool {
			return arr[curr[a][0]] < arr[curr[b][0]]
		})
		moves = append(moves, curr...)
	}

	printf("%d\n", len(moves))
	for _, v := range moves {
		printf("%d %d\n", v[0]+1, v[1]+1)
	}
}

package main

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

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

	n := readNum(reader)
	A := readNNums(reader, n)
	res := solve(n, A)
	var buf bytes.Buffer
	buf.WriteString(fmt.Sprintf("%d\n", len(res)))
	for i := 0; i < len(res); i++ {
		buf.WriteString(fmt.Sprintf("%d %d\n", res[i][0], res[i][1]))
	}
	fmt.Print(buf.String())
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, A []int) [][]int {
	ps := make([]Pair, n)

	for i := 0; i < n; i++ {
		ps[i] = Pair{A[i], i + 1}
	}

	sort.Sort(Pairs(ps))
	for i := 0; i < n; i++ {
		A[ps[i].second-1] = i
	}
	pos := make([]int, n+1)
	for i := 0; i < n; i++ {
		pos[A[i]+1] = i + 1
	}

	X := make([]int, n+1)
	for i := 1; i <= n; i++ {
		X[i] = A[i-1] + 1
	}

	var res [][]int

	for cur := n; cur > 0; cur-- {
		if X[cur] == cur {
			continue
		}
		x := X[cur] + 1

		for x <= cur {
			i, j := pos[x], cur
			res = append(res, []int{i, j})
			X[i], X[j] = X[j], X[i]
			//pos[x], pos[cur] = pos[cur], pos[x]
			pos[X[i]], pos[X[j]] = i, j
			x++
		}
	}

	return res
}

type Pair struct {
	first, second int
}

type Pairs []Pair

func (ps Pairs) Len() int {
	return len(ps)
}

func (ps Pairs) Less(i, j int) bool {
	return ps[i].first < ps[j].first || ps[i].first == ps[j].first && ps[i].second < ps[j].second
}

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

package main

import (
	"fmt"
	"sort"
)

type pp struct {
	L, R int
}

var (
	n int
	a [1010]int
	p [1000010]pp
	pcnt int = 0
)

func main() {
	_, _ = fmt.Scan(&n)
	for i := 1; i <= n; i++ {
		_, _ = fmt.Scan(&a[i])
	}
	for i := 1; i <= n; i++ {
		for j := i + 1; j <= n; j++ {
			if a[i] > a[j] {
				pcnt++
				p[pcnt] = pp{i, j}
			}
		}
	}
	fmt.Println(pcnt)
	for i := 1; i <= pcnt; {
		j := i
		for j <= pcnt && p[j].L == p[i].L {
			j++
		}
		sort.Slice(p[i:j], func(x int, y int) bool {
			x += i
			y += i
			if a[p[x].R] != a[p[y].R] {
				return a[p[x].R] > a[p[y].R]
			} else {
				return p[x].R > p[y].R
			}
		})
		for k := i; k < j; k++ {
			fmt.Println(p[k].L, p[k].R)
		}
		i = j
	}
}

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

var err error

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("d.in")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

	n := nextInt()
	arr := make([]int, n)
	for i := range arr {
		arr[i] = nextInt()
	}

	moves := [][2]int{}
	for i := n - 1; i > 0; i-- {
		curr := [][2]int{}
		for j := 0; j < i; j++ {
			if arr[j] > arr[i] {
				curr = append(curr, [2]int{j, i})
			}
		}
		sort.Slice(curr, func(a, b int) bool {
			return arr[curr[a][0]] < arr[curr[b][0]]
		})
		moves = append(moves, curr...)
	}

	printf("%d\n", len(moves))
	for _, v := range moves {
		printf("%d %d\n", v[0]+1, v[1]+1)
	}
}

package main

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

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

	n := readNum(reader)
	A := readNNums(reader, n)
	res := solve(n, A)
	var buf bytes.Buffer
	buf.WriteString(fmt.Sprintf("%d\n", len(res)))
	for i := 0; i < len(res); i++ {
		buf.WriteString(fmt.Sprintf("%d %d\n", res[i][0], res[i][1]))
	}
	fmt.Print(buf.String())
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, A []int) [][]int {
	ps := make([]Pair, n)

	for i := 0; i < n; i++ {
		ps[i] = Pair{A[i], i + 1}
	}

	sort.Sort(Pairs(ps))
	for i := 0; i < n; i++ {
		A[ps[i].second-1] = i
	}
	pos := make([]int, n+1)
	for i := 0; i < n; i++ {
		pos[A[i]+1] = i + 1
	}

	X := make([]int, n+1)
	for i := 1; i <= n; i++ {
		X[i] = A[i-1] + 1
	}

	var res [][]int

	for cur := n; cur > 0; cur-- {
		if X[cur] == cur {
			continue
		}
		x := X[cur] + 1

		for x <= cur {
			i, j := pos[x], cur
			res = append(res, []int{i, j})
			X[i], X[j] = X[j], X[i]
			//pos[x], pos[cur] = pos[cur], pos[x]
			pos[X[i]], pos[X[j]] = i, j
			x++
		}
	}

	return res
}

type Pair struct {
	first, second int
}

type Pairs []Pair

func (ps Pairs) Len() int {
	return len(ps)
}

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

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

package main

import (
	"fmt"
	"sort"
)

type pp struct {
	L, R int
}

var (
	n int
	a [1010]int
	p [1000010]pp
	pcnt int = 0
)

func main() {
	_, _ = fmt.Scan(&n)
	for i := 1; i <= n; i++ {
		_, _ = fmt.Scan(&a[i])
	}
	for i := 1; i <= n; i++ {
		for j := i + 1; j <= n; j++ {
			if a[i] > a[j] {
				pcnt++
				p[pcnt] = pp{i, j}
			}
		}
	}
	fmt.Println(pcnt)
	for i := 1; i <= pcnt; {
		j := i
		for j <= pcnt && p[j].L == p[i].L {
			j++
		}
		sort.Slice(p[i:j], func(i int, j int) bool {
			if a[p[i].R] != a[p[j].R] {
				return a[p[i].R] > a[p[j].R]
			} else {
				return p[i].R > p[j].R
			}
		})
		for k := i; k < j; k++ {
			fmt.Println(p[k].L, p[k].R)
		}
		i = j
	}
}


package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    var n int
    cnt := make(map[int]int)
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        scanner.Scan()
        a, _ := strconv.Atoi(scanner.Text())
        cnt[a]++
    }
    if (cnt[5] != 0) || (cnt[7] != 0) || (cnt[1] != (n/3)) || (cnt[3] > cnt[6]) || (cnt[2] != (cnt[4]+cnt[6]-cnt[3])) {
        fmt.Println(-1)
    } else {
        for cnt[4] > 0 {
            fmt.Println(1,2,4); cnt[1]--; cnt[2]--; cnt[4]--;
        }
        for cnt[2] > 0 {
            fmt.Println(1,2,6); cnt[1]--; cnt[2]--; cnt[6]--;
        }
        for cnt[6] > 0 {
            fmt.Println(1,3,6); cnt[1]--; cnt[3]--; cnt[6]--;
        }
    }
}

package main

import (
	"sort"
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"runtime/pprof"
	"strconv"
)

func run(s *InOut) {
	n := s.Next()

	a := make([]int, n)
	for i := range a {
		a[i] = s.Next()
	}

	sort.Ints(a)

	result := make([][]int, 0)
	for len(a) > 0 {
		r := make([]int, 3)
		i, x := 0, a[0]
		r[0] = x
		a = a[1:]
		i = sort.Search(len(a), func(i int) bool { return x < a[i] && a[i] % x == 0})
		if i >= len(a) {
			s.Println(-1)
			return
		}
		x, r[1] = a[i], a[i]
		a = append(a[0:i], a[i+1:]...)
		i = sort.Search(len(a), func(i int) bool { return x < a[i] && a[i] % x == 0})
		if i >= len(a) {
			s.Println(-1)
			return
		}
		r[2] = a[i]
		a = append(a[0:i], a[i+1:]...)
		result = append(result, r)
	}

	for _, r := range result {
		s.Println(fmt.Sprintf("%d %d %d", r[0], r[1], r[2]))
	}
}

func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}
	s := NewInOut(os.Stdin, os.Stdout)
	defer s.Flush()

	run(s)
}

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

type InOut struct {
	*bufio.Reader
	*bufio.Writer
}

func NewInOut(r io.Reader, w io.Writer) *InOut {
	return &InOut{bufio.NewReader(r), bufio.NewWriter(w)}
}

// Get Next Integer
func (s *InOut) Next() (r int) {
	b, _ := s.ReadByte()
	p := 1
	for (b < '0' || '9' < b) && b != '-' {
		b, _ = s.ReadByte()
	}
	if b == '-' {
		p = -1
		b, _ = s.ReadByte()
	}
	for '0' <= b && b <= '9' {
		r = 10*r + int(b-'0')
		b, _ = s.ReadByte()
	}
	return r * p
}

func (s *InOut) NextInt64() (r int64) {
	b, _ := s.ReadByte()
	p := int64(1)
	for (b < '0' || '9' < b) && b != '-' {
		b, _ = s.ReadByte()
	}
	if b == '-' {
		p = -1
		b, _ = s.ReadByte()
	}
	for '0' <= b && b <= '9' {
		r = 10*r + int64(b-'0')
		b, _ = s.ReadByte()
	}
	return r * p
}

// Get Next Line String
func (s *InOut) NextLine() (r string) {
	b, _ := s.ReadByte()
	for b == '\r' || b == '\n' {
		b, _ = s.ReadByte()
	}
	buf := make([]byte, 0)
	for ; b != '\r' && b != '\n'; b, _ = s.ReadByte() {
		buf = append(buf, b)
	}
	return string(buf)
}

// Get Next String using delimiter whitespace
func (s *InOut) NextStr() (r string) {
	return string(s.NextBytes())
}

// Get Next String using delimiter whitespace
func (s *InOut) NextBytes() (r []byte) {
	b, _ := s.ReadByte()
	for b == '\n' || b == ' ' {
		b, _ = s.ReadByte()
	}
	buf := make([]byte, 0)
	for ; b != '\n' && b != ' '; b, _ = s.ReadByte() {
		buf = append(buf, b)
	}
	return buf
}

// Print Strings using the suitable way to change type
func (s *InOut) Print(os ...interface{}) {
	for _, o := range os {
		switch o.(type) {
		case byte:
			s.WriteByte(o.(byte))
		case string:
			s.WriteString(o.(string))
		case int:
			s.WriteString(strconv.Itoa(o.(int)))
		case int64:
			s.WriteString(strconv.FormatInt(o.(int64), 10))
		default:
			s.WriteString(fmt.Sprint(o))
		}
	}
}

// Print Strings using the suitable way to change type with new line
func (s *InOut) Println(os ...interface{}) {
	for _, o := range os {
		s.Print(o)
	}
	s.Print("\n")
}

// Print immediately with new line (for debug)
func (s *InOut) PrintlnNow(o interface{}) {
	fmt.Println(o)
}

package main
import (
	"fmt"
	"sort"
	//"unicode/utf8"
)

func main() {
	var n int
	fmt.Scan(&n)
	a:=make([]int,n)
	for i:=0;i<n;i++ {
		fmt.Scan(&a[i])
	}
	sort.Ints(a)
	flag:=false
	for i:=0;i<n/3;i++ {
			if a[i]>=a[i+n/3] || a[i+n/3]>=a[i+(n/3)*2] || a[i+n/3]%a[i]!=0 || a[i+(n/3)*2]%a[i+n/3]!=0 {
				fmt.Println("-1")
				flag=true
				break
			}
	}
	if flag==false {
		for i:=0;i<n/3;i++ {
			fmt.Println(a[i],a[i+n/3],a[i+(n/3)*2])
		}
	}
}

// 342A-mic
package main

import (
    "fmt"
)

var n int
var a [8]int
var b int

func cond() bool {
    return (a[5] == 0 && a[7] == 0 && a[1] == n/3 && a[2] >= a[4] && a[2]-a[4]+a[3] == a[6])
}

func main() {

    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&b)
        a[b]++
    }

    if !cond() {
        fmt.Println("-1")
    } else {
        for i := 0; i < a[4]; i++ {
            fmt.Println("1 2 4")
        }
        for i := 0; i < a[2]-a[4]; i++ {
            fmt.Println("1 2 6")
        }
        for i := 0; i < a[3]; i++ {
            fmt.Println("1 3 6")
        }
    }

}

package main

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

var (
	sc   *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr   *bufio.Writer  = bufio.NewWriter(os.Stdout)
	vals                = make([]int, 8)
)

func nextInt() int {
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	return n
}

func populate(a, b, c int, tri *[][]int) {
	for vals[a] > 0 && vals[b] > 0 && vals[c] > 0 {
		vals[a], vals[b], vals[c] = vals[a]-1, vals[b]-1, vals[c]-1
		*tri = append(*tri, []int{a, b, c})
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	for i := 0; i < n; i++ {
		vals[nextInt()]++
	}
	tri := make([][]int, 0)
	populate(1, 2, 4, &tri)
	populate(1, 2, 6, &tri)
	populate(1, 3, 6, &tri)
	if n == len(tri)*3 {
		for _, t := range tri {
			fmt.Fprintln(wr, t[0], t[1], t[2])
		}
	} else {
		fmt.Fprintln(wr, -1)
	}
	wr.Flush()
}

package main

import (
	"sort"
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"runtime/pprof"
	"strconv"
)

func run(s *InOut) {
	n := s.Next()

	a := make([]int, n)
	for i := range a {
		a[i] = s.Next()
	}

	sort.Ints(a)

	for len(a) > 0 {
		r := make([]int, 3)
		i, x := 0, a[0]
		r[0] = x
		a = a[1:]
		i = sort.Search(len(a), func(i int) bool { return x < a[i] && a[i] % x == 0})
		if i >= len(a) {
			s.Println(-1)
			return
		}
		x, r[1] = a[i], a[i]
		a = append(a[0:i], a[i+1:]...)
		i = sort.Search(len(a), func(i int) bool { return x < a[i] && a[i] % x == 0})
		if i >= len(a) {
			s.Println(-1)
			return
		}
		r[2] = a[i]
		a = append(a[0:i], a[i+1:]...)
		s.Println(fmt.Sprintf("%d %d %d", r[0], r[1], r[2]))
	}
}

func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}
	s := NewInOut(os.Stdin, os.Stdout)
	defer s.Flush()

	run(s)
}

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

type InOut struct {
	*bufio.Reader
	*bufio.Writer
}

func NewInOut(r io.Reader, w io.Writer) *InOut {
	return &InOut{bufio.NewReader(r), bufio.NewWriter(w)}
}

// Get Next Integer
func (s *InOut) Next() (r int) {
	b, _ := s.ReadByte()
	p := 1
	for (b < '0' || '9' < b) && b != '-' {
		b, _ = s.ReadByte()
	}
	if b == '-' {
		p = -1
		b, _ = s.ReadByte()
	}
	for '0' <= b && b <= '9' {
		r = 10*r + int(b-'0')
		b, _ = s.ReadByte()
	}
	return r * p
}

func (s *InOut) NextInt64() (r int64) {
	b, _ := s.ReadByte()
	p := int64(1)
	for (b < '0' || '9' < b) && b != '-' {
		b, _ = s.ReadByte()
	}
	if b == '-' {
		p = -1
		b, _ = s.ReadByte()
	}
	for '0' <= b && b <= '9' {
		r = 10*r + int64(b-'0')
		b, _ = s.ReadByte()
	}
	return r * p
}

// Get Next Line String
func (s *InOut) NextLine() (r string) {
	b, _ := s.ReadByte()
	for b == '\r' || b == '\n' {
		b, _ = s.ReadByte()
	}
	buf := make([]byte, 0)
	for ; b != '\r' && b != '\n'; b, _ = s.ReadByte() {
		buf = append(buf, b)
	}
	return string(buf)
}

// Get Next String using delimiter whitespace
func (s *InOut) NextStr() (r string) {
	return string(s.NextBytes())
}

// Get Next String using delimiter whitespace
func (s *InOut) NextBytes() (r []byte) {
	b, _ := s.ReadByte()
	for b == '\n' || b == ' ' {
		b, _ = s.ReadByte()
	}
	buf := make([]byte, 0)
	for ; b != '\n' && b != ' '; b, _ = s.ReadByte() {
		buf = append(buf, b)
	}
	return buf
}

// Print Strings using the suitable way to change type
func (s *InOut) Print(os ...interface{}) {
	for _, o := range os {
		switch o.(type) {
		case byte:
			s.WriteByte(o.(byte))
		case string:
			s.WriteString(o.(string))
		case int:
			s.WriteString(strconv.Itoa(o.(int)))
		case int64:
			s.WriteString(strconv.FormatInt(o.(int64), 10))
		default:
			s.WriteString(fmt.Sprint(o))
		}
	}
}

// Print Strings using the suitable way to change type with new line
func (s *InOut) Println(os ...interface{}) {
	for _, o := range os {
		s.Print(o)
	}
	s.Print("\n")
}

// Print immediately with new line (for debug)
func (s *InOut) PrintlnNow(o interface{}) {
	fmt.Println(o)
}

package main

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

var (
	sc   *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr   *bufio.Writer  = bufio.NewWriter(os.Stdout)
	vals                = make([]int, 8)
)

func nextString() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	n, _ := strconv.Atoi(nextString())
	return n
}

func print(a, b, c int) (printed int) {
	for vals[a] > 0 && vals[b] > 0 && vals[c] > 0 {
		vals[a], vals[b], vals[c] = vals[a]-1, vals[b]-1, vals[c]-1
		fmt.Fprintln(wr, a, b, c)
		printed++
	}
	return
}

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	for i := 0; i < n; i++ {
		vals[nextInt()]++
	}
	printed := print(1, 2, 4) + print(1, 2, 6) + print(1, 3, 6)
	if printed == 0 {
		fmt.Fprintln(wr, -1)
	}
	wr.Flush()
}

package main

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

var (
	sc   *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr   *bufio.Writer  = bufio.NewWriter(os.Stdout)
	vals                = make([]int, 8)
)

func nextInt() int {
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	return n
}

func populate(a, b, c int, tri *[][]int) {
	for vals[a] > 0 && vals[b] > 0 && vals[c] > 0 {
		vals[a], vals[b], vals[c] = vals[a]-1, vals[b]-1, vals[c]-1
		*tri = append(*tri, []int{a, b, c})
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	for i := 0; i < n; i++ {
		vals[nextInt()]++
	}
	tri := make([][]int, 0)
	populate(1, 2, 4, &tri)
	populate(1, 2, 6, &tri)
	populate(1, 3, 6, &tri)
	if n == cap(tri)*3 {
		for _, t := range tri {
			fmt.Fprintln(wr, t[0], t[1], t[2])
		}
	} else {
		fmt.Fprintln(wr, -1)
	}
	wr.Flush()
}


package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int64 {
	if !in.Scan() {
		panic(in.Err())
	}
	res := int64(0)
	mul := int64(1)
	for _, b := range in.Bytes() {
		if b == '-' {
			mul *= -1
			continue
		}
		res = res*10 + int64(b-'0')
	}
	return mul * res
}

type point struct {
	x, y, i int64
}

type byXY []point

func (s byXY) Len() int           { return len(s) }
func (s byXY) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byXY) Less(i, j int) bool { return s[i].x < s[j].x || s[i].x == s[j].x && s[i].y < s[j].y }

func area(a, b, c point) int64 {
	r := a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y)
	if r < 0 {
		return -r
	}
	return r
}

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	p := make([]point, n)
	for i := range p {
		p[i] = point{readInt(), readInt(), int64(i + 1)}
	}
	sort.Sort(byXY(p))

	best := p[2]
	bestArea := area(p[0], p[1], best)
	for _, pp := range p[3:] {
		a := area(p[0], p[1], pp)
		if a != 0 && (bestArea == 0 || bestArea > a) {
			bestArea = a
			best = pp
		}
	}
	fmt.Println(p[0].i, p[1].i, best.i)
}

package main

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

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

func main() {
	defer out.Flush()
	var n int
	fmt.Fscan(in, &n)
	points := make(Points, n)
	for i, _ := range points {
		p := &Point{}
		p.index = i + 1
		fmt.Fscan(in, &p.x, &p.y)
		points[i] = p
	}
	sort.Sort(points)
	var a, b *Point
	for i, c := range points {
		if i >= 2 && area(a, b, c) != 0 {
			fmt.Fprintln(out, a.index, b.index, c.index)
			return
		}
		a, b = b, c
	}
}

func area(a, b, c *Point) int64 {
	return det(a.x-c.x, a.y-c.y, b.x-c.x, b.y-c.y)
}

func det(a, b, c, d int64) int64 {
	return a*d - b*c
}

type Point struct {
	x, y  int64
	index int
}

type Points []*Point

func (p Points) Less(i, j int) bool {
	return p[i].x < p[j].x || (p[i].x == p[j].x && p[i].y < p[j].y)
}

func (p Points) Len() int {
	return len(p)
}

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

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int64 {
	if !in.Scan() {
		panic(in.Err())
	}
	res := int64(0)
	for _, b := range in.Bytes() {
		res = res*10 + int64(b-'0')
	}
	return res
}

type point struct {
	x, y, i int64
}

type byXY []point

func (s byXY) Len() int           { return len(s) }
func (s byXY) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byXY) Less(i, j int) bool { return s[i].x < s[j].x || s[i].x == s[j].x && s[i].y < s[j].y }

func area(a, b, c point) int64 {
	r := a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y)
	if r < 0 {
		return -r
	}
	return r
}

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	p := make([]point, n)
	for i := range p {
		p[i] = point{readInt(), readInt(), int64(i + 1)}
	}
	sort.Sort(byXY(p))

	best := p[2]
	bestArea := area(p[0], p[1], p[2])
	for _, pp := range p[2:] {
		a := area(p[0], p[1], pp)
		if bestArea == 0 || bestArea > a {
			bestArea = a
			best = pp
		}
	}
	fmt.Println(p[0].i, p[1].i, best.i)
}

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int64 {
	if !in.Scan() {
		panic(in.Err())
	}
	res := int64(0)
	mul := int64(1)
	for _, b := range in.Bytes() {
		if b == '-' {
			mul *= -1
			continue
		}
		res = res*10 + int64(b-'0')
	}
	return res
}

type point struct {
	x, y, i int64
}

type byXY []point

func (s byXY) Len() int           { return len(s) }
func (s byXY) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byXY) Less(i, j int) bool { return s[i].x < s[j].x || s[i].x == s[j].x && s[i].y < s[j].y }

func area(a, b, c point) int64 {
	r := a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y)
	if r < 0 {
		return -r
	}
	return r
}

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	p := make([]point, n)
	for i := range p {
		p[i] = point{readInt(), readInt(), int64(i + 1)}
	}
	sort.Sort(byXY(p))

	best := p[2]
	bestArea := area(p[0], p[1], best)
	for _, pp := range p[3:] {
		a := area(p[0], p[1], pp)
		if a != 0 && (bestArea == 0 || bestArea > a) {
			bestArea = a
			best = pp
		}
	}
	fmt.Println(p[0].i, p[1].i, best.i)
}

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int64 {
	if !in.Scan() {
		panic(in.Err())
	}
	res := int64(0)
	for _, b := range in.Bytes() {
		res = res*10 + int64(b-'0')
	}
	return res
}

type point struct {
	x, y, i int64
}

type byXY []point

func (s byXY) Len() int           { return len(s) }
func (s byXY) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byXY) Less(i, j int) bool { return s[i].x < s[j].x || s[i].x == s[j].x && s[i].y < s[j].y }

func area(a, b, c point) int64 {
	r := a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y)
	if r < 0 {
		return -r
	}
	return r
}

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	p := make([]point, n)
	for i := range p {
		p[i] = point{readInt(), readInt(), int64(i + 1)}
	}
	sort.Sort(byXY(p))

	best := p[2]
	bestArea := area(p[0], p[1], best)
	for _, pp := range p[3:] {
		a := area(p[0], p[1], pp)
		if a != 0 && (bestArea == 0 || bestArea > a) {
			bestArea = a
			best = pp
		}
	}
	fmt.Println(p[0].i, p[1].i, best.i)
}


package main

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

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

  var t, fromX, fromY, toX, toY int64
  fmt.Fscanln(reader, &t, &fromX, &fromY, &toX, &toY)
  var n, e, s, w int64
  if fromX < toX {
    e = toX - fromX
  } else {
    w = fromX - toX
  }
  if fromY < toY {
    n = toY - fromY
  } else {
    s = fromY - toY
  }

  for i := int64(0); i < t; i++ {
    ch, _ := reader.ReadByte()
    if ch == 'N' && n > 0 {
      n--
    } else if ch == 'E' && e > 0 {
      e--
    } else if ch == 'S' && s > 0 {
      s--
    } else if ch == 'W' && w > 0 {
      w--
    }
    if n == 0 && e == 0 && s == 0 && w == 0 {
      writer.WriteString(fmt.Sprintf("%d\n", i+1))
      return
    }
  }
  writer.WriteString("-1\n")
}

// 298B-mic_rizal
package main

import (
    "fmt"
)

func main() {
    var t, sx, sy, ex, ey int
    ANS := -1
    var x string
    fmt.Scan(&t, &sx, &sy, &ex, &ey, &x)
    for i := 0; i < t; i++ {
        if ex == sx && ey == sy && ANS == -1 {
            ANS = i - 1
        }
        if x[i] == 'N' && sy < ey {
            sy++
        } else if x[i] == 'S' && sy > ey {
            sy--
        } else if x[i] == 'E' && sx < ex {
            sx++
        } else if x[i] == 'W' && sx > ex {
            sx--
        }
    }
    if ex == sx && ey == sy && ANS == -1 {
        ANS = t
    } else if ANS == -1 {
        fmt.Println(ANS)
        return
    } else {
        fmt.Println(ANS + 1)
        return
    }

    fmt.Println(ANS)
}

package main

import (
	"fmt"
)

func main() {
	var t, sx, sy, ex, ey int
	var wind string

	fmt.Scan(&t, &sx, &sy, &ex, &ey, &wind)
	ans, l := 0, len(wind)

	for i:=0; i<l; i++{
		if wind[i] == 'S' && sy > ey {
			sy--
		}
		if wind[i] == 'N' && sy < ey {
			sy++
		}
		if wind[i] == 'E' && sx < ex {
			sx++
		}
		if wind[i] == 'W' && sx > ex {
			sx--
		}
		ans++
		if sx == ex && sy == ey {
			break
		}
	}
	if sx == ex && sy == ey {
		fmt.Println(ans)
	} else {
		fmt.Println(-1)
	}
}

package main

import "fmt"

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

func main() {
    var t,sx,sy,ex,ey int
    var s string
    fmt.Scan(&t,&sx,&sy,&ex,&ey)
    fmt.Scan(&s)
    dx := map[rune]int{'E':1,'S':0,'W':-1,'N':0}
    dy := map[rune]int{'E':0,'S':-1,'W':0,'N':1}
    ans := -1
    for k, v := range s {
        nx, ny := sx+dx[v], sy+dy[v]
        if (abs(nx-ex) < abs(sx-ex)) || (abs(ny-ey) < abs(sy-ey)) {
            sx, sy = nx, ny
        }
        if (sx == ex) && (sy == ey) {
            ans = k+1
            break
        }
    }
    fmt.Println(ans)
}

package main
import (
	"fmt"
)

func main() {
	var t, sx, sy, ex, ey, sec int
	var arah string
	sec=0
	fmt.Scan(&t, &sx, &sy, &ex, &ey, &arah)
	fmt.Scanln(arah)
	for i:=0; i<t; i++ {
		if arah[i]=='E' {
			sx+=1
			if sx<=ex {
				sec++
			} else {
				sx--
				sec++
			}
		} else if arah[i]=='S' {
			sy-=1
			if sy>=ey {
				sec++
			} else {
				sy++
				sec++
			}
		} else if arah[i]=='W' {
			sx-=1
			if sx>=ex {
				sec++
			} else {
				sx++
				sec++
			}
		} else if arah[i]=='N' {
			sy+=1
			if sy<=ey {
				sec++
			} else {
				sy--
				sec++
			}
		}
		if (sx==ex)&&(sy==ey) {
            		break
        	}
	}
	if (sx==ex)&&(sy==ey) {
		fmt.Println(sec)
	} else {
		fmt.Println("-1")
	}
}

//298B
package main

import (
	"fmt"
)

func main() {
	var (
		t, sx, sy, ex, ey int
		s                 string
	)
	fmt.Scan(&t, &sx, &sy, &ex, &ey, &s)
	ans, l := 0, len(s)

	for i := 0; i < l; i++ {
		if s[i] == 'S' && sy > ey {
			sy--
		}
		if s[i] == 'N' && sy < ey {
			sy++
		}
		if s[i] == 'E' && sx < ex {
			sx++
		}
		if s[i] == 'W' && sx > ex {
			sx--
		}
		ans++
		if sx == ex && sy == ey {
			break
		}
	}
	if sx == ex && sy == ey {
		fmt.Println(ans)
	} else {
		fmt.Println(-1)
	}
}

//298B
package main

import (
	"fmt"
)

func main() {
	var (
		t, sx, sy, ex, ey int
		s                 string
	)
	fmt.Scan(&t, &sx, &sy, &ex, &ey, &s)
	ans, l := 0, len(s)

	for i := 0; i < l; i++ {
		if s[i] == 'S' && sy > ey {
			sy--
		}
		if s[i] == 'N' && sy < ey {
			sy++
		}
		if s[i] == 'E' && sx < ex {
			sx++
		}
		if s[i] == 'W' && sx > ex {
			sx--
		}
		ans++
		if sx == ex && sy == ey {
			break
		}
	}
	if sx != ex && sy != ey {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

// 298B-mic_rizal
package main

import (
    "fmt"
)

func main() {
    var t, sx, sy, ex, ey int
    ANS := -1
    var x string
    fmt.Scan(&t, &sx, &sy, &ex, &ey, &x)
    for i := 0; i < t; i++ {
        if ex == sx && ey == sy && ANS == -1 {
            ANS = i - 1
        }
        if x[i] == 'N' && sy < ey {
            sy++
        } else if x[i] == 'S' && sy > ey {
            sy--
        } else if x[i] == 'E' && sx < ex {
            sx++
        } else if x[i] == 'W' && sx > ex {
            sx--
        }
    }
    if ex == sx && ey == sy && ANS == -1 {
        ANS = t
    }
    if ANS == -1 {
        fmt.Println(ANS)
    } else {
        fmt.Println(ANS + 1)
    }
}