Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.

Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.

For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way:  At $$$0$$$-th minute, change the state to heating (the temperature is 0).  At $$$2$$$-nd minute, change the state to off (the temperature is 2).  At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied).  At $$$6$$$-th minute, change the state to off (the temperature is 3).  At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied).  At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.

package main

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

var sc, wr = bufio.NewScanner(os.Stdin), bufio.NewWriter(os.Stdout)

func scanString() string { sc.Scan(); return sc.Text() }
func scanInt() int { a,_ := strconv.Atoi(scanString()); return a }
func scanInt64() int64 { a,_ := strconv.ParseInt(scanString(),10,64); return a }
func scanFloat64() float64 { a,_ := strconv.ParseFloat(scanString(),64); return a }

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

func abs(a int) int { if a<0 { return -a }; return a }
func min(a,b int) int { if a<b { return a }; return b }
func max(a,b int) int { if a>b { return a }; return b }

//•*¨*•.¸¸♪Main•*¨*•.¸¸♪(　-ω-)ノ　(　・ω・)

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 1000000)

	tests := scanInt()
	for q := 0; q < tests; q++ {
		n := scanInt()
		m := scanInt()
		pre := 0
		templ := m
		temph := m
		f := true
		for i := 0; i < n; i++ {
			t := scanInt()
			l := scanInt()
			h := scanInt()

			d := t - pre
			maxh := temph+d
			minl := templ-d

			temph = min(h,maxh)
			templ = max(l,minl)

			if temph <templ {
				f = false
			}

			pre = t
		}
		if f {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

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

func main() {
	defer writer.Flush()

	var n, t, tm, l, h, m int64

	scanf("%d\n", &t)

	for i := 0; i < int(t); i++ {

		scanf("%d %d\n", &n, &m)

		mn, mx, last, td := m, m, int64(0), int64(0)

		flag := true

		for j := 0; j < int(n); j++ {
			scanf("%d %d %d\n", &tm, &l, &h)

			if !flag {
				continue
			}

			td = tm - last

			mn = mn - td
			mx = mx + td

			if mx < l || mn > h {
				printf("NO\n")
				flag = false

			}

			if l > mn {
				mn = l
			}
			if h < mx {
				mx = h
			}

			last = tm
		}
		if flag {
			printf("YES\n")
		}

	}

}

package main

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

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}
	type pair struct{ t, down, up int64 }

	solve := func() (ans bool) {
		var n, initT, t, down, up int64
		Fscan(in, &n, &initT)
		a := make([]pair, n)
		b := make([]pair, 0, n)
		for i := range a {
			Fscan(in, &t, &down, &up)
			a[i] = pair{t, down, up}
			if i == 0 || t > a[i-1].t {
				b = append(b, a[i])
			} else {
				b[len(b)-1].down = max(b[len(b)-1].down, down)
				b[len(b)-1].up = min(b[len(b)-1].up, up)
			}
		}

		down, up = initT, initT
		for i, p := range b {
			if p.down > p.up {
				return false
			}
			if i == 0 {
				down -= p.t
				up += p.t
			} else {
				down -= p.t - b[i-1].t
				up += p.t - b[i-1].t
			}
			if down > p.up || up < p.down {
				return false
			}
			down = max(down, p.down)
			up = min(up, p.up)
		}
		return true
	}

	var t int
	Fscan(in, &t)
	for _case := 1; _case <= t; _case++ {
		Fprintln(out, map[bool]string{true: "YES", false: "NO"} [solve()])
	}
}

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

package main

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

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}

	type pair struct{ t, down, up int64 }
	solve := func() (ans bool) {
		var n, initT int64
		Fscan(in, &n, &initT)
		a := make([]pair, n)
		b := make([]pair, 0, n)
		//b = append(b, pair{0,initT,initT})
		for i := range a {
			Fscan(in, &a[i].t, &a[i].down, &a[i].up)
		}
		for i, p := range a {
			if i == 0 || p.t > a[i-1].t {
				b = append(b, p)
			} else {
				b[len(b)-1].down = max(b[len(b)-1].down, p.down)
				b[len(b)-1].up = min(b[len(b)-1].up, p.up)
			}
		}

		down, up := initT, initT
		for i, p := range b {
			if p.down > p.up {
				return false
			}

			if i == 0 {
				down -= p.t
				up += p.t
			} else {
				down -= p.t-b[i-1].t
				up += p.t-b[i-1].t
			}
			if down <= p.up && up >= p.down {
				down = max(down, p.down)
				up = min(up, p.up)
			} else {
				return false
			}
		}

		return true
	}

	var t int
	Fscan(in, &t)
	for _case := 1; _case <= t; _case++ {
		Fprintln(out, map[bool]string{true: "YES", false: "NO"} [solve()])
	}
}

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

package main

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

// 需要考虑到所有的input都要考虑进去
func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	casesstr := scanner.Text()
	cases, _ := strconv.Atoi(casesstr)
	results := make([]bool, cases)
	for i := 0; i < cases; i++ {
		scanner.Scan()
		arrstr := scanner.Text()
		arr := strings.Split(arrstr, " ")
		customers, _ := strconv.ParseInt(arr[0], 10, 64)
		currentT, _ := strconv.ParseInt(arr[1], 10, 64)
		currentTime := int64(0)
		rangel, ranger := currentT, currentT
		flag := true
		for j := int64(0); j < customers; j++ {
			scanner.Scan()
			text := scanner.Text()
			arr = strings.Split(text, " ")
			ctime, _ := strconv.ParseInt(arr[0], 10, 64)
			clowerT, _ := strconv.ParseInt(arr[1], 10, 64)
			chigherT, _ := strconv.ParseInt(arr[2], 10, 64)
			rangel -= ctime - currentTime
			ranger += ctime - currentTime
			currentTime = ctime
			// fmt.Println(arr, rangel, ranger)
			if ranger < clowerT || rangel > chigherT {
				flag = false
			}
			if rangel < clowerT {
				rangel = clowerT
			}
			if ranger > chigherT {
				ranger = chigherT
			}
		}
		results[i] = flag
	}
	for i:=0;i<len(results)-1;i++ {
		if results[i] {
			fmt.Println("yes")
		}else {
			fmt.Println("no")
		}
	}
	if results[len(results)-1] {
		fmt.Print("yes")
	}else {
		fmt.Print("no")
	}
}

package main

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

var sc, wr = bufio.NewScanner(os.Stdin), bufio.NewWriter(os.Stdout)

func scanString() string { sc.Scan(); return sc.Text() }
func scanInt() int { a,_ := strconv.Atoi(scanString()); return a }
func scanInt64() int64 { a,_ := strconv.ParseInt(scanString(),10,64); return a }
func scanFloat64() float64 { a,_ := strconv.ParseFloat(scanString(),64); return a }

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

func abs(a int) int { if a<0 { return -a }; return a }
func min(a,b int) int { if a<b { return a }; return b }
func max(a,b int) int { if a>b { return a }; return b }

//•*¨*•.¸¸♪Main•*¨*•.¸¸♪(　-ω-)ノ　(　・ω・)

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 1000000)

	tests := scanInt()
	L: for q := 0; q < tests; q++ {
		n := scanInt()
		m := scanInt()
		pre := 0
		templ := m
		temph := m
		for i := 0; i < n; i++ {
			t := scanInt()
			l := scanInt()
			h := scanInt()

			d := t - pre
			maxh := temph+d
			minl := templ-d

			temph = min(h,maxh)
			templ = max(l,minl)

			if temph <templ {
				fmt.Println("NO")
				continue L
			}

			pre = t
		}
		fmt.Println("YES")
	}
}

package main

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

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

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

func main() {
	defer writer.Flush()

	var n, t, tm, l, h, m int

	scanf("%d\n", &t)

	for i := 0; i < t; i++ {

		scanf("%d %d\n", &n, &m)

		mn, mx, last, td := m, m, 0, 0

		flag := true

		for j := 0; j < n; j++ {
			scanf("%d %d %d\n", &tm, &l, &h)

			td = tm - last

			mn = mn - td
			mx = mx + td

			if mx < l || mn > h {
				printf("NO\n")
				flag = false
				break
			}

			if l > mn {
				mn = l
			}
			if h < mx {
				mx = h
			}

			last = tm
		}
		if flag {
			printf("YES\n")
		}

	}

}

