Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i + 1, i + 2, ..., i + k. Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?

The first line contains two integers n and k (2 ≤ n ≤ 3·105, 1 ≤ k ≤ 3·105). The next line contains n characters — the description of the road: the i-th character equals ".", if the i-th sector contains no rocks. Otherwise, it equals "#". It is guaranteed that the first and the last characters equal ".".

Print "YES" (without the quotes) if Ksusha can reach the end of the road, otherwise print "NO" (without the quotes).

package main

import (
	"fmt"
	"strings"
)

func main() {
	var s, g string
	var n, k int
	fmt.Scanln(&n, &k)
	fmt.Scanln(&s)
	g = strings.Repeat("#", k)
	if strings.Count(s, g) > 0 {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")
	}
}

package main

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

func main() {
	var words []string
	var s, g string
	in := bufio.NewReader(os.Stdin)
	s, _ = in.ReadString('\n')
	words = strings.Fields(s)
	k, _ := strconv.Atoi(words[1])
	s, _ = in.ReadString('\n')
	g = strings.Repeat("#", k)
	if strings.Contains(s, g) {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")
	}
}

package main

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

func main() {
	var s, g string
	in := bufio.NewReader(os.Stdin)
	s, _ = in.ReadString(' ')
	s, _ = in.ReadString('\n')
	k, _ := strconv.Atoi(s[:len(s)-1])
	s, _ = in.ReadString('\n')
	g = strings.Repeat("#", k)
	if strings.Contains(s, g) {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")
	}
}


Keshi is throwing a party and he wants everybody in the party to be happy.He has $$$n$$$ friends. His $$$i$$$-th friend has $$$i$$$ dollars. If you invite the $$$i$$$-th friend to the party, he will be happy only if at most $$$a_i$$$ people in the party are strictly richer than him and at most $$$b_i$$$ people are strictly poorer than him.Keshi wants to invite as many people as possible. Find the maximum number of people he can invite to the party so that every invited person would be happy.

The first line contains a single integer $$$t$$$ $$$(1\le t\le 10^4)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the number of Keshi's friends. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ $$$(0 \le a_i, b_i < n)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print the maximum number of people Keshi can invite.

NoteIn the first test case, he invites the first and the second person. If he invites all of them, the third person won't be happy because there will be more than $$$1$$$ person poorer than him.

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

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

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

func min(a, b int64) int64{
    if a < b { return a}
    return b
}
func max(a, b int64) int64{
    if a > b { return a}
    return b
}
func solve() {
    var n int
    fmt.Fscan(input, &n)
    a := make([]int, n)
    b := make([]int, n)

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

    ok := func(x int) bool {
        cnt := 0
        //for i := 0; i < n; i++ {
        //    if a[i] >= x - 1 - cnt && b[i] >= cnt { cnt ++}
        //}
        //return cnt >= x

        r := 0
        for r < n {
            for r < n && (a[r] < x - 1 - cnt || b[r] < cnt) { r++; continue }
            if r < n { cnt++ }
            r++
        }
        return cnt >= x
    }

    l, r := 1, n + 1
    for r - l > 1 {
        m := (r + l) / 2
        if ok(m) {
            l = m
        } else {
            r = m
        }
    }

    fmt.Fprintln(output, l)
}

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

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

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

func min(a, b int64) int64{
    if a < b { return a}
    return b
}
func max(a, b int64) int64{
    if a > b { return a}
    return b
}
func solve() {
    var n int
    fmt.Fscan(input, &n)
    a := make([]int, n)
    b := make([]int, n)

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

    ok := func(x int) bool {
        cnt := 0
        //for i := 0; i < n; i++ {
        //    if a[i] >= x - 1 - cnt && b[i] >= cnt { cnt ++}
        //}
        //return cnt >= x

        r := 0
        for r < n {
            if r < n && !(a[r] < x - 1 - cnt || b[r] < cnt) { cnt++ }
            r++
        }
        return cnt >= x
    }

    l, r := 1, n + 1
    for r - l > 1 {
        m := (r + l) / 2
        if ok(m) {
            l = m
        } else {
            r = m
        }
    }

    fmt.Fprintln(output, l)
}

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

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

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