package main

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

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

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

func main() {
	defer writer.Flush()

	var n, t, tm, l, h, m int64

	scanf("%d\n", &t)

	for i := 0; i < int(t); i++ {

		scanf("%d %d\n", &n, &m)

		mn, mx, last, td := m, m, int64(0), int64(0)

		flag := true

		for j := 0; j < int(n); j++ {
			scanf("%d %d %d\n", &tm, &l, &h)

			td = tm - last

			mn = mn - td
			mx = mx + td

			if mx < l || mn > h {
				printf("NO\n")
				flag = false
				break
			}

			if l > mn {
				mn = l
			}
			if h < mx {
				mx = h
			}

			last = tm
		}
		if flag {
			printf("YES\n")
		}

	}

}

package main

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

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}

	type pair struct{ t, down, up int64 }
	solve := func() (ans bool) {
		var n, initT int64
		Fscan(in, &n, &initT)
		a := make([]pair, n)
		b := make([]pair, 0, n)
		//b = append(b, pair{0,initT,initT})
		for i := range a {
			Fscan(in, &a[i].t, &a[i].down, &a[i].up)
		}
		for i, p := range a {
			if i == 0 || p.t > a[i-1].t {
				b = append(b, p)
			} else {
				b[len(b)-1].down = max(b[len(b)-1].down, p.down)
				b[len(b)-1].up = min(b[len(b)-1].up, p.up)
			}
		}

		down, up := initT, initT
		for i, p := range b {
			if i == 0 {
				down -= p.t
				up += p.t
			} else {
				down -= p.t-b[i-1].t
				up += p.t-b[i-1].t
			}
			if down <= p.up && up >= p.down {
				down = max(down, p.down)
				up = min(up, p.up)
			} else {
				return false
			}
		}

		return true
	}

	var t int
	Fscan(in, &t)
	for _case := 1; _case <= t; _case++ {
		Fprintln(out, map[bool]string{true: "YES", false: "NO"} [solve()])
	}
}

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

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	casesstr := scanner.Text()
	cases, _ := strconv.Atoi(casesstr)
	for i := 0; i < cases; i++ {
		scanner.Scan()
		arrstr := scanner.Text()
		arr := strings.Split(arrstr, " ")
		customers, _ := strconv.ParseInt(arr[0], 10, 64)
		currentT, _ := strconv.ParseInt(arr[1], 10, 64)
		currentTime := int64(0)
		rangel, ranger := currentT, currentT
		flag := true
		for i := int64(0); i < customers; i++ {
			scanner.Scan()
			text := scanner.Text()
			arr = strings.Split(text, " ")
			ctime, _ := strconv.ParseInt(arr[0], 10, 64)
			clowerT, _ := strconv.ParseInt(arr[1], 10, 64)
			chigherT, _ := strconv.ParseInt(arr[2], 10, 64)
			rangel -= ctime - currentTime
			ranger += ctime - currentTime
			currentTime = ctime
			// fmt.Println(arr, rangel, ranger)
			if ranger < clowerT || rangel > chigherT {
				flag = false
				break
			}
			if rangel < clowerT {
				rangel = clowerT
			}
			if ranger > chigherT {
				ranger = chigherT
			}
		}
		if flag {
			fmt.Println("yes")
		}else {
			fmt.Print("no")
		}
	}
}


Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex.You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree.Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree.

The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree.

Print the only integer t — the minimal time required for all ants to be in the root of the tree.

/*
    based on tutorial for Educational Round 7
*/
package main

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

const N int = 500500
var n int

type IntArray []int
type IntArrayArray []IntArray

var g IntArrayArray
var z IntArray

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

func dfs(v, p, d int) {
    c := 0
    for i := 0; i < len(g[v]); i++ {
        to := g[v][i]
        if to == p {
            continue
        }
        c += 1
        dfs(to, v, d + 1)
    }
    if c == 0 {
        z = append(z, d)
    }
}

func solve(v, p int) int {
    z = z[:0]
    dfs(v, p, 0)
    sort.Ints(z)
    for i := 0; i < len(z); i++ {
        if i > 0 {
            z[i] = max(z[i - 1] + 1, z[i])
        }
    }
    return z[len(z) - 1]
}

func main() {
    stin := bufio.NewReader(os.Stdin)
    g = make(IntArrayArray, N)
    z = make(IntArray, 0)
    fmt.Fscanf(stin, "%d\n", &n)
    var x, y int
    for i := 0; i < n-1; i++ {
        fmt.Fscanf(stin, "%d %d\n", &x, &y)
        //fmt.Printf("%d %d\n", x, y)
        x -= 1
        y -= 1
        g[x] = append(g[x], y)
        g[y] = append(g[y], x)
    }
    result := 0
    for i := 0; i < len(g[0]); i++ {
        result = max(result, solve(g[0][i], 0) + 1)
    }
    fmt.Printf("%d", result)
}

/*
    Tree is a connected graph without cycles.
    A leaf of a tree is any vertex connected with exactly one other vertex.

    You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree.
    In one second some ants can simultaneously go to the parent vertex from the vertex they were in.
    No two ants can be in the same vertex simultaneously except for the root of the tree.

    Find the minimal time required for all ants to be in the root of the tree.
    Note that at start the ants are only in the leaves of the tree

    Input
    First line: 2 <= n <= 500000 - the number of vertices in the tree.
    Next n-1 lines: pair of numbers x_i,y_i (1 <= x_i,y_i <= n) - the edges of the tree.
     It is guaranteed that you are given the correct undirected tree.

    Output
    Print the only integer t - the minimal time required for all ants to be in the root of the tree.
*/

/*
    based on tutorial for Educational Round 7
*/
package main

import (
        "fmt"
        "sort"
       )

const N int = 500500
var n int

type IntArray []int
type IntArrayArray []IntArray

var g IntArrayArray
var z IntArray

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

func dfs(v, p, d int) {
    c := 0
    for i := 0; i < len(g[v]); i++ {
        to := g[v][i]
        if to == p {
            continue
        }
        c += 1
        dfs(to, v, d + 1)
    }
    if c == 0 {
        z = append(z, d)
    }
}

func solve(v, p int) int {
    z = z[:0]
    dfs(v, p, 0)
    sort.Ints(z)
    for i := 0; i < len(z); i++ {
        if i > 0 {
            z[i] = max(z[i - 1] + 1, z[i])
        }
    }
    return z[len(z) - 1]
}

func main() {
    g = make(IntArrayArray, N)
    z = make(IntArray, 0)
    fmt.Scanf("%d\n", &n)
    var x, y int
    for i := 0; i < n-1; i++ {
        fmt.Scanf("%d %d\n", &x, &y)
        fmt.Printf("%d %d\n", x, y)
        x -= 1
        y -= 1
        g[x] = append(g[x], y)
        g[y] = append(g[y], x)
    }
    result := 0
    for i := 0; i < len(g[0]); i++ {
        result = max(result, solve(g[0][i], 0) + 1)
    }
    fmt.Printf("%d", result)
}

/*
    ������� ���� ��� ������ ���������� �������.
    ������ ������ ���������� ����� �������, ������� ������� ����� � ����� ������ ��������.

    ������ ������ �� n ������ � ������ � ������� 1. � ������ ����� ������ ��������� ���� �������.
    �� ���� ������� ��������� �������� ����� ������������ ������� � ������ ������� � ������� ��� ���������.
    ��� ������� �� ����� ���������� ������������ � ����� �������, �� ����������� ����� ������.

    ���������� ���������� ����� �� ������� ��� ������� ������ ������� � ������ ������.
    �������� ��������, ��� ������� ������� ��������� ������ � ������� ������.

    ������� ������
    � ������ ������� ��������� ����� ����� n (2 <= n <= 500000) � ���������� ������ � ������.
    ������ �� ��������� n-1 ����� �������� ���� ����� ����� x_i,y_i (1 <= x_i,y_i <= n) � ����� ������.
    �������������, ��� ��� ������ ���������� ������.

    �������� ������
    �������� ����� ����� t � ���������� �����, �����������, ����� ��� ������� ������ � ������ ������.
*/


Polycarp is a great fan of television.He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment li and ends at moment ri.Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV.Polycarp wants to check out all n shows. Are two TVs enough to do so?

The first line contains one integer n (1 ≤ n ≤ 2·105) — the number of shows. Each of the next n lines contains two integers li and ri (0 ≤ li < ri ≤ 109) — starting and ending time of i-th show.

If Polycarp is able to check out all the shows using only two TVs then print "YES" (without quotes). Otherwise, print "NO" (without quotes).

package main

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

const maxTokenSize = 512 * 1024

type seg struct {
	l int
	r int
}

type segments []*seg

func (s segments) Less(i, j int) bool {
	return s[i].l < s[j].l
}

func (s segments) Len() int {
	return len(s)
}

func (s segments) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, maxTokenSize), maxTokenSize)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	var segs []*seg

	for i := 0; i < n; i++ {
		scanner.Scan()
		l, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		r, _ := strconv.Atoi(scanner.Text())
		segs = append(segs, &seg{l: l, r: r})
	}
	sort.Sort(segments(segs))

	a := -1
	b := -1

	for i := 0; i < n; i++ {
		if segs[i].l > a {
			a = segs[i].r
			continue
		}
		if segs[i].l > b {
			b = segs[i].r
			continue
		}
		fmt.Println("NO")
		return
	}

	fmt.Println("YES")
	// 	3
	// 1 2
	// 2 3
	// 4 5
}


This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.Waking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs n ingredients, and for each ingredient she knows the value ai — how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all n ingredients.Apollinaria has bi gram of the i-th ingredient. Also she has k grams of a magic powder. Each gram of magic powder can be turned to exactly 1 gram of any of the n ingredients and can be used for baking cookies.Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.

The first line of the input contains two positive integers n and k (1 ≤ n, k ≤ 1000) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.

Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.

NoteIn the first sample it is profitably for Apollinaria to make the existing 1 gram of her magic powder to ingredient with the index 2, then Apollinaria will be able to bake 4 cookies.In the second sample Apollinaria should turn 1 gram of magic powder to ingredient with the index 1 and 1 gram of magic powder to ingredient with the index 3. Then Apollinaria will be able to bake 3 cookies. The remaining 1 gram of the magic powder can be left, because it can't be used to increase the answer.

package main

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

var N, K int

func CheckBake(cookie int64, magic int64, A []int, B []int) bool {
	for i := 0; i < N; i++ {
		need := cookie * int64(A[i])
		rest := int64(B[i]) - need
		if rest < 0 {
			magic += int64(rest)
		}
		if magic < 0 {
			return false
		}
	}
	return true
}

func main() {
	fsc := NewFastScanner()
	N = fsc.NextInt()
	K = fsc.NextInt()
	A := make([]int, N)
	B := make([]int, N)
	for i := 0; i < N; i++ {
		A[i] = fsc.NextInt()
	}
	for i := 0; i < N; i++ {
		B[i] = fsc.NextInt()
	}
	left := int64(0)
	right := int64(10000000)
	for right-left > 1 {
		med := (right + left) / 2
		flag := CheckBake(med, int64(K), A, B)

		if flag { //bake
			left = med
		} else {
			right = med
		}
	}
	fmt.Println(left)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 2028)
	return &FastScanner{r: rdr}
}

func (s *FastScanner) Next() string {
	s.Pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}

func (s *FastScanner) NextInt() int {
	val, err := strconv.Atoi(s.Next())
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) NextInt64() int64 {
	val, err := strconv.ParseInt(s.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}

func (s *FastScanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, err := s.r.ReadLine()
		if err != nil {
			panic(err.Error())
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

// Using binary search to validate the "answers" within lg(n) times.
package main

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

func main() {
	n, k, scanner := 0, 0, bufio.NewScanner(os.Stdin)
	fmt.Scan(&n, &k)
	scanner.Split(bufio.ScanWords)
	a, b := make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		a[i], _ = strconv.Atoi(scanner.Text())
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		b[i], _ = strconv.Atoi(scanner.Text())
	}

	answer, l, r := -1, 0, 2000
	for l <= r {
		mid, match, newK := (l+r)/2, false, k
		for i := 0; i < len(a); i++ {
			extra := a[i]*mid - b[i]
			if extra > newK {
				break
			} else if extra > 0 {
				newK -= extra
			}
			if i == (len(a) - 1) {
				match = true
			}
		}
		if match {
			l = mid + 1
			answer = mid
		} else {
			r = mid - 1
		}
	}

	fmt.Println(answer)
}

package main

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

func main() {
	n := getInt()
	k := getInt()
	a := getNint(n)
	b := getNint(n)

	ispossible := func(c int64) bool {
		k := k
		for i := 0; i < n; i++ {
			q := int64(a[i])*c - int64(b[i])
			if q > int64(k) {
				return false
			}
			if q > 0 {
				k -= int(q)
			}
		}
		return true
	}

	fmt.Println(bin_search_max64(ispossible, 0, 2000000001))
}

// largest argument, for which f(arg) is true
// logic function should be non-increasing
func bin_search_max64(f func(int64) bool, lo, up int64) int64 {
	var mid, step int64
	const eps = 1
	lo--
	cnt := up - lo
	for cnt >= eps {
		step = cnt / 2
		mid = up - step
		if !f(mid) {
			up = mid - eps
			cnt -= step + eps
		} else {
			cnt = step
		}
	}
	return up
}

type Input struct {
	*bufio.Scanner
}

var globalInput = wrapStdin()

func wrapStdin() Input {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	return Input{Scanner: sc}
}
func getInt() int {
	globalInput.Scan()
	x, _ := strconv.Atoi(globalInput.Text())
	return x
}
func getIntOk() (int, bool) {
	ok := globalInput.Scan()
	x, _ := strconv.Atoi(globalInput.Text())
	return x, ok
}
func getNint(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		v[i] = getInt()
	}
	return v
}
func getVint(v []int) bool {
	var ok bool
	for i := 0; i < len(v); i++ {
		v[i], ok = getIntOk()
	}
	return ok
}
func getWord() string {
	globalInput.Scan()
	return globalInput.Text()
}
func getWordOk() (string, bool) {
	ok := globalInput.Scan()
	return globalInput.Text(), ok
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}
func min64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func max64(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func minStr(a, b string) string {
	if a < b {
		return a
	}
	return b
}
func maxStr(a, b string) string {
	if a < b {
		return b
	}
	return a
}
func remin(a *int, b int) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remax(a *int, b int) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}
func remin64(a *int64, b int64) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remax64(a *int64, b int64) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}
func reminStr(a *string, b string) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remaxStr(a *string, b string) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func abs64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

type (
	FLess    func(i, j int) bool
	FSwap    func(i, j int)
	wrapSort struct {
		Length int
		FLess
		FSwap
	}
)

func (w *wrapSort) Len() int           { return w.Length }
func (w *wrapSort) Less(i, j int) bool { return w.FLess(i, j) }
func (w *wrapSort) Swap(i, j int)      { w.FSwap(i, j) }
func wsort(length int, fless func(i, j int) bool, fswap func(i, j int)) {
	sort.Sort(&wrapSort{length, fless, fswap})
}

package main

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

var N, K int

func CheckBake(cookie int, magic int, A []int, B []int) bool {
	for i := 0; i < N; i++ {
		need := cookie * A[i]
		rest := B[i] - need
		if rest < 0 {
			magic += rest
		}
		if magic < 0 {
			return false
		}
	}
	return true
}

func main() {
	fsc := NewFastScanner()
	N = fsc.NextInt()
	K = fsc.NextInt()
	A := make([]int, N)
	B := make([]int, N)
	for i := 0; i < N; i++ {
		A[i] = fsc.NextInt()
	}
	for i := 0; i < N; i++ {
		B[i] = fsc.NextInt()
	}
	left := 0
	right := 1009
	for right-left > 1 {
		med := (right + left) / 2
		flag := CheckBake(med, K, A, B)

		if flag { //bake
			left = med
		} else {
			right = med
		}
	}
	fmt.Println(left)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 2028)
	return &FastScanner{r: rdr}
}