func min(a, b int64) int64{
    if a < b { return a}
    return b
}
func max(a, b int64) int64{
    if a > b { return a}
    return b
}
func solve() {
    var n int
    fmt.Fscan(input, &n)
    a := make([]int, n)
    b := make([]int, n)

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

    ok := func(x int) bool {
        cnt := 0
        for i := 0; i < n; i++ {
            if a[i] >= x - 1 - cnt && b[i] >= cnt { cnt ++}
        }
        return cnt >= x

        r := 0
        for r < n {
            for r < n && (a[r] < x - 1 - cnt || b[r] < cnt) { r++ }
            if r < n { cnt++ }
        }
        return cnt >= x
    }

    l, r := 1, n + 1
    for r - l > 1 {
        m := (r + l) / 2
        if ok(m) {
            l = m
        } else {
            r = m
        }
    }

    fmt.Fprintln(output, l)
}

package main

import (
	"bufio"
	"fmt"
	"os"
)
func min(x, y int)int{
	if x<y{
		return x
	}
	return y
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		var n int
		fmt.Fscan(in,&n)
		a := make([]int, n+5)
		b := make([]int, n+5)
		for i:=1;i<=n;i++{
			fmt.Fscan(in,&a[i],&b[i])
		}
		l := 1
		r := n
		ans := -1
		for l<=r{
			mid := (l+r)>>1
			cnt:=0
			for i:=1;i<=n;i++{
				if mid -1 - a[i]<=cnt&&cnt<=b[i]{
					cnt++
				}
			}
			if cnt<mid{
				r=mid-1
				continue
			}
			ans = mid
			l=mid+1
		}
		fmt.Fprintln(out,ans)
	}
}

package main

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

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

func scan(a ...interface{})             { fmt.Fscan(reader, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)
	a := make([][2]int, n)
	for i := range a {
		scan(&a[i][0], &a[i][1])
	}
	ok := func(x int) bool {
		took := 0
		for i := range a {
			if took <= a[i][1] && x-1-took <= a[i][0] {
				took++
			}
		}
		return took >= x
	}
	l, r := 1, n+1
	for r-l > 1 {
		m := l + (r-l)/2
		if ok(m) {
			l = m
		} else {
			r = m
		}
	}
	printf("%v\n", l)
}

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

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

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

func min(a, b int64) int64{
    if a < b { return a}
    return b
}
func max(a, b int64) int64{
    if a > b { return a}
    return b
}
func solve() {
    var n int
    fmt.Fscan(input, &n)
    a := make([]int, n)
    b := make([]int, n)

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

    ok := func(x int) bool {
        cnt := 0
        //for i := 0; i < n; i++ {
        //    if a[i] >= x - 1 - cnt && b[i] >= cnt { cnt ++}
        //}
        //return cnt >= x

        r := 0
        for r < n {
            for r < n && (a[r] < x - 1 - cnt || b[r] < cnt) { r++; continue }
            cnt++
            r++
        }
        return cnt >= x
    }

    l, r := 1, n + 1
    for r - l > 1 {
        m := (r + l) / 2
        if ok(m) {
            l = m
        } else {
            r = m
        }
    }

    fmt.Fprintln(output, l)
}

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

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

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