func (s *FastScanner) Next() string {
	s.Pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}

func (s *FastScanner) NextInt() int {
	val, err := strconv.Atoi(s.Next())
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) NextInt64() int64 {
	val, err := strconv.ParseInt(s.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}

func (s *FastScanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, err := s.r.ReadLine()
		if err != nil {
			panic(err.Error())
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

var N, K int

func CheckBake(cookie int, magic int, A []int, B []int) bool {
	for i := 0; i < N; i++ {
		need := cookie * A[i]
		rest := B[i] - need
		if rest < 0 {
			magic += rest
		}
		if magic < 0 {
			return false
		}
	}
	return true
}

func main() {
	fsc := NewFastScanner()
	N = fsc.NextInt()
	K = fsc.NextInt()
	A := make([]int, N)
	B := make([]int, N)
	for i := 0; i < N; i++ {
		A[i] = fsc.NextInt()
	}
	for i := 0; i < N; i++ {
		B[i] = fsc.NextInt()
	}
	left := 0
	right := 1145141919
	for right-left > 1 {
		med := (right + left) / 2
		flag := CheckBake(med, K, A, B)

		if flag { //bake
			left = med
		} else {
			right = med
		}
	}
	fmt.Println(left)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 2028)
	return &FastScanner{r: rdr}
}

func (s *FastScanner) Next() string {
	s.Pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}

func (s *FastScanner) NextInt() int {
	val, err := strconv.Atoi(s.Next())
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) NextInt64() int64 {
	val, err := strconv.ParseInt(s.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}

func (s *FastScanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, err := s.r.ReadLine()
		if err != nil {
			panic(err.Error())
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}


You are given integer $$$n$$$. You have to arrange numbers from $$$1$$$ to $$$2n$$$, using each of them exactly once, on the circle, so that the following condition would be satisfied:For every $$$n$$$ consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard $$$2n$$$ numbers differ not more than by $$$1$$$.For example, choose $$$n = 3$$$. On the left you can see an example of a valid arrangement: $$$1 + 4 + 5 = 10$$$, $$$4 + 5 + 2 = 11$$$, $$$5 + 2 + 3 = 10$$$, $$$2 + 3 + 6 = 11$$$, $$$3 + 6 + 1 = 10$$$, $$$6 + 1 + 4 = 11$$$, any two numbers differ by at most $$$1$$$. On the right you can see an invalid arrangement: for example, $$$5 + 1 + 6 = 12$$$, and $$$3 + 2 + 4 = 9$$$, $$$9$$$ and $$$12$$$ differ more than by $$$1$$$.

The first and the only line contain one integer $$$n$$$ ($$$1 \le n \le 10^5$$$).

If there is no solution, output "NO" in the first line.  If there is a solution, output "YES" in the first line. In the second line output $$$2n$$$ numbers — numbers from $$$1$$$ to $$$2n$$$ in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them.

NoteExample from the statement is shown for the first example. It can be proved that there is no solution in the second example.

package main

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

func main() {
	var q int64

	scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Fscanln(scr, &q)

	a := make([]int64, 2*q)

	if q%2 == 0 {
		fmt.Println("NO")
	} else {
		for i := int64(0); i < 2*q; i = i + 2 {
			a[i] = i + 1
		}
		n := int64(1)
		for i := q; i < 2*q; i = i + 2 {
			a[i] = 2 * n
			n++
		}
		for i := int64(1); i < q; i = i + 2 {
			a[i] = 2 * n
			n++
		}

		fmt.Println("YES")

		for _, y := range a {
			fmt.Printf("%d ", y)
		}
	}

}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var n int
	fmt.Fscan(reader, &n)
	if n%2 == 0 {
		fmt.Fprintf(writer, "NO\n")
		return
	}
	fmt.Fprint(writer, "YES\n")
	var ans = make([]int, 2*n)
	var now = 1
	for i := 0; i < n; i++ {
		if i%2 == 0 {
			ans[i] = now
			ans[i+n] = now + 1
		} else {
			ans[i] = now + 1
			ans[i+n] = now
		}
		now += 2
	}
	for i := 0; i < 2*n; i++ {
		fmt.Fprintf(writer, "%v ", ans[i])
	}
	fmt.Fprintf(writer, "\n")
}

// Author: sighduck
// URL: https://codeforces.com/contest/1206/problem/C

package main

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

type Solution struct {
	exists      bool
	arrangement []int
}

func Solve(n int) Solution {
	if n%2 == 0 {
		return Solution{exists: false, arrangement: []int{}}
	}
	arrangement := make([]int, 2*n)
	for i := 0; i < n; i++ {
		if i%2 == 0 {
			arrangement[i] = 2*n - i
			arrangement[i+n] = 2*n - i - 1
		} else {
			arrangement[i] = i
			arrangement[i+n] = i + 1
		}
	}
	return Solution{exists: true, arrangement: arrangement}
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	solution := Solve(n)
	if solution.exists {
		fmt.Fprintf(writer, "YES\n")
		for _, elem := range solution.arrangement {
			fmt.Fprintf(writer, "%d ", elem)
		}
		fmt.Fprintf(writer, "\n")
	} else {
		fmt.Fprintf(writer, "NO\n")
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

func main() {
	defer writer.Flush()
	var n int
	scanf("%d\n", &n)
	var first,second []int
	if n%2 == 0{
		printf("NO")
	} else{
		//first = append(first,1)
		flag := false
		count := 0
		for i:=2;i<=n*2;i++{
			if flag{
				first = append(first,i)
			}else{
				second = append(second,i)
			}
			count++
			if count ==2{
				count = 0
				flag = !flag
			}
		}
		printf("YES\n")
		printf("1")
		for _,v:= range first{
			printf(" %d",v)
		}
		for _,v:= range second{
			printf(" %d",v)
		}
	}
}

package main

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

func main() {
	defer Flush()

	n := readll()
	a := make([]int64, 2*n)
	for i := int64(0); i < n; i++ {
		v1 := 2*i + 1
		v2 := 2*i + 2
		a[i] = v1
		a[i+n] = v2
	}

	for i := int64(1); i < n; i += 2 {
		a[i], a[i+n] = a[i+n], a[i]
	}

	b := append(a[:2*n:2*n], a...)
	var i, sum int64
	for i = int64(0); i < n; i++ {
		sum += b[i]
	}

	minv := sum
	maxv := sum
	for i = n; i < int64(len(b)); i++ {
		sum += b[i] - b[i-n]
		minv = minll(minv, sum)
		maxv = maxll(minv, sum)
		if 1 < maxv-minv {
			println("NO")
			return
		}
	}
	println("YES")
	sp := ""
	for _, v := range a {
		printf("%s%d", sp, v)
		sp = " "
	}
	println()
}

// -----------------------------------------------------------------------------

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

// -----------------------------------------------------------------------------

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

// -----------------------------------------------------------------------------

// Utilities

func sumSlice(a []int) int {
	var res int
	for _, v := range a {
		res += v
	}
	return res
}

func sumSlicell(a []int64) int64 {
	var res int64
	for _, v := range a {
		res += v
	}
	return res
}

func readInts(N int) (int, []int) {
	if N == 0 {
		N = readi()
	}
	a := make([]int, N)
	for i := range a {
		a[i] = readi()
	}
	return N, a
}

func readIntsll(N int) (int, []int64) {
	if N == 0 {
		N = readi()
	}
	a := make([]int64, N)
	for i := range a {
		a[i] = readll()
	}
	return N, a
}

// reverse slice in place
func reverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}

// areverse: allocating reverse
func areverse(a []int) []int {
	b := make([]int, len(a))
	for i := range a {
		b[i] = a[len(a)-i-1]
	}
	return b
}

// -----------------------------------------------------------------------------

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

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

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

func minf(a, b float64) float64 {
	if a < b {
		return a
	}
	return b
}

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

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

func maxf(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

func absll(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

func absf(a float64) float64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}


You are given four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$. You should build a sequence $$$a_0, a_1, a_2, \dots, a_n$$$ where $$$a_0 = 0$$$ and for each $$$i \ge 1$$$ you can choose:   either $$$a_i = a_{i - 1} + x$$$  or $$$a_i = a_{i - 1} - y$$$. Your goal is to build such a sequence $$$a$$$ that $$$a_i \le B$$$ for all $$$i$$$ and $$$\sum\limits_{i=0}^{n}{a_i}$$$ is maximum possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first and only line of each test case contains four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le B, x, y \le 10^9$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the maximum possible $$$\sum\limits_{i=0}^{n}{a_i}$$$.

NoteIn the first test case, the optimal sequence $$$a$$$ is $$$[0, 1, 2, 3, 4, 5]$$$.In the second test case, the optimal sequence $$$a$$$ is $$$[0, 10^9, 0, 10^9, 0, 10^9, 0, 10^9]$$$.In the third test case, the optimal sequence $$$a$$$ is $$$[0, -3, -6, 1, -2]$$$.

package main

import "fmt"

func main() {
	k := 0
	fmt.Scanf("%d\n", &k)
	for k > 0 {
		k--
		var n = 0
		var B, x, y int64
		n, B, x, y = 0, 0, 0, 0
		fmt.Scanf("%d %d %d %d\n", &n, &B, &x, &y)
		var s, c int64
		for i := 1; i < n+1; i++ {
			if c+x <= B {
				c += x
			} else {
				c -= y
			}
			s += c
		}
		fmt.Println(s)
	}
}

package main

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

const (
	INF = 3e5 + 10
)

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

	var t, n int
	var b, x, y int64
	Fscan(in, &t)

	for k := 0; k < t; k++ {
		Fscan(in, &n, &b, &x, &y)
		ans := int64(0)
		cur := int64(0)
		for i := 1; i <= n; i++ {
			if cur+x <= b {
				cur += x
			} else {
				cur -= y
			}
			ans += cur
		}

		Fprintln(out, ans)
	}
}

package main

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

func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}

const mod = 998244353

// 1 2 3 4
func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := 1
	fmt.Fscan(in, &t)

	for ii := 0; ii < t; ii++ {
		var n, b, x, y int64
		fmt.Fscan(in, &n, &b, &x, &y)
		last := int64(0)
		sum := int64(0)
		for i := int64(1); i <= n; i++ {
			if last+x > b {
				last -= y
			} else {
				last += x
			}
			sum += last
		}
		fmt.Fprintln(out, sum)
	}
}

package main

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

func main() {

	reader := bufio.NewReader(os.Stdin)
	writter := bufio.NewWriter(os.Stdout)
	defer writter.Flush()

	t := 0
	fmt.Fscan(reader, &t)

	for t > 0 {
		n, B, x, y := 0, 0, 0, 0
		fmt.Fscan(reader, &n, &B, &x, &y)

		// p := make([]int, n)
		// for i := range p {
		// 	fmt.Fscan(reader, &p[i])
		// }

		fmt.Fprintln(writter, solve(n, B, x, y))

		t--
	}

	//fmt.Println(commonServices.Solve(4, 1, 7, 3))
}

func solve(n, B, x, y int) int64 {

	result := int64(0)

	array := make([]int64, n+1)
	array[0] = 0

	for i := 1; i <= n; i++ {

		next := array[i-1] + int64(x)
		if next > int64(B) {
			next -= int64(x + y)
		}

		array[i] = next
		result += int64(next)

	}

	//fmt.Println(array)

	return result

}

package main
import "fmt"
import "os"
import "bufio"
//import "math"
//import "sort"
var (
	input = bufio.NewReader(os.Stdin)
	output = bufio.NewWriter(os.Stdout)
)
func main() {
	defer output.Flush()
	count := 0
	fmt.Fscan(input,&count)
	for count>0 {
		count --
		n := 0
		B := 0
		x := 0
		y := 0
		fmt.Fscan(input,&n)
		fmt.Fscan(input,&B)
		fmt.Fscan(input,&x)
		fmt.Fscan(input,&y)
		s := int64(0)
		val := 0
		for i:=1;i<=n;i++ {
			if val+x<=B {
				val += x
				s += int64(val)
			} else {
				val -= y
				s += int64(val)
			}
		}
		fmt.Fprintln(output,s)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	var n, B, x, y int64
	fmt.Scanf("%d\n", &t)
	for ; t >= 1; t-- {
		fmt.Scanf("%d %d %d %d\n", &n, &B, &x, &y)
		var ans int64
		var a int64
		var i int64
		for i = 1; i <= n; i++ {
			if x > -y && a+x <= B {
				a += x
			} else if -y > x && a-y <= B {
				a -= y
			} else if -y < 0 {
				a -= y
			} else if x < 0 {
				a += x
			}
			ans += a
			// fmt.Println(i, a)
		}
		fmt.Println(ans)
	}
}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n,B,x,y int
		fmt.Fscan(in,&n,&B,&x,&y)
		var list []int= []int{0}
		for j:=1;j<=n;j++{
			if list[j-1]+x <= B {
				list= append(list,list[j-1]+x)
			} else {
				list= append(list,list[j-1]-y)
			}
		}
		count:=0
		for j:=0;j<len(list);j++{
			count+=list[j]
		}
		fmt.Fprintln(out,count)
	}
}

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		line := readNNums(reader, 4)

		res := solve(line[0], line[1], line[2], line[3])

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

	fmt.Print(buf.String())
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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, B int, x int, y int) int64 {

	var sum int64

	cur := 0

	for i := 1; i <= n; i++ {
		if cur+x <= B {
			cur += x
		} else {
			cur -= y
		}
		sum += int64(cur)
	}

	return sum
}

package main

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

type CF1657B struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1657B) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1657B) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1657B) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1657B) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1657B) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1657B
Date: 5/04/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1657/B
Problem: CF1657B
**/
func (in *CF1657B) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n, B, x, y := in.NextInt(), in.NextInt(), in.NextInt(), in.NextInt()
		last := 0
		sum := int64(0)
		for i := 0; i < n; i++ {
			if last+x <= B {
				last += x
				sum += int64(last)
			} else {
				last -= y
				sum += int64(last)
			}
		}
		fmt.Println(sum)
	}
}

func NewCF1657B(r *bufio.Reader) *CF1657B {
	return &CF1657B{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1657B(bufio.NewReader(os.Stdin)).Run()
}

package main

import (
	"fmt"
)

func main(){
	var t, n, B, x, y int64
	fmt.Scanf("%d ", &t)
	for ;t>0;t-=1{
		fmt.Scanf("%d %d %d %d ", &n, &B, &x, &y)
		sum, tmp := int64(0), int64(0)
		for i:=int64(0);i<n;i+=1{
			if tmp + x <= B{
				tmp += x
			}else{
				tmp -= y
			}
			sum += tmp
		}
		fmt.Printf("%d\n", sum)
	}
}

package main

import "fmt"

func solve() {
    var n uint32
    var b, x, y int64
    fmt.Scan(&n)
    fmt.Scan(&b)
    fmt.Scan(&x)
    fmt.Scan(&y)
    cur := int64(0)
    sum := int64(0)
    for i := uint32(0); i < n; i++ {
        if cur + x <= b {
            cur += x
        } else {
            cur -= y
        }
        sum += cur
    }
    fmt.Println(sum)
}

func main() {
    var t uint32
    fmt.Scan(&t)
    for i := uint32(0); i < t; i++ {
        solve()
    }
}

package main

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

var T, n int
var B, x, y int64

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

	Fscan(in, &T)
	for t := 0; t < T; t++ {
		Fscan(in, &n, &B, &x, &y)
		var last, ans int64
		last, ans = 0, 0
		for i := 1; i <= n; i++ {
			if last + x <= B {
				last = last + x
			} else {
				last = last - y
			}
			ans += last
		}
		Fprintln(out, ans)
	}
}

package main

import "fmt"