func min(a, b int64) int64{
    if a < b { return a}
    return b
}
func max(a, b int64) int64{
    if a > b { return a}
    return b
}
func solve() {
    var n int
    fmt.Fscan(input, &n)
    a := make([]int, n)
    b := make([]int, n)

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

    ok := func(x int) bool {
        cnt := 0
        //for i := 0; i < n; i++ {
        //    if a[i] >= x - 1 - cnt && b[i] >= cnt { cnt ++}
        //}
        //return cnt >= x

        r := 0
        for r < n {
            if r < n && (a[r] < x - 1 - cnt || b[r] < cnt) { r++; continue }
            cnt++
        }
        return cnt >= x
    }

    l, r := 1, n + 1
    for r - l > 1 {
        m := (r + l) / 2
        if ok(m) {
            l = m
        } else {
            r = m
        }
    }

    fmt.Fprintln(output, l)
}

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

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

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

func min(a, b int64) int64{
    if a < b { return a}
    return b
}
func max(a, b int64) int64{
    if a > b { return a}
    return b
}
func solve() {
    var n int
    fmt.Fscan(input, &n)
    a := make([]int, n)
    b := make([]int, n)

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

    ok := func(x int) bool {
        cnt := 0
        //for i := 0; i < n; i++ {
        //    if a[i] >= x - 1 - cnt && b[i] >= cnt { cnt ++}
        //}
        //return cnt >= x

        r := 0
        for r < n {
            for r < n && (a[r] < x - 1 - cnt || b[r] < cnt) { r++; continue }
            cnt++
        }
        return cnt >= x
    }

    l, r := 1, n + 1
    for r - l > 1 {
        m := (r + l) / 2
        if ok(m) {
            l = m
        } else {
            r = m
        }
    }

    fmt.Fprintln(output, l)
}

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

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

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

func min(a, b int64) int64{
    if a < b { return a}
    return b
}
func max(a, b int64) int64{
    if a > b { return a}
    return b
}
func solve() {
    var n int
    fmt.Fscan(input, &n)
    a := make([]int, n)
    b := make([]int, n)

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

    ok := func(x int) bool {
        r := 0
        cnt := 0
        for r < n {
            for r < n && (a[r] < x - 1 - cnt || b[r] < cnt) { r++ }
            if r < n { cnt++ }
        }
        return cnt >= x
    }

    l, r := 1, n + 1
    for r - l > 1 {
        m := (r + l) / 2
        if ok(m) {
            l = m
        } else {
            r = m
        }
    }

    fmt.Fprintln(output, l)
}

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

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

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

func min(a, b int64) int64{
    if a < b { return a}
    return b
}
func max(a, b int64) int64{
    if a > b { return a}
    return b
}
func solve() {
    var n int
    fmt.Fscan(input, &n)
    a := make([]int, n)
    b := make([]int, n)

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

    ok := func(x int) bool {
        X := x
        r := 0
        cnt := 0
        for r < n {
            for r < n && (a[r] < x - 1 || b[r] < cnt) { r++ }
            if r < n {
                cnt++
                x--
            }
        }
        return cnt >= X
    }

    l, r := 0, n + 1
    for r - l > 1 {
        m := (r + l) / 2
        if ok(m) {
            l = m
        } else {
            r = m
        }
    }

    fmt.Fprintln(output, l)
}

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

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

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

func min(a, b int64) int64{
    if a < b { return a}
    return b
}
func max(a, b int64) int64{
    if a > b { return a}
    return b
}
func solve() {
    var n int
    fmt.Fscan(input, &n)
    a := make([]int, n)
    b := make([]int, n)

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

    ok := func(x int) bool {
        r := 0
        cnt := 0
        for r < n {
            for r < n && (a[r] < x - 1 || b[r] < cnt) { r++ }
            if r < n {
                cnt++
                x--
            }
        }
        return x <= 0
    }

    l, r := 0, n + 1
    for r - l > 1 {
        m := (r + l) / 2
        if ok(m) {
            l = m
        } else {
            r = m
        }
    }

    fmt.Fprintln(output, l)
}

package main