func main() {
	var T, n, B, x, y, a, sum int64
	fmt.Scan(&T)
	for ; T > 0; T -- {
		fmt.Scan(&n, &B, &x, &y);
		a, sum = 0, 0
		for ; n > 0; n -- {
			if a + x <= B {
				a += x
			} else {
				a -= y
			}
			sum += a
		}
		fmt.Println(sum)
	}
}

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-- {
		var n, b, x, y int64
		fmt.Fscan(in, &n, &b, &x, &y)

		var sum, val int64
		for i := int64(0); i < n; i++ {
			if t := val + x; t <= b {
				val = t
			} else {
				val -= y
			}
			sum += val
		}

		fmt.Fprintln(out, sum)
	}
}

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 n int
		var b, x, y int64
		fmt.Fscan(in, &n, &b, &x, &y)

		var z, sum int64
		for i := 0; i < n; i++ {
			if z+x <= b {
				z += x
			} else {
				z -= y
			}

			sum += z
		}
		fmt.Fprintln(out, sum)
	}
}

package main

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

/*
1
4 3 8 3
---
5 = -3 -3 2 -1
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n, b, x, y int64
	scanf("%d %d %d %d\n", &n, &b, &x, &y)

	sum := int64(0)

	a := int64(0)

	for i := int64(0); i < n; i++ {
		if a+x <= b {
			a += x
		} else {
			a -= y
		}

		sum += a
	}

	fmt.Fprintln(writer, sum)
}

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

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

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

const maxUint = ^uint(0)

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

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

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

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

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

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

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

	return nums[minNumIdx]
}

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

	return nums[maxNumIdx]
}

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

	return maxNumIdx
}

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

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

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

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

	return true
}

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

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

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

	num = abs(num)

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

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

package main

import "fmt"

func main() {
	k := 0
	fmt.Scanf("%d\n", &k)
	for k > 0 {
		k--
		var n = 0
		var B, x, y uint64
		n, B, x, y = 0, 0, 0, 0
		fmt.Scanf("%d %d %d %d\n", &n, &B, &x, &y)
		var s, c uint64
		for i := 1; i < n+1; i++ {
			if c+x <= B {
				c += x
			} else {
				c -= y
			}
			s += c
		}
		fmt.Println(s)
	}
}

package main

import "fmt"

func main() {
	k := 0
	fmt.Scanf("%d\n", &k)
	for k > 0 {
		k--
		n, B, x, y := 0, 0, 0, 0
		fmt.Scanf("%d %d %d %d\n", &n, &B, &x, &y)
		s := 0
		c := 0
		for i := 1; i < n+1; i++ {
			if c+x <= B {
				c += x
			} else {
				c -= y
			}
			s += c
		}
		fmt.Println(s)
	}
}

package main

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

const (
	INF = 3e5 + 10
)

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

	var t, n int
	var b, x, y int64
	Fscan(in, &t)

	for k := 0; k < t; k++ {
		Fscan(in, &n, &b, &x, &y)
		y += x
		dp := make([][]int64, 2)
		dp[0] = make([]int64, n+1)
		dp[1] = make([]int64, n+1)

		dp[0][0] = 0
		if x <= b {
			dp[1][0] = x
		} else {
			dp[1][0] = -y * int64(n)
		}
		dp[1][1] = x - y
		ans := -y * int64(n)
		for i := 2; i <= n; i++ {

			for j := 0; j <= i; j++ {
				dp[i%2][j] = -y * int64(n)
			}

			for j := 0; j < i; j++ {
				val := int64(i)*x - int64(j)*y

				if val <= b {
					dp[i%2][j] = max(dp[i%2][j], dp[(i-1)%2][j]+val)
				}
				if val-y <= b {
					dp[i%2][j+1] = max(dp[i%2][j+1], dp[(i-1)%2][j]+val-y)
				}
			}
		}
		for j := 0; j < n; j++ {
			ans = max(ans, dp[n%2][j])
		}
		Fprintln(out, ans)
	}
}

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

}

package main

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

const (
	INF = 3e5 + 10
)

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

	var t, n int
	var b, x, y int64
	Fscan(in, &t)

	for k := 0; k < t; k++ {
		Fscan(in, &n, &b, &x, &y)
		y += x
		dp := make([][]int64, 2)
		dp[0] = make([]int64, n+1)
		dp[1] = make([]int64, n+1)

		dp[0][0] = 0
		if x <= b {
			dp[1][0] = x
		} else {
			dp[1][0] = -y * int64(n)
		}
		dp[1][1] = x - y
		ans := -y * int64(n)
		for i := 2; i <= n; i++ {

			for j := 0; j <= i; j++ {
				dp[i%2][j] = -y * int64(n)
			}

			for j := 0; j < i; j++ {
				val := int64(i)*x - int64(j)*y

				if val <= b {
					dp[i%2][j] = max(dp[i%2][j], dp[(i-1)%2][j]+val)
				}
				if val-y <= b {
					dp[i%2][j+1] = max(dp[i%2][j+1], dp[(i-1)%2][j]+val-y)
				}
				if i == n {
					ans = max(ans, dp[i%2][j])
				}
			}
		}
		Fprintln(out, ans)
	}
}

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

}

package main

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

func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}

const mod = 998244353

// 1 2 3 4
func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := 1
	fmt.Fscan(in, &t)

	for ii := 0; ii < t; ii++ {
		var n, b, x, y int
		fmt.Fscan(in, &n, &b, &x, &y)
		last := 0
		sum := 0
		for i := 1; i <= n; i++ {
			if last+x > b {
				last -= y
			} else {
				last += x
			}
			sum += last
		}
		fmt.Fprintln(out, sum)
	}
}

package main

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

func main() {

	reader := bufio.NewReader(os.Stdin)
	writter := bufio.NewWriter(os.Stdout)
	defer writter.Flush()

	t := 0
	fmt.Fscan(reader, &t)

	for t > 0 {
		n, B, x, y := 0, 0, 0, 0
		fmt.Fscan(reader, &n, &B, &x, &y)

		// p := make([]int, n)
		// for i := range p {
		// 	fmt.Fscan(reader, &p[i])
		// }

		fmt.Fprintln(writter, solve(n, B, x, y))

		t--
	}

	//fmt.Println(commonServices.Solve(4, 1, 7, 3))
}

func solve(n, B, x, y int) int {

	result := 0

	array := make([]int, n+1)
	array[0] = 0

	for i := 1; i <= n; i++ {

		next := array[i-1] + x
		if next > B {
			next -= (x + y)
		}

		array[i] = next
		result += next

	}

	//fmt.Println(array)

	return result

}

package main
import "fmt"
import "os"
import "bufio"
//import "math"
//import "sort"
var (
	input = bufio.NewReader(os.Stdin)
	output = bufio.NewWriter(os.Stdout)
)
func main() {
	defer output.Flush()
	count := 0
	fmt.Fscan(input,&count)
	for count>0 {
		count --
		n := 0
		B := 0
		x := 0
		y := 0
		fmt.Fscan(input,&n)
		fmt.Fscan(input,&B)
		fmt.Fscan(input,&x)
		fmt.Fscan(input,&y)
		s := 0
		val := 0
		for i:=1;i<=n;i++ {
			if val+x<=B {
				val += x
				s += val
			} else {
				val -= y
				s += val
			}
		}
		fmt.Fprintln(output,s)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for ; t >= 1; t-- {
		var n, B, x, y int
		fmt.Scanf("%d %d %d %d\n", &n, &B, &x, &y)
		var ans int
		var a int
		for i := 1; i <= n; i++ {
			if x > -y && a+x <= B {
				a += x
			} else if -y > x && a-y <= B {
				a -= y
			} else if a-y <= B {
				a -= y
			} else if a+x <= B {
				a += x
			}
			ans += a
			// fmt.Println(i, a, ans)
		}
		fmt.Println(ans)
	}
}


You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps:  select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$);  if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following:  select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010;  select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010;  select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010;  select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0;  select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00;  select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the maximum number of operations you can perform.

NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.

package main

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

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

var T, n int
var s string

func main() {
	for _, _ = fmt.Fscan(_r, &T); T > 0; T-- {
		_, _ = fmt.Fscan(_r, &n)
		_, _ = fmt.Fscan(_r, &s)
		var lens []int
		for i := 0; i < n; {
			st := i
			for ; i < n && s[i] == s[st]; i++ {
			}
			lens = append(lens, i-st)
		}

		ans := 0
		for i, p := 0, 0; i < len(lens); i++ {
			if p < i {
				p = i
			}
			for ; p < len(lens) && lens[p] == 1; p++ {
			}
			if p < len(lens) {
				lens[p]--
			} else {
				i++
			}
			ans++
		}
		_, _ = fmt.Fprintln(_w, ans)
		_ = _w.Flush()

	}
}

/*
URL:
https://codeforces.com/contest/1430/problem/D
*/

package main

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

var (
	t int

	n int
	S []rune
)

func main() {
	defer stdout.Flush()

	t = readi()
	for tc := 0; tc < t; tc++ {
		n = readi()
		S = readrs()

		ans := solve()
		printf("%d\n", ans)
	}
}

func solve() int {
	res := 0

	_, C := RunLengthEncoding(S)
	B := len(C)
	fp := 0 // 1文字消すポインタ
	sp := 0 // prefixを消すポインタ
	for sp < B {
		// まず最初に、fpは必ずspと同じかそれより後方に位置させる
		for fp < sp {
			fp++
		}

		// fpは2文字以上あるブロックまで移動させる
		for fp < B && C[fp] <= 1 {
			fp++
		}

		// 「1文字消す」に相当する操作
		if fp < B {
			// 2文字以上あるものがあればそれを消す
			C[fp]--
		} else {
			// しょうがないのでspの最後の1文字を消す
			sp++
		}

		// 1文字消せたら操作完了
		res++

		// prefixを消すに相当するポインタ移動
		sp++
	}

	return res
}

// RunLengthEncoding returns encoded slice of an input.
func RunLengthEncoding(S []rune) ([]rune, []int) {
	runes := []rune{}
	lengths := []int{}

	l := 0
	for i := 0; i < len(S); i++ {
		// 1文字目の場合保持
		if i == 0 {
			l = 1
			continue
		}

		if S[i-1] == S[i] {
			// 直前の文字と一致していればインクリメント
			l++
		} else {
			// 不一致のタイミングで追加し、長さをリセットする
			runes = append(runes, S[i-1])
			lengths = append(lengths, l)
			l = 1
		}
	}
	runes = append(runes, S[len(S)-1])
	lengths = append(lengths, l)

	return runes, lengths
}

// RunLengthDecoding decodes RLE results.
func RunLengthDecoding(S []rune, L []int) []rune {
	if len(S) != len(L) {
		panic("S, L are not RunLengthEncoding results")
	}

	res := []rune{}

	for i := 0; i < len(S); i++ {
		for j := 0; j < L[i]; j++ {
			res = append(res, S[i])
		}
	}

	return res
}

/*******************************************************************/

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	reads = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

// mod can calculate a right residual whether value is positive or negative.
func mod(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// chmin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func chmin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// chmax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func chmax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// sum returns multiple integers sum.
func sum(integers ...int) int {
	var s int
	s = 0

	for _, i := range integers {
		s += i
	}

	return s
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  func() string
	stdout *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

func _readInt64() int64 {
	i, err := strconv.ParseInt(reads(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// readis returns an integer slice that has n integers.
func readis(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = readi()
	}
	return b
}

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	return b
}

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

func _readFloat64() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func readfs(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = readf()
	}
	return b
}

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// Printf is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func printf(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*********** Debugging ***********/

// debugf is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func debugf(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

/*
URL:
https://codeforces.com/contest/1430/problem/D
*/

package main

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

var (
	t int

	n int
	S []rune
)

func main() {
	defer stdout.Flush()

	t = readi()
	for tc := 0; tc < t; tc++ {
		n = readi()
		S = readrs()

		ans := solve()
		// printf("%d\n", ans)
		fmt.Println(ans)
	}
}

func solve() int {
	res := 0

	_, C := RunLengthEncoding(S)
	B := len(C)
	fp := 0 // 1文字消すポインタ
	sp := 0 // prefixを消すポインタ
	for sp < B {
		// まず最初に、fpは必ずspと同じかそれより後方に位置させる
		for fp < sp {
			fp++
		}

		// fpは2文字以上あるブロックまで移動させる
		for fp < B && C[fp] <= 1 {
			fp++
		}

		// 「1文字消す」に相当する操作
		if fp < B {
			// 2文字以上あるものがあればそれを消す
			C[fp]--
		} else {
			// しょうがないのでspの最後の1文字を消す
			sp++
		}

		// 1文字消せたら操作完了
		res++

		// prefixを消すに相当するポインタ移動
		sp++
	}

	return res
}

// RunLengthEncoding returns encoded slice of an input.
func RunLengthEncoding(S []rune) ([]rune, []int) {
	runes := []rune{}
	lengths := []int{}

	l := 0
	for i := 0; i < len(S); i++ {
		// 1文字目の場合保持
		if i == 0 {
			l = 1
			continue
		}

		if S[i-1] == S[i] {
			// 直前の文字と一致していればインクリメント
			l++
		} else {
			// 不一致のタイミングで追加し、長さをリセットする
			runes = append(runes, S[i-1])
			lengths = append(lengths, l)
			l = 1
		}
	}
	runes = append(runes, S[len(S)-1])
	lengths = append(lengths, l)

	return runes, lengths
}

// RunLengthDecoding decodes RLE results.
func RunLengthDecoding(S []rune, L []int) []rune {
	if len(S) != len(L) {
		panic("S, L are not RunLengthEncoding results")
	}

	res := []rune{}

	for i := 0; i < len(S); i++ {
		for j := 0; j < L[i]; j++ {
			res = append(res, S[i])
		}
	}

	return res
}

/*******************************************************************/

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	reads = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

// mod can calculate a right residual whether value is positive or negative.
func mod(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// chmin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func chmin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// chmax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func chmax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// sum returns multiple integers sum.
func sum(integers ...int) int {
	var s int
	s = 0

	for _, i := range integers {
		s += i
	}

	return s
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  func() string
	stdout *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

func _readInt64() int64 {
	i, err := strconv.ParseInt(reads(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// readis returns an integer slice that has n integers.
func readis(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = readi()
	}
	return b
}

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	return b
}

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

func _readFloat64() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func readfs(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = readf()
	}
	return b
}

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// Printf is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func printf(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*********** Debugging ***********/

// debugf is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func debugf(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

package main

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

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

	var T, n int
	var s string
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &s)
		c := []int{}
		for i := 0; i < n; {
			st := i
			for ; i < n && s[i] == s[st]; i++ {
			}
			c = append(c, i-st)
		}
		n = len(c)
		ans := 0
		for i, p := 0, 0; i < n; i++ {
			if p < i {
				p = i
			}
			for ; p < n && c[p] <= 1; p++ {
			}
			if p < n {
				c[p]--
			} else {
				i++
			}
			ans++
		}
		Fprintln(out, ans)
	}
}

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

package main

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

type node struct {
	lr       [2]*node
	priority uint
	key      int
	ids      []int
}

func (o *node) cmp(b int) int8 {
	switch {
	case b < o.key:
		return 0
	case b > o.key:
		return 1
	default:
		return -1
	}
}

func (o *node) rotate(d int8) *node {
	x := o.lr[d^1]
	o.lr[d^1] = x.lr[d]
	x.lr[d] = o
	return x
}

type treap struct {
	rd   uint
	root *node
}

func (t *treap) fastRand() uint {
	t.rd ^= t.rd << 13
	t.rd ^= t.rd >> 17
	t.rd ^= t.rd << 5
	return t.rd
}

func (t *treap) _put(o *node, key, i int) *node {
	if o == nil {
		return &node{priority: t.fastRand(), key: key, ids: []int{i}}
	}
	if d := o.cmp(key); d >= 0 {
		o.lr[d] = t._put(o.lr[d], key, i)
		if o.lr[d].priority > o.priority {
			o = o.rotate(d ^ 1)
		}
	} else {
		o.ids = append(o.ids, i)
	}
	return o
}

func (t *treap) put(key, i int) { t.root = t._put(t.root, key, i) }

func (t *treap) _delete(o *node, key int) *node {
	if o == nil {
		return nil
	}
	if d := o.cmp(key); d >= 0 {
		o.lr[d] = t._delete(o.lr[d], key)
	} else {
		if len(o.ids) > 1 {
			o.ids = o.ids[1:]
		} else {
			if o.lr[1] == nil {
				return o.lr[0]
			}
			if o.lr[0] == nil {
				return o.lr[1]
			}
			d = 0
			if o.lr[0].priority > o.lr[1].priority {
				d = 1
			}
			o = o.rotate(d)
			o.lr[d] = t._delete(o.lr[d], key)
		}
	}
	return o
}

func (t *treap) delete(key int) { t.root = t._delete(t.root, key) }

func (t *treap) get(key int) *node {
	for o := t.root; o != nil; {
		if d := o.cmp(key); d >= 0 {
			o = o.lr[d]
		} else {
			return o
		}
	}
	return nil
}

func (t *treap) max() (max *node) {
	for o := t.root; o != nil; o = o.lr[1] {
		max = o
	}
	return
}

func newTreap() *treap { return &treap{rd: 1} }

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

	solve := func(Case int) {
		var n int
		var s []byte
		Fscan(in, &n, &s)

		//t := newTreap()
		cnt := []int{}
		for i := 0; i < n; {
			st := i
			v := s[st]
			for i++; i < n && s[i] == v; i++ {
			}
			//t.put(i-st, len(cnt))
			cnt = append(cnt, i-st)
		}
n = len(cnt)
		ans := 0
		cur := 0
		next := 0
		next2 := 0
		for cur < n {
			if cnt[cur] > 1 {
				//t.delete(cnt[cur])
				cur++

			} else {
				cur++

				if next < cur {
					next = cur
				}
				if next2 < cur {
					next2=cur
				}

				for ; next < n && cnt[next] <= 2; next++ {
				}
				if next < n {
					cnt[next]--
				} else {

					for ; next2 < n && cnt[next2] != 2; next2++ {
					}
					if next2 < n {
						cnt[next2]--
					} else {
						cur++
					}

				}

				//mx := t.max()
				//if mx.key > 1 {
				//	mx.key--
				//	cnt[mx.ids[0]]--
				//} else {
				//	t.delete(cnt[cur])
				//	cur++
				//}
				//if cur < len(cnt) {
				//	t.delete(cnt[cur])
				//	cur++
				//}
			}
			if next < cur {
				next = cur
			}
			if next2 < cur {
				next2=cur
			}

			ans++
		}
		Fprintln(out, ans)
		return
	}

	var t int
	Fscan(in, &t)
	for Case := 1; Case <= t; Case++ {
		solve(Case)
	}
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(reader, &n)

		var s string
		fmt.Fscan(reader, &s)

		fmt.Println(steps(s))
	}

}