import (
	"bufio"
	"fmt"
	"os"
)
func min(x, y int)int{
	if x<y{
		return x
	}
	return y
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		var n int
		fmt.Fscan(in,&n)
		a := make([]int, n+5)
		b := make([]int, n+5)
		for i:=1;i<=n;i++{
			fmt.Fscan(in,&a[i],&b[i])
		}
		l := 1
		r := n
		ans := -1
		for l<=r{
			mid := (l+r)>>1
			cnt:=0
			for i:=1;i<=n;i++{
				if min(a[i],n-i)+min(b[i],i-1)+1>=mid{
					cnt++
				}
			}
			if cnt<mid{
				r=mid-1
				continue
			}
			ans = mid
			l=mid+1
		}
		fmt.Fprintln(out,ans)
	}
}


In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.When a query appears server may react in three possible ways:   If server is free and query queue is empty, then server immediately starts to process this query.  If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue.  If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed. As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.

The first line of the input contains two integers n and b (1 ≤ n, b ≤ 200 000) — the number of queries and the maximum possible size of the query queue. Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers ti and di (1 ≤ ti, di ≤ 109), where ti is the moment of time when the i-th query appears and di is the time server needs to process it. It is guaranteed that ti - 1 < ti for all i > 1.

Print the sequence of n integers e1, e2, ..., en, where ei is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or  - 1 if the corresponding query will be rejected.

NoteConsider the first sample.   The server will start to process first query at the moment 2 and will finish to process it at the moment 11.  At the moment 4 second query appears and proceeds to the queue.  At the moment 10 third query appears. However, the server is still busy with query 1, b = 1 and there is already query 2 pending in the queue, so third query is just rejected.  At the moment 11 server will finish to process first query and will take the second query from the queue.  At the moment 15 fourth query appears. As the server is currently busy it proceeds to the queue.  At the moment 19 two events occur simultaneously: server finishes to proceed the second query and the fifth query appears. As was said in the statement above, first server will finish to process the second query, then it will pick the fourth query from the queue and only then will the fifth query appear. As the queue is empty fifth query is proceed there.  Server finishes to process query number 4 at the moment 21. Query number 5 is picked from the queue.  Server finishes to process query number 5 at the moment 22.

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
}


In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number i should be prepared by pi people for ti days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it.For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd.In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time.

The first line contains integer n — the number of Olympiads in 2013 (1 ≤ n ≤ 100). Each of the following n lines contains four integers mi, di, pi and ti — the month and day of the Olympiad (given without leading zeroes), the needed number of the jury members and the time needed to prepare the i-th Olympiad (1 ≤ mi ≤ 12, di ≥ 1, 1 ≤ pi, ti ≤ 100), di doesn't exceed the number of days in month mi. The Olympiads are given in the arbitrary order. Several Olympiads can take place in one day. Use the modern (Gregorian) calendar in the solution. Note that all dates are given in the year 2013. This is not a leap year, so February has 28 days. Please note, the preparation of some Olympiad can start in 2012 year.

Print a single number — the minimum jury size.

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 (

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


You're given an array of $$$n$$$ integers between $$$0$$$ and $$$n$$$ inclusive.In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).For example, if the current array is $$$[0, 2, 2, 1, 4]$$$, you can choose the second element and replace it by the MEX of the present elements  — $$$3$$$. Array will become $$$[0, 3, 2, 1, 4]$$$.You must make the array non-decreasing, using at most $$$2n$$$ operations.It can be proven that it is always possible. Please note that you do not have to minimize the number of operations. If there are many solutions, you can print any of them. –An array $$$b[1 \ldots n]$$$ is non-decreasing if and only if $$$b_1 \le b_2 \le \ldots \le b_n$$$.The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:  The MEX of $$$[2, 2, 1]$$$ is $$$0$$$, because $$$0$$$ does not belong to the array.  The MEX of $$$[3, 1, 0, 1]$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the array, but $$$2$$$ does not.  The MEX of $$$[0, 3, 1, 2]$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the array, but $$$4$$$ does not. It's worth mentioning that the MEX of an array of length $$$n$$$ is always between $$$0$$$ and $$$n$$$ inclusive.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 1000$$$) — length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$0 \le a_i \le n$$$) — elements of the array. Note that they don't have to be distinct. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$1000$$$.