func steps(s string) int {
	front := len(s) - 1
	bank := 0
	turns := 0

	for front >= 0 {
		back := front
		for front >= 0 && s[front] == s[back] {
			front--
		}

		bank += back - front - 1
		turns++

		if bank == 0 && front < 0 {
			break
		}

		if bank > 0 {
			bank--
		} else {
			front--
		}
	}

	return turns
}

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

	return b
}

package main

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

type node struct {
	lr       [2]*node
	priority uint
	key      int
	ids []int
}

func (o *node) cmp(b int) int8 {
	switch {
	case b < o.key:
		return 0
	case b > o.key:
		return 1
	default:
		return -1
	}
}

func (o *node) rotate(d int8) *node {
	x := o.lr[d^1]
	o.lr[d^1] = x.lr[d]
	x.lr[d] = o
	return x
}

type treap struct {
	rd   uint
	root *node
}

func (t *treap) fastRand() uint {
	t.rd ^= t.rd << 13
	t.rd ^= t.rd >> 17
	t.rd ^= t.rd << 5
	return t.rd
}

func (t *treap) _put(o *node, key,i int) *node {
	if o == nil {
		return &node{priority: t.fastRand(), key: key, ids : []int{i}}
	}
	if d := o.cmp(key); d >= 0 {
		o.lr[d] = t._put(o.lr[d], key,i)
		if o.lr[d].priority > o.priority {
			o = o.rotate(d ^ 1)
		}
	} else {
		o.ids = append(o.ids, i)
	}
	return o
}

func (t *treap) put(key,i int) { t.root = t._put(t.root, key,i) }

func (t *treap) _delete(o *node, key int) *node {
	if o == nil {
		return nil
	}
	if d := o.cmp(key); d >= 0 {
		o.lr[d] = t._delete(o.lr[d], key)
	} else {
		if len(o.ids) > 1 {
			o.ids = o.ids[1:]
		} else {
			if o.lr[1] == nil {
				return o.lr[0]
			}
			if o.lr[0] == nil {
				return o.lr[1]
			}
			d = 0
			if o.lr[0].priority > o.lr[1].priority {
				d = 1
			}
			o = o.rotate(d)
			o.lr[d] = t._delete(o.lr[d], key)
		}
	}
	return o
}

func (t *treap) delete(key int) { t.root = t._delete(t.root, key) }

func (t *treap) get(key int) *node {
	for o := t.root; o != nil; {
		if d := o.cmp(key); d >= 0 {
			o = o.lr[d]
		} else {
			return o
		}
	}
	return nil
}

func (t *treap) max() (max *node) {
	for o := t.root; o != nil; o = o.lr[1] {
		max = o
	}
	return
}

func newTreap() *treap { return &treap{rd: 1} }

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

	solve := func(Case int) {
		var n int
		var s []byte
		Fscan(in, &n, &s)

		t := newTreap()
		cnt := []int{}
		for i := 0; i < n; {
			st := i
			v := s[st]
			for i++; i < n && s[i] == v; i++ {
			}
			t.put(i-st, len(cnt))
			cnt = append(cnt, i-st)
		}

		ans := 0
		cur := 0
		for cur < len(cnt) {
			if cnt[cur] > 1 {
				t.delete(cnt[cur])
				cur++
			} else {
				mx := t.max()
				if mx.key > 1 {
					mx.key--
					cnt[mx.ids[0]]--
				} else {
					t.delete(cnt[cur])
					cur++
				}
				if cur < len(cnt) {
					t.delete(cnt[cur])
					cur++
				}
			}

			ans++
		}
		Fprintln(out, ans)
		return
	}

	var t int
	Fscan(in, &t)
	for Case := 1; Case <= t; Case++ {
		solve(Case)
	}
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(reader, &n)

		var s string
		fmt.Fscan(reader, &s)

		fmt.Println(steps(s))
	}

}

func steps(s string) int {
	back := len(s) - 1
	front := len(s) - 1

	ans := 0

	for front >= 0 {
		for front > 0 && s[front-1] == s[front] {
			front--
		}

		if front-back > 0 {
			// we have something in the bank
			front = front - 1
			back = front
		} else {
			// we don't have anything in the bank
			front = front - 2
			back = front
		}
		ans++
	}

	if ans == 0 {
		ans++
	}

	return ans
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(reader, &n)

		var s string
		fmt.Fscan(reader, &s)

		fmt.Println(steps(s))
	}

}

func steps(s string) int {
	back := len(s) - 1
	front := len(s) - 1

	ans := 0

	for front >= 0 {
		for front > 0 && s[front-1] == s[front] {
			front--
		}

		if back-front > 0 {
			// we have something in the bank
			front = front - 1
			back = front
		} else {
			// we don't have anything in the bank
			front = front - 2
			back = front
		}
		ans++
	}

	return max(ans, 1)
}

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

	return b
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(reader, &n)

		var s string
		fmt.Fscan(reader, &s)

		fmt.Println(steps(s))
	}

}

func steps(s string) int {
	back := len(s) - 1
	front := len(s) - 1

	ans := 0

	for front >= 0 {
		for front > 0 && s[front-1] == s[front] {
			front--
		}

		if front-back > 0 {
			// we have something in the bank
			front = front - 1
			back = front
		} else {
			// we don't have anything in the bank
			front = front - 2
			back = front
		}
		ans++

	}

	return ans
}