For each test case, you must output two lines: The first line must contain a single integer $$$k$$$ ($$$0 \le k \le 2n$$$)  — the number of operations you perform. The second line must contain $$$k$$$ integers $$$x_1, \ldots, x_k$$$ ($$$1 \le x_i \le n$$$), where $$$x_i$$$ is the index chosen for the $$$i$$$-th operation. If there are many solutions, you can find any of them. Please remember that it is not required to minimize $$$k$$$.

NoteIn the first test case, the array is already non-decreasing ($$$2 \le 2 \le 3$$$).Explanation of the second test case (the element modified by each operation is colored in red):   $$$a = [2, 1, 0]$$$ ; the initial MEX is $$$3$$$.  $$$a = [2, 1, \color{red}{3}]$$$ ; the new MEX is $$$0$$$.  $$$a = [\color{red}{0}, 1, 3]$$$ ; the new MEX is $$$2$$$.  The final array is non-decreasing: $$$0 \le 1 \le 3$$$. Explanation of the third test case:   $$$a = [0, 7, 3, 1, 3, 7, 7]$$$ ; the initial MEX is $$$2$$$.  $$$a = [0, \color{red}{2}, 3, 1, 3, 7, 7]$$$ ; the new MEX is $$$4$$$.  $$$a = [0, 2, 3, 1, \color{red}{4}, 7, 7]$$$ ; the new MEX is $$$5$$$.  $$$a = [0, 2, 3, 1, \color{red}{5}, 7, 7]$$$ ; the new MEX is $$$4$$$.  $$$a = [0, 2, 3, \color{red}{4}, 5, 7, 7]$$$ ; the new MEX is $$$1$$$.  The final array is non-decreasing: $$$0 \le 2 \le 3 \le 4 \le 5 \le 7 \le 7$$$.

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


You are given a string $$$s$$$ of length $$$n$$$ consisting of characters a and/or b.Let $$$\operatorname{AB}(s)$$$ be the number of occurrences of string ab in $$$s$$$ as a substring. Analogically, $$$\operatorname{BA}(s)$$$ is the number of occurrences of ba in $$$s$$$ as a substring.In one step, you can choose any index $$$i$$$ and replace $$$s_i$$$ with character a or b.What is the minimum number of steps you need to make to achieve $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$?Reminder:The number of occurrences of string $$$d$$$ in $$$s$$$ as substring is the number of indices $$$i$$$ ($$$1 \le i \le |s| - |d| + 1$$$) such that substring $$$s_i s_{i + 1} \dots s_{i + |d| - 1}$$$ is equal to $$$d$$$. For example, $$$\operatorname{AB}($$$aabbbabaa$$$) = 2$$$ since there are two indices $$$i$$$: $$$i = 2$$$ where aabbbabaa and $$$i = 6$$$ where aabbbabaa.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first and only line of each test case contains a single string $$$s$$$ ($$$1 \le |s| \le 100$$$, where $$$|s|$$$ is the length of the string $$$s$$$), consisting only of characters a and/or b.

For each test case, print the resulting string $$$s$$$ with $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$ you'll get making the minimum number of steps. If there are multiple answers, print any of them.

NoteIn the first test case, both $$$\operatorname{AB}(s) = 0$$$ and $$$\operatorname{BA}(s) = 0$$$ (there are no occurrences of ab (ba) in b), so can leave $$$s$$$ untouched.In the second test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 2$$$, so you can leave $$$s$$$ untouched. In the third test case, $$$\operatorname{AB}(s) = 1$$$ and $$$\operatorname{BA}(s) = 0$$$. For example, we can change $$$s_1$$$ to b and make both values zero.In the fourth test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 1$$$. For example, we can change $$$s_6$$$ to a and make both values equal to $$$1$$$.

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"
	"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"
	"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"
	"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 :]
}