Vasya participates in a ski race along the X axis. The start is at point 0, and the finish is at L, that is, at a distance L meters from the start in the positive direction of the axis. Vasya has been training so hard that he can run one meter in exactly one second.Besides, there are n take-off ramps on the track, each ramp is characterized by four numbers:   xi represents the ramp's coordinate  di represents from how many meters Vasya will land if he goes down this ramp  ti represents the flight time in seconds  pi is the number, indicating for how many meters Vasya should gather speed to get ready and fly off the ramp. As Vasya gathers speed, he should ski on the snow (that is, he should not be flying), but his speed still equals one meter per second. Vasya is allowed to move in any direction on the X axis, but he is prohibited to cross the start line, that is go to the negative semiaxis. Vasya himself chooses which take-off ramps he will use and in what order, that is, he is not obliged to take off from all the ramps he encounters. Specifically, Vasya can skip the ramp. It is guaranteed that xi + di ≤ L, that is, Vasya cannot cross the finish line in flight.Vasya can jump from the ramp only in the positive direction of X axis. More formally, when using the i-th ramp, Vasya starts gathering speed at point xi - pi, jumps at point xi, and lands at point xi + di. He cannot use the ramp in opposite direction.Your task is to find the minimum time that Vasya will spend to cover the distance.

The first line contains two integers n and L (0 ≤ n ≤ 105, 1 ≤ L ≤ 109). Then n lines contain the descriptions of the ramps, each description is on a single line. Each description is a group of four non-negative integers xi, di, ti, pi (0 ≤ xi ≤ L, 1 ≤ di, ti, pi ≤ 109, xi + di ≤ L).

Print in the first line the minimum time in seconds Vasya needs to complete the track. Print in the second line k — the number of take-off ramps that Vasya needs to use, and print on the third line of output k numbers the number the take-off ramps Vasya used in the order in which he used them. Print each number exactly once, separate the numbers with a space. The ramps are numbered starting from 1 in the order in which they are given in the input.

NoteIn the first sample, Vasya cannot use ramp 2, because then he will need to gather speed starting from point -3, which is not permitted by the statement. The optimal option is using ramp 1, the resulting time is: moving to the point of gathering speed + gathering speed until reaching the takeoff ramp + flight time + moving to the finish line = 0 + 5 + 5 + 5 = 15.In the second sample using ramp 1 is not optimal for Vasya as t1 > d1. The optimal option is using ramp 2, the resulting time is: moving to the point of gathering speed + gathering speed until reaching the takeoff ramp + flight time + moving to the finish line = 14 + 1 + 1 + 0 = 16.

package main

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

type ramp struct {
	x, d, t, p int
	index      int // Ramp index, starting from 1
}

func newRamp(x, d, t, p int) *ramp {
	return &ramp{x, d, t, p, 0}
}

func (r ramp) Start() int {
	return r.x - r.p
}

func (r ramp) End() int {
	return r.x + r.d
}

type node struct {
	pos, time int
	prevRamps *rlist
	processed bool
	qindex    int
}

type edge struct {
	pos, time int
	rampIndex int
}

// Implements heap.Interface.
type priorityQueue []*node

func (q priorityQueue) Len() int           { return len(q) }
func (q priorityQueue) Less(i, j int) bool { return q[i].time < q[j].time }
func (q priorityQueue) Swap(i, j int) {
	q[i], q[j] = q[j], q[i]
	q[i].qindex = i
	q[j].qindex = j
}

func (q *priorityQueue) Push(x interface{}) {
	l := q.Len()
	n := x.(*node)
	n.qindex = l
	*q = append(*q, n)
}

func (q *priorityQueue) Pop() interface{} {
	last := q.Len() - 1
	n := (*q)[last]
	n.qindex = -1
	*q = (*q)[:last]
	return n
}

type rlist struct {
	index int
	prev  *rlist
}

func solve(l int, ramps []*ramp) *node {
	for i, r := range ramps {
		r.index = i + 1
	}

	ramps = filterRamps(ramps)

	posMap := make(map[int]bool)
	posMap[0] = true
	posMap[l] = true
	for _, r := range ramps {
		posMap[r.Start()] = true
		posMap[r.End()] = true
	}

	positions := make([]int, 0, len(ramps)*2+2)
	for pos := range posMap {
		positions = append(positions, pos)
	}
	sort.Ints(positions)

	// Construct Nodes
	nodes := make(map[int]*node)
	for _, pos := range positions {
		var time int
		if pos != 0 {
			time = math.MaxInt32
		}
		n := &node{pos, time, nil, false, -1}
		nodes[pos] = n
	}

	// Construct Edges
	edges := make(map[int][]*edge)

	for i := 0; i < len(positions)-1; i++ {
		start := positions[i]
		end := positions[i+1]
		dist := end - start

		edges[start] = append(edges[start], &edge{end, dist, 0})
		edges[end] = append(edges[end], &edge{start, dist, 0})
	}

	for _, r := range ramps {
		e := &edge{
			pos:       r.End(),
			time:      r.p + r.t,
			rampIndex: r.index,
		}
		edges[r.Start()] = append(edges[r.Start()], e)
	}

	// Run dijkstra's algorithm.
	q := make(priorityQueue, 0, len(positions))
	heap.Push(&q, nodes[0])

	for q.Len() > 0 {
		cur := heap.Pop(&q).(*node)
		cur.processed = true

		if cur.pos == l {
			return cur
		}

		// Update adjacent nodes.
		for _, e := range edges[cur.pos] {
			dest := nodes[e.pos]
			if dest.processed {
				continue
			}

			newTime := cur.time + e.time
			if newTime < dest.time {
				dest.time = newTime
				if e.rampIndex > 0 {
					dest.prevRamps = &rlist{e.rampIndex, cur.prevRamps}
				} else {
					dest.prevRamps = cur.prevRamps
				}

				if dest.qindex != -1 {
					heap.Fix(&q, dest.qindex)
				} else {
					heap.Push(&q, dest)
				}
			}
		}
	}

	return nil
}

func filterRamps(ramps []*ramp) []*ramp {
	result := ramps[:0]
	for _, r := range ramps {
		if r.Start() >= 0 && r.t < r.d {
			result = append(result, r)
		}
	}
	return result
}

func reconstructRamps(prevRamps *rlist) []int {
	var result []int
	for cur := prevRamps; cur != nil; cur = cur.prev {
		result = append(result, cur.index)
	}
	for i := 0; i < len(result)/2; i++ {
		opp := len(result) - i - 1
		result[i], result[opp] = result[opp], result[i]
	}

	return result
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	tokens := strings.Split(scanner.Text(), " ")
	n, _ := strconv.Atoi(tokens[0])
	l, _ := strconv.Atoi(tokens[1])

	ramps := make([]*ramp, 0, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		tokens := strings.Split(scanner.Text(), " ")
		x, _ := strconv.Atoi(tokens[0])
		d, _ := strconv.Atoi(tokens[1])
		t, _ := strconv.Atoi(tokens[2])
		p, _ := strconv.Atoi(tokens[3])
		ramps = append(ramps, newRamp(x, d, t, p))
	}

	result := solve(l, ramps)
	usedRamps := reconstructRamps(result.prevRamps)

	fmt.Println(result.time)
	fmt.Println(len(usedRamps))
	if len(usedRamps) > 0 {
		for i, usedRamp := range usedRamps {
			if i > 0 {
				fmt.Print(" ")
			}
			fmt.Print(usedRamp)
		}
		fmt.Println()
	}
}

package main

import (
	"container/heap"
	"fmt"
	"sort"
)

type ramp struct {
	x, d, t, p int
	index      int // Ramp index, starting from 1
}

func newRamp(x, d, t, p int) *ramp {
	return &ramp{x, d, t, p, 0}
}

func (r ramp) Start() int {
	return r.x - r.p
}

func (r ramp) End() int {
	return r.x + r.d
}

type node struct {
	pos, time int
	prevRamps *rlist
	qindex    int
}

type edge struct {
	pos, time int
	rampIndex int
}

// Implements container/heap.Interface
type queue []*node

func (q queue) Len() int { return len(q) }
func (q queue) Less(i, j int) bool {
	if q[i].time < q[j].time {
		return true
	}
	if q[i].time > q[j].time {
		return false
	}

	return q[i].pos < q[j].pos
}

func (q queue) Swap(i, j int) {
	q[i], q[j] = q[j], q[i]
	q[i].qindex = i
	q[j].qindex = j
}

func (q *queue) Push(x interface{}) {
	n := x.(*node)
	n.qindex = q.Len()
	*q = append(*q, n)
}

func (q *queue) Pop() interface{} {
	n := len(*q)
	x := (*q)[n-1]
	x.qindex = -1
	*q = (*q)[:n-1]
	return x
}

type rlist struct {
	index int
	prev  *rlist
}

func solve(l int, ramps []*ramp) *node {
	for i, r := range ramps {
		r.index = i + 1
	}

	sort.SliceStable(ramps, lessRamp(ramps))
	ramps = filterRamps(ramps)

	posMap := make(map[int]bool)
	posMap[0] = true
	posMap[l] = true
	for _, r := range ramps {
		posMap[r.Start()] = true
		posMap[r.End()] = true
	}

	positions := make([]int, 0, len(ramps)*2+2)
	for pos := range posMap {
		positions = append(positions, pos)
	}
	sort.Ints(positions)

	// Construct Nodes
	nodes := make(map[int]*node)
	q := make(queue, 0, len(positions))
	for i, pos := range positions {
		n := &node{pos, pos, nil, i}
		nodes[pos] = n
		q = append(q, n)
	}

	// Construct Edges
	edges := make(map[int][]*edge)

	for i := 0; i < len(positions)-1; i++ {
		start := positions[i]
		end := positions[i+1]
		dist := end - start

		edges[start] = append(edges[start], &edge{end, dist, 0})
		edges[end] = append(edges[end], &edge{start, dist, 0})
	}

	for _, r := range ramps {
		e := &edge{
			pos:       r.End(),
			time:      r.p + r.t,
			rampIndex: r.index,
		}
		edges[r.Start()] = append(edges[r.Start()], e)
	}

	// Run dijkstra's algorithm.
	heap.Init(&q)

	for q.Len() > 0 {
		cur := heap.Pop(&q).(*node)
		if cur.pos == l {
			return cur
		}

		// Update adjacent nodes.
		for _, e := range edges[cur.pos] {
			dest := nodes[e.pos]
			// This means the dest node is visited.
			if dest.qindex == -1 {
				continue
			}

			if cur.time+e.time < dest.time {
				dest.time = cur.time + e.time
				if e.rampIndex > 0 {
					dest.prevRamps = &rlist{e.rampIndex, cur.prevRamps}
				} else {
					dest.prevRamps = cur.prevRamps
				}

				heap.Fix(&q, dest.qindex)
			}
		}
	}

	return nil
}

func lessRamp(ramps []*ramp) func(i, j int) bool {
	return func(i, j int) bool {
		return ramps[i].Start() < ramps[j].Start()
	}
}

func filterRamps(ramps []*ramp) []*ramp {
	result := ramps[:0]
	for _, r := range ramps {
		if r.Start() >= 0 && r.t < r.d {
			result = append(result, r)
		}
	}
	return result
}

func reconstructRamps(prevRamps *rlist) []int {
	var result []int
	for cur := prevRamps; cur != nil; cur = cur.prev {
		result = append(result, cur.index)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(result)))

	return result
}

func main() {
	var n, l int
	fmt.Scan(&n)
	fmt.Scan(&l)

	ramps := make([]*ramp, 0, n)
	for i := 0; i < n; i++ {
		var x, d, t, p int
		fmt.Scan(&x)
		fmt.Scan(&d)
		fmt.Scan(&t)
		fmt.Scan(&p)
		ramps = append(ramps, newRamp(x, d, t, p))
	}

	result := solve(l, ramps)
	usedRamps := reconstructRamps(result.prevRamps)

	fmt.Println(result.time)
	fmt.Println(len(usedRamps))
	for i, usedRamp := range usedRamps {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(usedRamp)
	}
	fmt.Println()
}

package main

import (
	"container/heap"
	"fmt"
	"math"
	"sort"
)

type ramp struct {
	x, d, t, p int
	index      int // Ramp index, starting from 1
}

func newRamp(x, d, t, p int) *ramp {
	return &ramp{x, d, t, p, 0}
}

func (r ramp) Start() int {
	return r.x - r.p
}

func (r ramp) End() int {
	return r.x + r.d
}

type node struct {
	pos, time int
	prevRamps *rlist
	qindex    int
	processed bool
}

type edge struct {
	pos, time int
	rampIndex int
}

// Implements container/heap.Interface
type queue []*node

func (q queue) Len() int           { return len(q) }
func (q queue) Less(i, j int) bool { return q[i].time < q[j].time }

func (q queue) Swap(i, j int) {
	q[i], q[j] = q[j], q[i]
	q[i].qindex = i
	q[j].qindex = j
}

func (q *queue) Push(x interface{}) {
	n := x.(*node)
	n.qindex = q.Len()
	*q = append(*q, n)
}

func (q *queue) Pop() interface{} {
	n := len(*q)
	x := (*q)[n-1]
	x.qindex = -1
	*q = (*q)[:n-1]
	return x
}

type rlist struct {
	index int
	prev  *rlist
}

func solve(l int, ramps []*ramp) *node {
	for i, r := range ramps {
		r.index = i + 1
	}

	ramps = filterRamps(ramps)

	posMap := make(map[int]bool)
	posMap[0] = true
	posMap[l] = true
	for _, r := range ramps {
		posMap[r.Start()] = true
		posMap[r.End()] = true
	}

	positions := make([]int, 0, len(ramps)*2+2)
	for pos := range posMap {
		positions = append(positions, pos)
	}
	sort.Ints(positions)

	// Construct Nodes
	nodes := make(map[int]*node)
	for _, pos := range positions {
		var time int
		if pos != 0 {
			time = math.MaxInt32
		}
		n := &node{pos, time, nil, -1, false}
		nodes[pos] = n
	}

	// Construct Edges
	edges := make(map[int][]*edge)

	for i := 0; i < len(positions)-1; i++ {
		start := positions[i]
		end := positions[i+1]
		dist := end - start

		edges[start] = append(edges[start], &edge{end, dist, 0})
		edges[end] = append(edges[end], &edge{start, dist, 0})
	}

	for _, r := range ramps {
		e := &edge{
			pos:       r.End(),
			time:      r.p + r.t,
			rampIndex: r.index,
		}
		edges[r.Start()] = append(edges[r.Start()], e)
	}

	// Run dijkstra's algorithm.
	q := make(queue, 0, len(positions))
	heap.Push(&q, nodes[0])

	for q.Len() > 0 {
		cur := heap.Pop(&q).(*node)
		cur.processed = true

		if cur.pos == l {
			return cur
		}

		// Update adjacent nodes.
		for _, e := range edges[cur.pos] {
			dest := nodes[e.pos]
			if dest.processed {
				continue
			}

			if cur.time+e.time < dest.time {
				dest.time = cur.time + e.time
				if e.rampIndex > 0 {
					dest.prevRamps = &rlist{e.rampIndex, cur.prevRamps}
				} else {
					dest.prevRamps = cur.prevRamps
				}

				if dest.qindex != -1 {
					heap.Fix(&q, dest.qindex)
				} else {
					heap.Push(&q, dest)
				}
			}
		}
	}

	return nil
}

func filterRamps(ramps []*ramp) []*ramp {
	result := ramps[:0]
	for _, r := range ramps {
		if r.Start() >= 0 && r.t < r.d {
			result = append(result, r)
		}
	}
	return result
}

func reconstructRamps(prevRamps *rlist) []int {
	var result []int
	for cur := prevRamps; cur != nil; cur = cur.prev {
		result = append(result, cur.index)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(result)))

	return result
}

func main() {
	var n, l int
	fmt.Scan(&n)
	fmt.Scan(&l)

	ramps := make([]*ramp, 0, n)
	for i := 0; i < n; i++ {
		var x, d, t, p int
		fmt.Scan(&x)
		fmt.Scan(&d)
		fmt.Scan(&t)
		fmt.Scan(&p)
		ramps = append(ramps, newRamp(x, d, t, p))
	}

	result := solve(l, ramps)
	usedRamps := reconstructRamps(result.prevRamps)

	fmt.Println(result.time)
	fmt.Println(len(usedRamps))
	for i, usedRamp := range usedRamps {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(usedRamp)
	}
	fmt.Println()
}

package main

import (
	"container/heap"
	"fmt"
	"sort"
)

type ramp struct {
	x, d, t, p int
	index      int // Ramp index, starting from 1
}

func newRamp(x, d, t, p int) *ramp {
	return &ramp{x, d, t, p, 0}
}

func (r ramp) Start() int {
	return r.x - r.p
}

func (r ramp) End() int {
	return r.x + r.d
}

type node struct {
	pos, time int
	prevRamps *rlist
	qindex    int
}

type edge struct {
	pos, time int
	rampIndex int
}

// Implements container/heap.Interface
type queue []*node

func (q queue) Len() int           { return len(q) }
func (q queue) Less(i, j int) bool { return q[i].time < q[j].time }

func (q queue) Swap(i, j int) {
	q[i], q[j] = q[j], q[i]
	q[i].qindex = i
	q[j].qindex = j
}

func (q *queue) Push(x interface{}) {
	n := x.(*node)
	n.qindex = q.Len()
	*q = append(*q, n)
}

func (q *queue) Pop() interface{} {
	n := len(*q)
	x := (*q)[n-1]
	x.qindex = -1
	*q = (*q)[:n-1]
	return x
}

type rlist struct {
	index int
	prev  *rlist
}

func solve(l int, ramps []*ramp) *node {
	for i, r := range ramps {
		r.index = i + 1
	}

	sort.SliceStable(ramps, lessRamp(ramps))
	ramps = filterRamps(ramps)

	posMap := make(map[int]bool)
	posMap[0] = true
	posMap[l] = true
	for _, r := range ramps {
		posMap[r.Start()] = true
		posMap[r.End()] = true
	}

	positions := make([]int, 0, len(ramps)*2+2)
	for pos := range posMap {
		positions = append(positions, pos)
	}
	sort.Ints(positions)

	// Construct Nodes
	nodes := make(map[int]*node)
	q := make(queue, 0, len(positions))
	for i, pos := range positions {
		n := &node{pos, pos, nil, i}
		nodes[pos] = n
		q = append(q, n)
	}

	// Construct Edges
	edges := make(map[int][]*edge)

	for i := 0; i < len(positions)-1; i++ {
		start := positions[i]
		end := positions[i+1]
		dist := end - start

		edges[start] = append(edges[start], &edge{end, dist, 0})
		edges[end] = append(edges[end], &edge{start, dist, 0})
	}

	for _, r := range ramps {
		e := &edge{
			pos:       r.End(),
			time:      r.p + r.t,
			rampIndex: r.index,
		}
		edges[r.Start()] = append(edges[r.Start()], e)
	}

	// Run dijkstra's algorithm.
	heap.Init(&q)

	for q.Len() > 0 {
		cur := heap.Pop(&q).(*node)
		if cur.pos == l {
			return cur
		}

		// Update adjacent nodes.
		for _, e := range edges[cur.pos] {
			dest := nodes[e.pos]
			// This means the dest node is visited.
			if dest.qindex == -1 {
				continue
			}

			if cur.time+e.time < dest.time {
				dest.time = cur.time + e.time
				if e.rampIndex > 0 {
					dest.prevRamps = &rlist{e.rampIndex, cur.prevRamps}
				} else {
					dest.prevRamps = cur.prevRamps
				}

				heap.Fix(&q, dest.qindex)
			}
		}
	}

	return nil
}

func lessRamp(ramps []*ramp) func(i, j int) bool {
	return func(i, j int) bool {
		return ramps[i].Start() < ramps[j].Start()
	}
}

func filterRamps(ramps []*ramp) []*ramp {
	result := ramps[:0]
	for _, r := range ramps {
		if r.Start() >= 0 && r.t < r.d {
			result = append(result, r)
		}
	}
	return result
}

func reconstructRamps(prevRamps *rlist) []int {
	var result []int
	for cur := prevRamps; cur != nil; cur = cur.prev {
		result = append(result, cur.index)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(result)))

	return result
}

func main() {
	var n, l int
	fmt.Scan(&n)
	fmt.Scan(&l)

	ramps := make([]*ramp, 0, n)
	for i := 0; i < n; i++ {
		var x, d, t, p int
		fmt.Scan(&x)
		fmt.Scan(&d)
		fmt.Scan(&t)
		fmt.Scan(&p)
		ramps = append(ramps, newRamp(x, d, t, p))
	}

	result := solve(l, ramps)
	usedRamps := reconstructRamps(result.prevRamps)

	fmt.Println(result.time)
	fmt.Println(len(usedRamps))
	for i, usedRamp := range usedRamps {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(usedRamp)
	}
	fmt.Println()
}

package main

import (
	"container/heap"
	"fmt"
	"sort"
)

type ramp struct {
	x, d, t, p int
	index      int // Ramp index, starting from 1
}

func newRamp(x, d, t, p int) *ramp {
	return &ramp{x, d, t, p, 0}
}

func (r ramp) Start() int {
	return r.x - r.p
}

func (r ramp) End() int {
	return r.x + r.d
}

type node struct {
	pos, time int
	prevRamps *rlist
	qindex    int
}

type edge struct {
	pos, time int
	rampIndex int
}

// Implements container/heap.Interface
type queue []*node

func (q queue) Len() int           { return len(q) }
func (q queue) Less(i, j int) bool { return q[i].time < q[j].time }

func (q queue) Swap(i, j int) {
	q[i], q[j] = q[j], q[i]
	q[i].qindex = i
	q[j].qindex = j
}

func (q *queue) Push(x interface{}) {
	n := x.(*node)
	n.qindex = q.Len()
	*q = append(*q, n)
}

func (q *queue) Pop() interface{} {
	n := len(*q)
	x := (*q)[n-1]
	x.qindex = -1
	*q = (*q)[:n-1]
	return x
}

type rlist struct {
	index int
	prev  *rlist
}

func solve(l int, ramps []*ramp) *node {
	for i, r := range ramps {
		r.index = i + 1
	}

	sort.SliceStable(ramps, lessRamp(ramps))
	ramps = filterRamps(ramps)

	posMap := make(map[int]bool)
	posMap[0] = true
	posMap[l] = true
	for _, r := range ramps {
		posMap[r.Start()] = true
		posMap[r.End()] = true
	}

	positions := make([]int, 0, len(ramps)*2+2)
	for pos := range posMap {
		positions = append(positions, pos)
	}
	sort.Ints(positions)

	// Construct Nodes
	nodes := make(map[int]*node)
	q := make(queue, 0, len(positions))
	for i, pos := range positions {
		n := &node{pos, pos, nil, i}
		nodes[pos] = n
		q = append(q, n)
	}

	// Construct Edges
	edges := make(map[int][]*edge)

	for i := 0; i < len(positions)-1; i++ {
		start := positions[i]
		end := positions[i+1]

		e := &edge{
			pos:  end,
			time: end - start,
		}
		edges[start] = append(edges[start], e)
	}

	for _, r := range ramps {
		e := &edge{
			pos:       r.End(),
			time:      r.p + r.t,
			rampIndex: r.index,
		}
		edges[r.Start()] = append(edges[r.Start()], e)
	}

	// Run dijkstra's algorithm.
	heap.Init(&q)

	for q.Len() > 0 {
		cur := heap.Pop(&q).(*node)
		if cur.pos == l {
			return cur
		}

		// Update adjacent nodes.
		for _, e := range edges[cur.pos] {
			dest := nodes[e.pos]
			// This means the dest node is visited.
			if dest.qindex == -1 {
				continue
			}

			if cur.time+e.time < dest.time {
				dest.time = cur.time + e.time
				if e.rampIndex > 0 {
					dest.prevRamps = &rlist{e.rampIndex, cur.prevRamps}
				} else {
					dest.prevRamps = cur.prevRamps
				}

				heap.Fix(&q, dest.qindex)
			}
		}
	}

	return nil
}

func lessRamp(ramps []*ramp) func(i, j int) bool {
	return func(i, j int) bool {
		return ramps[i].Start() < ramps[j].Start()
	}
}

func filterRamps(ramps []*ramp) []*ramp {
	result := ramps[:0]
	for _, r := range ramps {
		if r.Start() >= 0 && r.t < r.d {
			result = append(result, r)
		}
	}
	return result
}

func reconstructRamps(prevRamps *rlist) []int {
	var result []int
	for cur := prevRamps; cur != nil; cur = cur.prev {
		result = append(result, cur.index)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(result)))

	return result
}

func main() {
	var n, l int
	fmt.Scan(&n)
	fmt.Scan(&l)

	ramps := make([]*ramp, 0, n)
	for i := 0; i < n; i++ {
		var x, d, t, p int
		fmt.Scan(&x)
		fmt.Scan(&d)
		fmt.Scan(&t)
		fmt.Scan(&p)
		ramps = append(ramps, newRamp(x, d, t, p))
	}

	result := solve(l, ramps)
	usedRamps := reconstructRamps(result.prevRamps)

	fmt.Println(result.time)
	fmt.Println(len(usedRamps))
	for i, usedRamp := range usedRamps {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(usedRamp)
	}
	fmt.Println()
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, l int
	fmt.Scan(&n)
	fmt.Scan(&l)

	ramps := make([]*ramp, 0, n)
	for i := 0; i < n; i++ {
		var x, d, t, p int
		fmt.Scan(&x)
		fmt.Scan(&d)
		fmt.Scan(&t)
		fmt.Scan(&p)
		ramps = append(ramps, newRamp(x, d, t, p))
	}

	result := solve(l, ramps)
	usedRamps := reconstructRamps(result.prevRamps)

	fmt.Println(result.time)
	fmt.Println(len(usedRamps))
	for i, usedRamp := range usedRamps {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(usedRamp)
	}
	fmt.Println()
}

type ramp struct {
	x, d, t, p int
	index      int // Ramp index, starting from 1
	start      int // Starting point (x - p)
}

func newRamp(x, d, t, p int) *ramp {
	return &ramp{x, d, t, p, 0, 0}
}

func (r *ramp) String() string {
	return fmt.Sprintf("(%v %v %v %v)", r.x, r.d, r.t, r.p)
}

type progress struct {
	pos, time int
	prevRamps *rlist
}

type rlist struct {
	index int
	prev  *rlist
}

func solve(l int, ramps []*ramp) *progress {
	for i, r := range ramps {
		r.index = i + 1
		r.start = r.x - r.p
	}

	sort.SliceStable(ramps, lessRamp(ramps))
	ramps = filterRamps(ramps)

	queue := make([]*progress, 0, len(ramps)*2)
	queue = append(queue, &progress{})

	for len(queue) > 0 {
		cur := queue[0]
		if cur.pos == l {
			return cur
		}

		queue = queue[1:]
		queue = filterQueue(queue, cur)

		for _, future := range queue {
			newTime := future.time + future.pos - cur.pos
			if newTime < cur.time {
				cur.time = newTime
				cur.prevRamps = future.prevRamps
			}
		}

		// Process ramps that can be taken from here.
		for len(ramps) > 0 && ramps[0].start == cur.pos {
			r := ramps[0]
			ramps = ramps[1:]
			newProgress := &progress{
				pos:       r.x + r.d,
				time:      cur.time + r.p + r.t,
				prevRamps: &rlist{index: r.index, prev: cur.prevRamps},
			}
			queue = enqueue(queue, newProgress)
		}

		// Enqueue the next ramp start position or the goal line.
		var nextPos int
		if len(ramps) > 0 {
			nextPos = ramps[0].start
		} else {
			nextPos = l
		}

		newProgress := &progress{
			pos:       nextPos,
			time:      cur.time + (nextPos - cur.pos),
			prevRamps: cur.prevRamps,
		}
		queue = enqueue(queue, newProgress)
	}

	return nil
}

func lessRamp(ramps []*ramp) func(i, j int) bool {
	return func(i, j int) bool {
		return ramps[i].start < ramps[j].start
	}
}

func filterRamps(ramps []*ramp) []*ramp {
	result := ramps[:0]
	for _, r := range ramps {
		if r.start >= 0 && r.t < r.d {
			result = append(result, r)
		}
	}
	return result
}

func filterQueue(queue []*progress, cur *progress) []*progress {
	result := queue[:0]
	for _, future := range queue {
		if cur.time+(future.pos-cur.pos) > future.time {
			result = append(result, future)
		}
	}
	return result
}

func enqueue(queue []*progress, newProgress *progress) []*progress {
	i := 0
	for ; i < len(queue); i++ {
		if queue[i].pos < newProgress.pos {
			continue
		}

		if queue[i].pos == newProgress.pos {
			if queue[i].time <= newProgress.time {
				return queue
			}

			queue = append(queue[:i], append([]*progress{newProgress}, queue[i+1:]...)...)
			return queue
		}

		break
	}

	queue = append(queue[:i], append([]*progress{newProgress}, queue[i:]...)...)
	return queue
}

func reconstructRamps(prevRamps *rlist) []int {
	var result []int
	for cur := prevRamps; cur != nil; cur = cur.prev {
		result = append(result, cur.index)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(result)))

	return result
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, l int
	fmt.Scan(&n)
	fmt.Scan(&l)

	ramps := make([]*ramp, 0, n)
	for i := 0; i < n; i++ {
		var x, d, t, p int
		fmt.Scan(&x)
		fmt.Scan(&d)
		fmt.Scan(&t)
		fmt.Scan(&p)
		ramps = append(ramps, newRamp(x, d, t, p))
	}

	result := solve(l, ramps)
	usedRamps := reconstructRamps(result.prevRamps)

	fmt.Println(result.time)
	fmt.Println(len(usedRamps))
	for i, usedRamp := range usedRamps {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(usedRamp)
	}
	fmt.Println()
}

type ramp struct {
	x, d, t, p int
	index      int // Ramp index, starting from 1
	start      int // Starting point (x - p)
}

func newRamp(x, d, t, p int) *ramp {
	return &ramp{x, d, t, p, 0, 0}
}

func (r *ramp) String() string {
	return fmt.Sprintf("(%v %v %v %v)", r.x, r.d, r.t, r.p)
}

type progress struct {
	pos, time int
	prevRamps *rlist
}

type rlist struct {
	index int
	prev  *rlist
}

func solve(l int, ramps []*ramp) *progress {
	for i, r := range ramps {
		r.index = i + 1
		r.start = r.x - r.p
	}

	sort.Slice(ramps, lessRamp(ramps))
	ramps = filterRamps(ramps)

	queue := make([]*progress, 0, len(ramps)*2)
	queue = append(queue, &progress{})

	for len(queue) > 0 {
		cur := queue[0]
		if cur.pos == l {
			return cur
		}

		queue = queue[1:]
		queue = filterQueue(queue, cur)

		for _, future := range queue {
			newTime := future.time + future.pos - cur.pos
			if newTime < cur.time {
				cur.time = newTime
				cur.prevRamps = future.prevRamps
			}
		}

		// Process ramps that can be taken from here.
		for len(ramps) > 0 && ramps[0].start == cur.pos {
			r := ramps[0]
			ramps = ramps[1:]
			newProgress := &progress{
				pos:       r.x + r.d,
				time:      cur.time + r.p + r.t,
				prevRamps: &rlist{index: r.index, prev: cur.prevRamps},
			}
			queue = enqueue(queue, newProgress)
		}

		// Enqueue the next ramp start position or the goal line.
		var nextPos int
		if len(ramps) > 0 {
			nextPos = ramps[0].start
		} else {
			nextPos = l
		}

		newProgress := &progress{
			pos:       nextPos,
			time:      cur.time + (nextPos - cur.pos),
			prevRamps: cur.prevRamps,
		}
		queue = enqueue(queue, newProgress)
	}

	return nil
}

func lessRamp(ramps []*ramp) func(i, j int) bool {
	return func(i, j int) bool {
		return ramps[i].start < ramps[j].start
	}
}

func filterRamps(ramps []*ramp) []*ramp {
	result := ramps[:0]
	for _, r := range ramps {
		if r.start >= 0 && r.t < r.d {
			result = append(result, r)
		}
	}
	return result
}

func filterQueue(queue []*progress, cur *progress) []*progress {
	result := queue[:0]
	for _, future := range queue {
		if cur.time+(future.pos-cur.pos) > future.time {
			result = append(result, future)
		}
	}
	return result
}

func enqueue(queue []*progress, newProgress *progress) []*progress {
	i := 0
	for ; i < len(queue); i++ {
		if queue[i].pos < newProgress.pos {
			continue
		}

		if queue[i].pos == newProgress.pos {
			if queue[i].time <= newProgress.time {
				return queue
			}

			queue = append(queue[:i], append([]*progress{newProgress}, queue[i+1:]...)...)
			return queue
		}

		break
	}

	queue = append(queue[:i], append([]*progress{newProgress}, queue[i:]...)...)
	return queue
}

func reconstructRamps(prevRamps *rlist) []int {
	var result []int
	for cur := prevRamps; cur != nil; cur = cur.prev {
		result = append(result, cur.index)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(result)))

	return result
}

package main

import (
	"container/heap"
	"fmt"
	"math"
	"sort"
)

type ramp struct {
	x, d, t, p int
	index      int // Ramp index, starting from 1
}

func newRamp(x, d, t, p, index int) *ramp {
	return &ramp{x, d, t, p, index}
}

func (r ramp) Start() int {
	return r.x - r.p
}

func (r ramp) End() int {
	return r.x + r.d
}

type queueElem struct {
	pos, time int
	prevRamps *rlist
	processed bool
	inQueue   bool
	qindex    int
}

type edge struct {
	start, end, time int
	rampIndex        int
}

// Implements container/heap.Interface
type queue []*queueElem

func (q queue) Len() int { return len(q) }
func (q queue) Less(i, j int) bool {
	if q[i].time < q[j].time {
		return true
	}
	if q[i].time > q[j].time {
		return false
	}

	return q[i].pos < q[j].pos
}

func (q queue) Swap(i, j int) {
	q[i], q[j] = q[j], q[i]
	q[i].qindex = i
	q[j].qindex = j
}

func (q *queue) Push(x interface{}) {
	n := x.(*queueElem)
	n.qindex = q.Len()
	*q = append(*q, n)
}

func (q *queue) Pop() interface{} {
	n := len(*q)
	x := (*q)[n-1]
	x.qindex = -1
	*q = (*q)[:n-1]
	return x
}

type rlist struct {
	index int
	prev  *rlist
}

func solve(l int, ramps []*ramp) *queueElem {
	// Filter out invalid ramps.
	ramps = filterRamps(ramps, l)

	// List up all the vertices.
	posMap := make(map[int]bool)
	posMap[0] = true
	posMap[l] = true
	for _, r := range ramps {
		posMap[r.Start()] = true
		posMap[r.End()] = true
	}

	vertices := make([]int, 0, len(ramps)*2+2)
	for pos := range posMap {
		vertices = append(vertices, pos)
	}
	sort.Ints(vertices)

	// List up all the edges.
	edges := make(map[int][]*edge)
	for i := 0; i < len(vertices)-1; i++ {
		start := vertices[i]
		end := vertices[i+1]
		time := end - start
		edges[start] = append(edges[start], &edge{start, end, time, 0})
		edges[end] = append(edges[end], &edge{end, start, time, 0})
	}

	for _, r := range ramps {
		start := r.Start()
		end := r.End()
		time := r.p + r.t
		edges[start] = append(edges[start], &edge{start, end, time, r.index})
	}

	// Run Dijkstra's shortest path algorithm.
	elements := make(map[int]*queueElem)
	for _, pos := range vertices {
		var time int
		if pos != 0 {
			time = math.MaxInt32
		}
		elements[pos] = &queueElem{pos: pos, time: time}
	}

	pq := make(queue, 0, len(vertices))
	heap.Push(&pq, elements[0])

	for pq.Len() > 0 {
		elem := heap.Pop(&pq).(*queueElem)
		elem.processed = true

		if elem.pos == l {
			// Found the solution.
			return elem
		}

		// Find all edges from this vertex.
		for _, e := range edges[elem.pos] {
			endElem := elements[e.end]
			if endElem.processed {
				continue
			}

			newTime := elem.time + e.time
			if newTime < endElem.time {
				if endElem.inQueue {
					heap.Remove(&pq, endElem.qindex)
				}
				endElem.time = newTime
				if e.rampIndex > 0 {
					endElem.prevRamps = &rlist{e.rampIndex, elem.prevRamps}
				} else {
					endElem.prevRamps = elem.prevRamps
				}
				endElem.inQueue = true
				heap.Push(&pq, endElem)
			}
		}
	}

	return nil
}

func filterRamps(ramps []*ramp, l int) []*ramp {
	result := make([]*ramp, 0, len(ramps))
	for _, r := range ramps {
		if r.Start() >= 0 && r.End() <= l && r.t < r.d {
			result = append(result, r)
		}
	}
	return result
}

func reconstructRamps(prevRamps *rlist) []int {
	var result []int
	for cur := prevRamps; cur != nil; cur = cur.prev {
		result = append(result, cur.index)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(result)))

	return result
}

func main() {
	var n, l int
	fmt.Scan(&n)
	fmt.Scan(&l)

	ramps := make([]*ramp, 0, n)
	rampIndex := 0
	for i := 0; i < n; i++ {
		var x, d, t, p int
		fmt.Scan(&x)
		fmt.Scan(&d)
		fmt.Scan(&t)
		fmt.Scan(&p)
		rampIndex++
		ramps = append(ramps, newRamp(x, d, t, p, rampIndex))
	}

	result := solve(l, ramps)
	usedRamps := reconstructRamps(result.prevRamps)

	fmt.Println(result.time)
	fmt.Println(len(usedRamps))
	for i, usedRamp := range usedRamps {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(usedRamp)
	}
	fmt.Println()
}


It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?

First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).  Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).

Output a single integer — the minimum day at which Borya can visit the last doctor.

NoteIn the first sample case, Borya can visit all doctors on days 2, 3 and 4.In the second sample case, Borya can visit all doctors on days 10 and 11.

package main

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

func solve() {
	n := readInt()
	s := make([]int, n)
	d := make([]int, n)
	for i := 0; i < n; i++ {
		s[i] = readInt()
		d[i] = readInt()
	}
	cur := s[0] + 1
	for i := 1; i < n; i++ {
		p := s[i]
		for p < cur {
			p += d[i]
		}
		cur = p + 1
	}

	fmt.Println(cur - 1)
}

var scanner *bufio.Scanner

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

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

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

// IO

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

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

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

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

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

package main

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

func Init() {
}

func Solve(io *FastIO) {
	N := io.NextInt()

	day := 0
	for i := 0; i < N; i++ {
		S := io.NextInt()
		D := io.NextInt()

		day++
		for day < S || (day - S) % D != 0 {
			day++
		}
	}
	io.Println(day)
}

type FastIO struct {
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}

func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = (res * 10) + int(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}

func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextInt()
	}
	return arr
}

func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}

func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextLong()
	}
	return arr
}

func (io *FastIO) NextString() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}

func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}

func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}

func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}

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

func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}

package main

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

func Init() {
}

func Solve(io *FastIO) {
	N := io.NextInt()

	day := 0
	for i := 0; i < N; i++ {
		S := io.NextInt()
		D := io.NextInt()

		for day < S || (day - S) % D != 0 {
			day++
		}
	}
	io.Println(day)
}

type FastIO struct {
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}

func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = (res * 10) + int(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}

func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextInt()
	}
	return arr
}

func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}

func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextLong()
	}
	return arr
}

func (io *FastIO) NextString() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}

func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}

func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}

func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}

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

func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}


There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.A result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately. In each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct). In the first contest, the participant on the 100-th place scored $$$a$$$ points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least $$$b$$$ points in the second contest.Similarly, for the second contest, the participant on the 100-th place has $$$c$$$ points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least $$$d$$$ points in the first contest.After two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The cutoff score to qualify to the final stage is the total score of the participant on the 100-th place.Given integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, please help the jury determine the smallest possible value of the cutoff score.

You need to process $$$t$$$ test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 3025$$$) — the number of test cases. Then descriptions of $$$t$$$ test cases follow. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,\,b,\,c,\,d \le 9$$$; $$$d \leq a$$$; $$$b \leq c$$$).  One can show that for any test case satisfying the constraints above, there is at least one olympiad scenario possible.

For each test case print a single integer — the smallest possible cutoff score in some olympiad scenario satisfying the given information.

NoteFor the first test case, consider the following olympiad scenario: there are $$$101$$$ participants in the elimination stage, each having $$$1$$$ point for the first contest and $$$2$$$ points for the second contest. Hence the total score of the participant on the 100-th place is $$$3$$$.For the second test case, consider the following olympiad scenario:   there are $$$50$$$ participants with points $$$5$$$ and $$$9$$$ for the first and second contest respectively;  $$$50$$$ participants with points $$$4$$$ and $$$8$$$ for the first and second contest respectively;  and $$$50$$$ participants with points $$$2$$$ and $$$9$$$ for the first and second contest respectively.  Hence the total point score of the participant on the 100-th place is $$$12$$$.

package main

import (
	"fmt"
)

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

func main() {
	var t int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		var a, b, c, d int
		fmt.Scan(&a, &b, &c, &d)
		fmt.Println(max(a + b, c + d))
	}
}

package main
import (
	"bufio"
	"fmt"
	"os"
)
func max(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}
func main() {
	rd := bufio.NewReader(os.Stdin)
	q := 0
	fmt.Fscan(rd, &q)
	for t := 0; t < q; t++ {
		var a, b, c, d int
		fmt.Fscan(rd, &a, &b, &c, &d)
		fmt.Println(max(a + b, c + d))
	}
}

package main

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

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

func print(str string) {
	writer.WriteString(str)
}

func nextInt() int {
	scanner.Scan()
	str := scanner.Text()
	val, _ := strconv.Atoi(str)
	return val
}

func nextFloat() float64 {
	scanner.Scan()
	str := scanner.Text()
	val, _ := strconv.ParseFloat(str, 64)
	return val
}

func nextString() string {
	scanner.Scan()
	str := scanner.Text()
	return str
}

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

func main() {
	scanner.Split(bufio.ScanWords)
	defer writer.Flush()

	t := nextInt()
	for t != 0 {
		a, b := nextInt(), nextInt()
		c, d := nextInt(), nextInt()
		res := max(a+b, c+d)
		print(strconv.Itoa(res)+"\n")
		t--
	}
}

package main

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

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

	in := bufio.NewReader(os.Stdin)

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

	for i := 0; i < t; i++ {
		var a, b, c, d int
		fmt.Fscan(in, &a, &b, &c, &d)
		if a+b > c+d {
			fmt.Fprintf(out, "%d\n", a+b)
		} else {
			fmt.Fprintf(out, "%d\n", c+d)
		}
	}
}

package main

import (
	"fmt"
)

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

func main() {
	var t int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		var a, b, c, d int
		fmt.Scan(&a, &b, &c, &d)
		fmt.Print(max(a + b, c + d))
	}
}


Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of columns.  The next n lines contain the pairs of integers li and ri (1 ≤ li, ri ≤ 500) — the number of soldiers in the i-th column which start to march from the left or the right leg respectively.

Print single integer k — the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached. Consider that columns are numbered from 1 to n in the order they are given in the input data. If there are several answers, print any of them.

NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5 + 8 + 10 = 23, and from the right leg — 6 + 9 + 3 = 18. In this case the beauty of the parade will equal |23 - 18| = 5.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5 + 8 + 3 = 16, and who march from the right leg — 6 + 9 + 10 = 25. In this case the beauty equals |16 - 25| = 9.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9.

package main

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

func solve() {
    n := readInt()
	a := make([]int, n)

	sum := 0
	for i := 0; i < n; i++ {
        l, r := readInt(), readInt()
		a[i] = l - r
		sum += a[i]
	}

	ans, best := 0, abs(sum)
	for i := 0; i < n; i++ {
		cur := abs(sum - 2*a[i])
		if cur > best {
			best = cur
			ans = i + 1
		}

	}
	fmt.Println(ans)
}

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func main() {
    scanner.Split(bufio.ScanWords)
    solve()
}

// Math
func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

// IO

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

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

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

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer

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

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()

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

	l := make([]int, n+1)
	r := make([]int, n+1)

	lsum := 0
	rsum := 0
	for i := 1; i <= n; i++ {
		fmt.Fscanf(bufin, "%d %d\n", &l[i], &r[i])
		lsum += l[i]
		rsum += r[i]
	}

	res := 0
	maxBeauty := abs(lsum - rsum)

	for i := 1; i <= n; i++ {
		lnow := lsum - l[i] + r[i]
		rnow := rsum - r[i] + l[i]
		beauty := abs(lnow - rnow)
		if maxBeauty < beauty {
			maxBeauty = beauty
			res = i
		}
	}

	fmt.Fprintf(bufout, "%d\n", res)
}

package main

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

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

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	L, R := 0, 0
	l := make([]int, n)
	r := make([]int, n)
	ans := -1

	for i := 0; i < n; i++ {
		l[i] = nextInt()
		r[i] = nextInt()
		L += l[i]
		R += r[i]
	}
	// println(abs(L - R))
	maxBeaty := abs(L - R)

	for i := 0; i < n; i++ {
		newBeaty := abs(L - R + 2*(r[i]-l[i]))
		// println(newBeaty)
		if newBeaty > maxBeaty {
			maxBeaty = newBeaty
			ans = i
		}
	}

	println(ans + 1)
}

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

	return n
}

func next() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

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

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer

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

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()
	var N int
	fmt.Fscanf(bufin, "%d\n", &N)
	var l = make([]int, N)
	var r = make([]int, N)
	var L, R = 0, 0
	for i := 0; i < N; i++ {
		fmt.Fscanf(bufin, "%d %d\n", &l[i], &r[i])
		L += l[i]
		R += r[i]
	}
	var beauty = abs(L - R)
	var ans = 0
	for i := 0; i < N; i++ {
		var nL = L - l[i] + r[i]
		var nR = R - r[i] + l[i]
		var nbeauty = abs(nL - nR)
		if beauty < nbeauty {
			beauty = nbeauty
			ans = i + 1
		}
	}
	fmt.Fprintf(bufout, "%d\n", ans)

}

package main

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

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

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

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

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

    n := ReadInt()
    deltas := make([]int, n)
    plus, minus := 0, 0

    for i := 0; i < n; i++ {
        left, right := ReadInt(), ReadInt()
        deltas[i] = left - right

        if deltas[i] > 0 {
            plus += deltas[i]
        } else {
            minus += deltas[i]
        }
    }

    maxIndex := -1
    maxPretty := math.Abs(float64(plus + minus))

    for i := 0; i < n; i++ {
        if deltas[i] == 0 {
            continue
        }

        newPretty := math.Abs(float64(plus + minus - 2 * deltas[i]))

        if newPretty > maxPretty {
            maxPretty = newPretty
            maxIndex = i
        }
    }

    fmt.Print(maxIndex + 1)
}

package main

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

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	type Tup struct {
		A int
		B int
	}

	T := make([]Tup, N)
	for i := 0; i < N; i++ {
		T[i] = Tup{A:sc.NextInt(), B:sc.NextInt()}
	}

	a := 0
	b := 0
	for i := 0; i < N; i++ {
		a += T[i].A
		b += T[i].B
	}

	z := abs(a - b)
	index := 0
	for i := 0; i < N; i++ {
		c := a - T[i].A + T[i].B
		d := b + T[i].A - T[i].B

		if abs(c - d) > z {
			z = abs(c - d)
			index = i + 1
		}
	}
	fmt.Println(index)

}

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

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r:rdr}
}
func (s *Scanner) 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 *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

// cf 733b project main.go
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 ReadString() string {
	scanner.Scan()
	return scanner.Text()
}

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

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	var n int = ReadInt32()
	var a, ai, b, bi, ls, rs int
	for i := 0; i < n; i++ {
		var l, r int = ReadInt32(), ReadInt32()
		if l-r > a {
			a = l - r
			ai = i + 1
		}
		if r-l > b {
			b = r - l
			bi = i + 1
		}
		ls += l
		rs += r

	}
	if ls+b > rs+a || ls == rs {
		PrintInts(bi)
	} else if ls+b < rs+a {
		PrintInts(ai)
	} else {
		PrintInts(0)
	}

}

// cf733b project main.go
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 ReadString() string {
	scanner.Scan()
	return scanner.Text()
}

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

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	var n int = ReadInt32()
	var a, ai, b, bi, ls, rs int
	for i := 0; i < n; i++ {
		var l, r int = ReadInt32(), ReadInt32()
		if l-r > a {
			a = l - r
			ai = i + 1
		}
		if r-l > b {
			b = r - l
			bi = i + 1
		}
		ls += l
		rs += r

	}
	if ls+b > rs+a || ls == rs {
		PrintInts(bi)
	} else if ls+b < rs+a {
		PrintInts(ai)
	} else {
		PrintInts(0)
	}

}

package main

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

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

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

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

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

    n := ReadInt()
    deltas := make([]int, n)
    plus, minus := 0, 0

    for i := 0; i < n; i++ {
        left, right := ReadInt(), ReadInt()
        deltas[i] = left - right

        if deltas[i] > 0 {
            plus++
        } else {
            minus++
        }
    }

    maxIndex := -1

    for i := 0; i < n; i++ {
        if deltas[i] == 0 || (plus > minus && deltas[i] > 0) || (plus < minus && deltas[i] < 0) {
            continue
        }

        if maxIndex == -1 || math.Abs(float64(deltas[maxIndex])) < math.Abs(float64(deltas[i])) {
            maxIndex = i
        }
    }

    fmt.Print(maxIndex + 1)
}

package main

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

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	type Tup struct {
		A int
		B int
	}

	T := make([]Tup, N)
	for i := 0; i < N; i++ {
		T[i] = Tup{A:sc.NextInt(), B:sc.NextInt()}
	}

	L := 0
	for i := 0; i < N; i++ {
		if T[i].A - T[i].B > 0 {
			L++
		} else {
			L--
		}
	}
	if L == 0 {
		fmt.Println(1)
		return
	}
	mx := 0
	mxI := -1
	for i := 0; i < N; i++ {
		if L >= 0 {
			if mx < T[i].B - T[i].A {
				mx = T[i].B - T[i].A
				mxI = i
			}
		} else {
			if mx < T[i].A - T[i].B {
				mx = T[i].A - T[i].B
				mxI = i
			}
		}
	}
	fmt.Println(mxI + 1)

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r:rdr}
}
func (s *Scanner) 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 *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

// cf 733b project main.go
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	var a, ai, b, bi, ls, rs int
	for i := 0; i < n; i++ {
		var l, r int
		fmt.Scan(&l, &r)
		if l-r > a {
			a = l - r
			ai = i + 1
		}
		if r-l > b {
			b = r - l
			bi = i + 1
		}
		ls += l
		rs += r

	}
	if ls+b > rs+a {
		fmt.Println(bi)
	} else if ls+b < rs+a {
		fmt.Println(ai)
	} else {
		fmt.Println(0)
	}

}

// cf 733b project main.go
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 ReadString() string {
	scanner.Scan()
	return scanner.Text()
}

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

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	var n int = ReadInt32()
	var a, ai, b, bi, ls, rs int
	for i := 0; i < n; i++ {
		var l, r int = ReadInt32(), ReadInt32()
		if l-r > a {
			a = l - r
			ai = i + 1
		}
		if r-l > b {
			b = r - l
			bi = i + 1
		}
		ls += l
		rs += r

	}
	if ls+b > rs+a || a == b {
		PrintInts(bi)
	} else if ls+b < rs+a {
		PrintInts(ai)
	} else {
		PrintInts(0)
	}

}


Given an undirected connected graph with $$$n$$$ vertices and $$$m$$$ edges. The graph contains no loops (edges from a vertex to itself) and multiple edges (i.e. no more than one edge between each pair of vertices). The vertices of the graph are numbered from $$$1$$$ to $$$n$$$. Find the number of paths from a vertex $$$s$$$ to $$$t$$$ whose length differs from the shortest path from $$$s$$$ to $$$t$$$ by no more than $$$1$$$. It is necessary to consider all suitable paths, even if they pass through the same vertex or edge more than once (i.e. they are not simple).    Graph consisting of $$$6$$$ of vertices and $$$8$$$ of edges For example, let $$$n = 6$$$, $$$m = 8$$$, $$$s = 6$$$ and $$$t = 1$$$, and let the graph look like the figure above. Then the length of the shortest path from $$$s$$$ to $$$t$$$ is $$$1$$$. Consider all paths whose length is at most $$$1 + 1 = 2$$$.   $$$6 \rightarrow 1$$$. The length of the path is $$$1$$$.  $$$6 \rightarrow 4 \rightarrow 1$$$. Path length is $$$2$$$.  $$$6 \rightarrow 2 \rightarrow 1$$$. Path length is $$$2$$$.  $$$6 \rightarrow 5 \rightarrow 1$$$. Path length is $$$2$$$. There is a total of $$$4$$$ of matching paths.

The first line of test contains the number $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. Before each test case, there is a blank line.  The first line of test case contains two numbers $$$n, m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$) —the number of vertices and edges in the graph.  The second line contains two numbers $$$s$$$ and $$$t$$$ ($$$1 \le s, t \le n$$$, $$$s \neq t$$$) —the numbers of the start and end vertices of the path. The following $$$m$$$ lines contain descriptions of edges: the $$$i$$$th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i,v_i \le n$$$) — the numbers of vertices that connect the $$$i$$$th edge. It is guaranteed that the graph is connected and does not contain loops and multiple edges. It is guaranteed that the sum of values $$$n$$$ on all test cases of input data does not exceed $$$2 \cdot 10^5$$$. Similarly, it is guaranteed that the sum of values $$$m$$$ on all test cases of input data does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single number — the number of paths from $$$s$$$ to $$$t$$$ such that their length differs from the length of the shortest path by no more than $$$1$$$. Since this number may be too large, output it modulo $$$10^9 + 7$$$.

package main

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

const INF = 0x3f3f3f3f
const MOD = 1000000007

func solve(cin *scanner, cout *writer, cerr *writer) {
	n, m := cin.NextInt(), cin.NextInt()
	s, t := cin.NextInt()-1, cin.NextInt()-1
	g := make([][]int, n)
	for i := 0; i < m; i++ {
		u, v := cin.NextInt()-1, cin.NextInt()-1
		g[u] = append(g[u], v)
		g[v] = append(g[v], u)
	}
	dist := make([]int, n)
	dp0 := make([]int, n)
	dp1 := make([]int, n)
	for i := 0; i < n; i++ {
		dist[i] = INF
		dp0[i] = 0
		dp1[i] = 0
	}
	dist[s] = 0
	dp0[s] = 1
	var q []int
	q = append(q, s)
	for len(q) > 0 {
		u := q[0]
		q = q[1:]
		if u < n {
			for _, v := range g[u] {
				if dist[v] == INF {
					dist[v] = dist[u] + 1
					q = append(q, v)
				}
				if dist[v] == dist[u]+1 {
					dp0[v] += dp0[u]
					dp0[v] %= MOD
				}
				if dist[v] == dist[u] {
					dp1[v] += dp0[u]
					dp1[v] %= MOD
				}
			}
			q = append(q, u+n)
		} else {
			u -= n
			for _, v := range g[u] {
				if dist[v] == dist[u]+1 {
					dp1[v] += dp1[u]
					dp1[v] %= MOD
				}
			}
		}
	}
	cout.Println((dp0[t] + dp1[t]) % MOD)
	// cerr.Println(dist)
	// cerr.Println(dp0)
	// cerr.Println(dp1)
}

func main() {
	cin := NewScanner(os.Stdin)
	cout, cerr := NewWriter(os.Stdout), NewWriter(os.Stderr)
	defer cout.Flush()
	defer cerr.Flush()
	t := cin.NextInt()
	// t := 1
	for ti := 0; ti < t; ti++ {
		solve(cin, cout, cerr)
	}
}

// Template Bolierplate {{{
type scanner struct {
	*bufio.Scanner
}

func NewScanner(r io.Reader) *scanner {
	s := bufio.NewScanner(r)
	s.Split(bufio.ScanWords)
	s.Buffer(nil, 1024*1024)
	return &scanner{s}
}

func (i *scanner) Next() string {
	i.Scan()
	return i.Text()
}

func (i *scanner) Nexts(n int) []string {
	res := make([]string, n)
	for j := range res {
		res[j] = i.Next()
	}
	return res
}

func (i *scanner) NextInt() int {
	v, _ := strconv.Atoi(i.Next())
	return v
}

func (i *scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(i.Next(), 10, 64)
	return v
}

func (i *scanner) NextInts(n int) []int {
	res := make([]int, n)
	for j := range res {
		res[j] = i.NextInt()
	}
	return res
}

func (i *scanner) NextInt64s(n int) []int64 {
	res := make([]int64, n)
	for j := range res {
		res[j] = i.NextInt64()
	}
	return res
}

type writer struct {
	w *bufio.Writer
}

func NewWriter(w io.Writer) *writer {
	return &writer{bufio.NewWriter(w)}
}

func (i *writer) Print(a ...interface{}) {
	fmt.Fprint(i.w, a...)
}

func (i *writer) Println(a ...interface{}) {
	fmt.Fprintln(i.w, a...)
}

func (i *writer) Printf(format string, a ...interface{}) {
	fmt.Fprintf(i.w, format, a...)
}

func (i *writer) Flush() {
	i.w.Flush()
}

// }}}

// vim: fdm=marker

package main

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

const INF = 0x3f3f3f3f
const MOD = 1000000007

func solve(cin *scanner, cout *writer, cerr *writer) {
	n, m := cin.NextInt(), cin.NextInt()
	s, t := cin.NextInt()-1, cin.NextInt()-1
	g := make([][]int, n)
	for i := 0; i < m; i++ {
		u, v := cin.NextInt()-1, cin.NextInt()-1
		g[u] = append(g[u], v)
		g[v] = append(g[v], u)
	}
	dist := make([]int, n)
	dp0 := make([]int64, n)
	dp1 := make([]int64, n)
	for i := 0; i < n; i++ {
		dist[i] = INF
		dp0[i] = 0
		dp1[i] = 0
	}
	dist[s] = 0
	dp0[s] = 1
	var q []int
	q = append(q, s)
	for len(q) > 0 {
		u := q[0]
		q = q[1:]
		if u < n {
			for _, v := range g[u] {
				if dist[v] == INF {
					dist[v] = dist[u] + 1
					q = append(q, v)
				}
				if dist[v] == dist[u]+1 {
					dp0[v] += dp0[u]
					dp0[v] %= MOD
				}
				if dist[v] == dist[u] {
					dp1[v] += dp0[u]
					dp1[v] %= MOD
				}
			}
			q = append(q, u+n)
		} else {
			u -= n
			for _, v := range g[u] {
				if dist[v] == dist[u]+1 {
					dp1[v] += dp1[u]
					dp1[v] %= MOD
				}
			}
		}
	}
	cout.Println((dp0[t] + dp1[t]) % MOD)
	// cerr.Println(dist)
	// cerr.Println(dp0)
	// cerr.Println(dp1)
}

func main() {
	cin := NewScanner(os.Stdin)
	cout, cerr := NewWriter(os.Stdout), NewWriter(os.Stderr)
	defer cout.Flush()
	defer cerr.Flush()
	t := cin.NextInt()
	// t := 1
	for ti := 0; ti < t; ti++ {
		solve(cin, cout, cerr)
	}
}

// Template Bolierplate {{{
type scanner struct {
	*bufio.Scanner
}

func NewScanner(r io.Reader) *scanner {
	s := bufio.NewScanner(r)
	s.Split(bufio.ScanWords)
	s.Buffer(nil, 1024*1024)
	return &scanner{s}
}

func (i *scanner) Next() string {
	i.Scan()
	return i.Text()
}

func (i *scanner) Nexts(n int) []string {
	res := make([]string, n)
	for j := range res {
		res[j] = i.Next()
	}
	return res
}

func (i *scanner) NextInt() int {
	v, _ := strconv.Atoi(i.Next())
	return v
}

func (i *scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(i.Next(), 10, 64)
	return v
}

func (i *scanner) NextInts(n int) []int {
	res := make([]int, n)
	for j := range res {
		res[j] = i.NextInt()
	}
	return res
}

func (i *scanner) NextInt64s(n int) []int64 {
	res := make([]int64, n)
	for j := range res {
		res[j] = i.NextInt64()
	}
	return res
}

type writer struct {
	w *bufio.Writer
}

func NewWriter(w io.Writer) *writer {
	return &writer{bufio.NewWriter(w)}
}

func (i *writer) Print(a ...interface{}) {
	fmt.Fprint(i.w, a...)
}

func (i *writer) Println(a ...interface{}) {
	fmt.Fprintln(i.w, a...)
}

func (i *writer) Printf(format string, a ...interface{}) {
	fmt.Fprintf(i.w, format, a...)
}

func (i *writer) Flush() {
	i.w.Flush()
}

// }}}

// vim: fdm=marker


Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, "abc" $$$\cdot~2~=$$$ "abcabc", "a" $$$\cdot~5~=$$$ "aaaaa".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \cdot x = a$$$. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of test cases. Each test case consists of two lines, containing strings $$$s$$$ and $$$t$$$ ($$$1 \le |s|, |t| \le 20$$$). Each character in each of these strings is either 'a' or 'b'.

For each test case, print $$$LCM(s, t)$$$ if it exists; otherwise, print -1. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

NoteIn the first test case, "baba" = "baba" $$$\cdot~1~=$$$ "ba" $$$\cdot~2$$$.In the second test case, "aaaaaa" = "aa" $$$\cdot~3~=$$$ "aaa" $$$\cdot~2$$$.

package main

import (
	"bufio"
	"fmt"
	"os"
    "strings"
)
var (
    input = bufio.NewReader(os.Stdin)
    output = bufio.NewWriter(os.Stdout)
)

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)
func main() {
    var t int
	fmt.Fscanln(input, &t)
    for t > 0 {
        t--
        solve()
    }
    output.Flush()
}

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

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

func solve() {
    var (
        s, t string
    )
    fmt.Fscanln(input, &s)
    fmt.Fscanln(input, &t)
    if len(s) < len(t) {s, t = t, s}

    ans := ""
    for i := 1; i <= len(s) * len(t); i++ {
        str := strings.Repeat(s, i)
        if len(str) % len(t) == 0 {
            res := true
            for i := 0; i < len(str); i++ {
                if str[i] != t[i % len(t)] {
                    res = false
                    break
                }
            }
            if res {
                ans = str
                goto q
            }
        }
    }

    q:
    if len(ans) > 0 {
        fmt.Fprintln(output, ans)
    } else {
        fmt.Fprintln(output, "-1")
    }
}

package main

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

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

func main() {
	defer writer.Flush()

	var q int
	fmt.Fscan(reader, &q)

	for i := 0; i < q; i++ {
		var s, t string
		fmt.Fscan(reader, &s, &t)

		lcmVal := lcm(len(s), len(t))

		var sLcm, tLcm string
		for i := 0; i < lcmVal/len(s); i++ {
			sLcm += s
		}
		for i := 0; i < lcmVal/len(t); i++ {
			tLcm += t
		}

		if sLcm == tLcm {
			fmt.Fprintln(writer, sLcm)
		} else {
			fmt.Fprintln(writer, -1)
		}
	}
}

func lcm(a, b int) int {
	return a * b / gcd(a, b)
}

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

	return gcd(b, a%b)
}

package main

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

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
	t   int
	a   string
	b   string
)

func main() {

	defer out.Flush()

	fmt.Fscan(in, &t)

	for ; t > 0; t-- {

		fmt.Fscan(in, &a)
		fmt.Fscan(in, &b)

		solve(a, b)

	}

}

func solve(a string, b string) {

	index := 0
	flag := true

	//fmt.Println(a[len(a)-len(b) : len(a)])

	if len(a) >= len(b) {

		for i := 0; i < len(a); i++ {

			if a[i] != b[index] {
				flag = false
			}

			index++

			if index == len(b) {
				index = 0
			}

		}

		if a[len(a)-len(b):len(a)] != b {
			flag = false
		}

		if flag {
			for i := 0; i < Lcm(len(a), len(b)); i++ {

				fmt.Fprintf(out, "%c", b[index])

				index++

				if index == len(b) {
					index = 0
				}

				if i == Lcm(len(a), len(b))-1 {
					fmt.Fprintf(out, "\n")
				}

			}
		} else {
			fmt.Fprintln(out, "-1")
		}

	} else {

		for i := 0; i < len(b); i++ {

			if b[i] != a[index] {
				flag = false
			}

			index++

			if index == len(a) {
				index = 0
			}

		}

		if b[len(b)-len(a):len(b)] != a {
			flag = false
		}

		if flag {
			for i := 0; i < Lcm(len(a), len(b)); i++ {

				fmt.Fprintf(out, "%c", a[index])

				index++

				if index == len(a) {
					index = 0
				}

				if i == Lcm(len(a), len(b))-1 {
					fmt.Fprintf(out, "\n")
				}

			}
		} else {
			fmt.Fprintln(out, "-1")
		}

	}

}

//最大公因數
func Gcd(a int, b int) int {
	var twoCounter uint

	for {
		if a == b || b == 0 {
			return a << twoCounter
		} else if a == 0 {
			return b << twoCounter
		} else if a&1 == 0 {
			a >>= 1

			if b&1 == 0 {
				b >>= 1

				twoCounter += 1
			}
		} else if b&1 == 0 {
			b >>= 1
		} else if a > b {
			a = (a - b) >> 1
		} else {
			b = (b - a) >> 1
		}
	}
}

//最小公倍數
func Lcm(a int, b int) int {
	return a * b / Gcd(a, b)
}

package main

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

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

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

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

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func sbytes() []byte {
	scanner.Scan()
	return scanner.Bytes()
}

func main() {
	defer writer.Flush()
	for t := sint64(); t > 0; t-- {
		ss := sstring()
		tt := sstring()
		printf("%s\n", sol(ss, tt))
	}
}

func sol(s, t string) string {
	si, ti := 0, 0
	count := 0
	flag := false
	for {
		if s[si] != t[ti] {
			return "-1"
		}
		count++
		if si == 0 && ti == 0 && flag {
			break
		}
		flag = true
		si++
		si %= len(s)
		ti++
		ti %= len(t)
	}
	count--
	ret := ""
	for i := 0; i < count/len(s); i++ {
		ret += s
	}
	return ret
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	q      int
	s, t   string
)

func lcm(x, y int) int {
	return x * y / gcd(x, y)
}

func gcd(x, y int) int {
	if x < y {
		return gcd(y, x)
	}
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

func solve(s, t string) string {
	l := lcm(len(s), len(t))
	a := strings.Repeat(s, l/len(s))
	for i := 0; i < len(a); i++ {
		if a[i] != t[i%len(t)] {
			return "-1"
		}
	}
	return a
}

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

package main

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

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

func (in *CF1473B) 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 *CF1473B) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

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

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

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

/**
 Run solve the problem CF1473B
 Date: 11/06/21
 User: pepradere
 URL: https://codeforces.com/contest/1473/problem/B
 Problem: CF1473B
**/
func (in *CF1473B) Run() {

	q := in.NextInt()
	for ; q > 0; q-- {
		s := in.NextString()
		t := in.NextString()
		ans := "-1"
		if len(s) == len(t) {
			if s == t {
				ans = s
			}
		} else {
			ans = in.g(s, t)
		}

		fmt.Println(ans)
	}

}

func (in *CF1473B) g(s, t string) string {
	os := s
	ot := t
	ans := "-1"
	a, b := 1, 1
	for ; len(s) != len(t) && a < 5000 && b < 5000; {
		if len(s) < len(t) {
			s = in.f(s, os)
			a++
		} else if len(s) > len(t) {
			t = in.f(t, ot)
			b++
		}
	}
	if len(s) == len(t) && s == t {
		ans = t
	}

	return ans
}

func (in *CF1473B) f(str string, o string) string {
	return o + str
}

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

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

package main

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

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

func Scan(a ...interface{})    { fmt.Fscan(reader, a...) }
func Scanln(a ...interface{})  { fmt.Fscanln(reader, a...) }
func Print(a ...interface{})   { fmt.Fprint(writer, a...) }
func Println(a ...interface{}) { fmt.Fprintln(writer, a...) }

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

func lcm(a, b int) int {
	return a * b / gcd(a, b)
}

func main() {
	defer writer.Flush()
	var t int
	Scanln(&t)
	for tc := 0; tc < t; tc++ {
		var a, b string
		Scanln(&a)
		Scanln(&b)
		n := len(a)
		m := len(b)
		g := lcm(n, m)
		var cur_a, cur_b string
		for i := 0; i < g/n; i++ {
			cur_a += a
		}
		for i := 0; i < g/m; i++ {
			cur_b += b
		}
		if cur_a == cur_b {
			Println(cur_a)
		} else {
			Println(-1)
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

var bytes []byte

func nextByte() byte {
	b := bytes[0]
	bytes = bytes[1:]
	return b
}

func scanInt64() int64 {
	var negative bool
	var result int64

	b := nextByte()

	for ; b < '0' || b > '9'; b = nextByte() {
		if b == '-' {
			negative = true
		}
	}

	for ; '0' <= b && b <= '9'; b = nextByte() {
		result = (result << 3) + (result << 1) + int64(b-'0')
	}

	if negative {
		return -result
	} else {
		return result
	}
}

func scanInt() int {
	return int(scanInt64())
}

func ScanString() string {
	builder := strings.Builder{}

	for b := nextByte(); b != '\r'; b = nextByte() {
		if b != '\n' {
			builder.WriteByte(b)
		}
	}

	return builder.String()
}

func init() {
	f, err := os.Open("in.txt")

	if err == nil {
		defer f.Close()
	} else {
		f = os.Stdin
	}

	bytes, _ = ioutil.ReadAll(bufio.NewReader(f))
}

func main() {
	for q := scanInt(); q > 0; q-- {
		s, t := ScanString(), ScanString()

		n := lcm(len(s), len(t))

		s = strings.Repeat(s, n/len(s))
		t = strings.Repeat(t, n/len(t))

		if s == t {
			fmt.Println(s)
		} else {
			fmt.Println(-1)
		}
	}
}

func lcm(x, y int) int {
	return x * y / gcd(x, y)
}

func gcd(x, y int) int {
	switch {
	case x > y:
		return gcd(x%y, y)
	case x == 0:
		return y
	default:
		return gcd(y%x, x)
	}
}

package main

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

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

func gen(a, b string) string {
	var c string
	for i := 0; ; i++ {
		c += string(a[i%len(a)])
		if c[i] != b[i%len(b)] {
			return "-1"
		}
		if (i+1)%len(a) == 0 && (i+1)%len(b) == 0 {
			return c
		}
	}
	return "-1"
}

func main() {
	t := 0
	fmt.Fscan(in, &t)
	for t > 0 {
		t--
		var a, b string
		fmt.Fscan(in, &a, &b)
		if len(a) < len(b) {
			a, b = b, a
		}
		fmt.Fprintln(out, gen(a, b))
	}
	out.Flush()
}

package main

// https://codeforces.com/problemset/problem/313/B
import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func gcd(a, b int) int {
	for b != 0 {
		t := b
		b = a % b
		a = t
	}
	return a
}

func lcm(s string, l string) string {
	l1 := len(s)
	l2 := len(l)
	// iisaikais viemeer otrais
	if l1 < l2 {
		tmp := s
		s = l
		l = tmp
	}
	l1 = len(s)
	l2 = len(l)

	gcd := gcd(l1, l2)
	// 3 , 2
	// 1
	m := l1 * l2 / gcd
	//	fmt.Println("m", m)
	ll := strings.Repeat(l, m/l2)
	//	fmt.Println("ll", ll)

	ss := strings.Repeat(s, m/l1)
	//	fmt.Println("ss", ss)

	if ss == ll {
		return ss
	}

	return "-1"

}
func main() {

	// fmt.Println(3 * 2 / gcd(3, 2))
	buf := make([]byte, 0, 1000000)

	reader := bufio.NewScanner(os.Stdin)
	reader.Buffer(buf, 1000000)
	reader.Scan()
	// line := reader.Text() // number of test cases

	//	m := reader.Text()

	for reader.Scan() {

		s1 := reader.Text()
		reader.Scan()
		t1 := reader.Text()

		fmt.Println(lcm(s1, t1))

	}

	if err := reader.Err(); err != nil {
		fmt.Println("Error reading from stdin", err)
	}
}

package main

import (
	"fmt"
	"bufio"
	"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 lcm(a, b int) int {
	p := a * b
	for ; b != 0; a %= b {
		if b > a {
			a, b = b, a
		}
		if b == 0 {
			break
		}
	}
	return p / a
}

func solve() {
	var s, t string
	scanf("%s\n%s\n", &s, &t)
	n := len(s)
	m := len(t)
	d := lcm(n, m)
	ss := ""
	for i := 0; i < d / n; i++ {
		ss += s
	}
	tt := ""
	for i := 0; i < d / m; i++ {
		tt += t
	}
	if tt == ss {
		printf(tt + "\n")
	} else {
		printf("-1\n")
	}
}

func main() {
	defer writer.Flush()
	var t int
	scanf("%d\n", &t)
	for ; t > 0; t-- {
		solve()
	}
}

package main

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

func main() {
	sc:=bufio.NewScanner(os.Stdin)
	sc.Scan()
	l,_:=strconv.Atoi(sc.Text())
	for i:=0; i<l;i++{
		sc.Scan()
		a := sc.Text()
		sc.Scan()
		fmt.Printf("%s\n",fn(a, sc.Text()))
	}
}

func fn(a string, d string) string{
	l1:=len(a)
	l2:=len(d)
	p:=l1*l2
	i1,i2 := 1,1
	for true{
		if i1*l1 == i2*l2 {
			if strings.Repeat(a, i1) == strings.Repeat(d, i2)  {
				return strings.Repeat(a, i1)
			}else{
				return "-1"
			}

		}
		if i1*l1>p || i2*l2>p{
			break
		}
		if l2*i2>l1*i1{
			i1++
		}else {
			i2++
		}

	}
	return "-1"
}

package main

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

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

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

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
		STRING1 := make([]byte, 0)
		NEWSTRING := make([]byte, 0)
		fmt.Fscan(input, &n)

		fmt.Fscan(input, &STRING1)
		fmt.Fscan(input, &NEWSTRING)

		len1 := len(STRING1)
		len2 := len(NEWSTRING)

		if len2 >= len1 {
			initial := len2
			for i := 1; i < len1+2; i++ {
				if initial%len1 == 0 {
					break
				} else {
					initial = initial + len2
				}
			}

			var LCM string
			for j := 1; j < (initial/len2)+1; j++ {
				LCM = LCM + string(NEWSTRING)
			}
			mao := 0
			for k := 0; k < initial/len1; k++ {
				if string(STRING1) != LCM[(k*len1):(k+1)*len1] {
					mao = mao + 1
					break
				}
			}

			if mao > 0 {
				fmt.Println(-1)
			} else {
				fmt.Println(LCM)
			}

		} else {
			initial := len1
			for i := 1; i < len2+2; i++ {
				if initial%len2 == 0 {
					break
				} else {
					initial = initial + len1
				}
			}

			var LCM string
			for j := 1; j < (initial/len1)+1; j++ {
				LCM = LCM + string(STRING1)
			}
			mao := 0
			for k := 0; k < initial/len2; k++ {
				if string(NEWSTRING) != LCM[(k*len2):(k+1)*len2] {
					mao = mao + 1
				}
			}

			if mao > 0 {
				fmt.Println(-1)
			} else {
				fmt.Println(LCM)
			}
		}
	}
}

/*
URL:
https://codeforces.com/contest/1473/problem/B
*/

package main

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

var (
	println = fmt.Println

	q    int
	S, T []rune
)

func main() {
	defer stdout.Flush()

	q = readi()
	for i := 0; i < q; i++ {
		S, T = readrs(), readrs()

		solve()
	}
}

func solve() {
	a, b := len(S), len(T)
	l := Lcm(a, b)

	SS := []rune{}
	TT := []rune{}
	for i := 0; i < l/a; i++ {
		SS = append(SS, S...)
	}
	for i := 0; i < l/b; i++ {
		TT = append(TT, T...)
	}

	if string(SS) == string(TT) {
		printf("%s\n", string(SS))
	} else {
		printf("-1\n")
	}
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 0).
// Negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a < 0 || b < 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	if b == 0 {
		return a
	}
	return Gcd(b, a%b)
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 0).
// Negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a < 0 || b < 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	if a == 0 || b == 0 {
		return 0
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	g := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / g) * b
}

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

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

// abs is integer version of math.Abs
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// pow is integer version of math.Pow
// pow calculate a power by Binary Power (二分累乗法(O(log e))).
func pow(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := pow(a, halfE)
		return half * half
	}

	return a * pow(a, e-1)
}

/********** 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"
	"os"
    "strings"
)
var (
    input = bufio.NewReader(os.Stdin)
    output = bufio.NewWriter(os.Stdout)
)

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)
func main() {
    var t int
	fmt.Fscanln(input, &t)
    for t > 0 {
        t--
        solve()
    }
    output.Flush()
}

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

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

func solve() {
    var (
        s, t string
    )
    fmt.Fscanln(input, &s)
    fmt.Fscanln(input, &t)
    if len(s) < len(t) {s, t = t, s}

    ans := ""
    for i := 1; i < len(s) * len(t); i++ {
        str := strings.Repeat(s, i)
        if len(str) % len(t) == 0 {
            res := true
            for i := 0; i < len(str); i++ {
                if str[i] != t[i % len(t)] {
                    res = false
                    break
                }
            }
            if res {
                ans = str
                goto q
            }
        }
    }

    q:
    if len(ans) > 0 {
        fmt.Fprintln(output, ans)
    } else {
        fmt.Fprintln(output, "-1")
    }
}

package main

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

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

func main() {
	defer writer.Flush()

	var q int
	fmt.Fscan(reader, &q)

	for i := 0; i < q; i++ {
		var s, t string
		fmt.Fscan(reader, &s, &t)

		g := gcd(s, t)
		if g == -1 {
			fmt.Fprintln(writer, -1)
			continue
		}

		lcm := len(s) * len(t) / g
		ans := s

		for len(ans) < lcm {
			ans += s
		}

		fmt.Fprintln(writer, ans)
	}
}

func gcd(s, t string) int {
	if len(t) > len(s) {
		tmp := t
		t = s
		s = tmp
	}

	if composedOfString(s, t) {
		return len(t)
	}

	if composedOf(s, 'a') && composedOf(t, 'a') {
		return 1
	}

	if composedOf(s, 'b') && composedOf(t, 'b') {
		return 1
	}

	return -1
}

func composedOf(s string, r rune) bool {
	for _, v := range s {
		if v != r {
			return false
		}
	}

	return true
}

func composedOfString(s string, r string) bool {
	for len(s) > 0 {
		if len(s) < len(r) {
			return false
		}

		if s[:len(r)] != r {
			return false
		}

		s = s[len(r):]
	}

	return true
}

package main

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

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

func main() {
	defer writer.Flush()

	var q int
	fmt.Fscan(reader, &q)

	for i := 0; i < q; i++ {
		var s, t string
		fmt.Fscan(reader, &s, &t)

		g := gcd(s, t)
		if g == -1 {
			fmt.Fprintln(writer, -1)
			continue
		}

		lcm := len(s) * len(t) / g
		ans := s

		for len(ans) < lcm {
			ans += s
		}

		fmt.Fprintln(writer, ans)
	}
}

func gcd(s, t string) int {
	if composedOf(s, 'a') && composedOf(t, 'a') {
		return 1
	}

	if composedOf(s, 'b') && composedOf(t, 'b') {
		return 1
	}

	if len(t) > len(s) {
		tmp := t
		t = s
		s = tmp
	}

	if !composedOfString(s, t) {
		return -1
	}

	return len(t)
}

func composedOf(s string, r rune) bool {
	for _, v := range s {
		if v != r {
			return false
		}
	}

	return true
}

func composedOfString(s string, r string) bool {
	for len(s) > 0 {
		if len(s) < len(r) {
			return false
		}

		if s[:len(r)] != r {
			return false
		}

		s = s[len(r):]
	}

	return true
}

package main

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

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
	t   int
	a   string
	b   string
)

func main() {

	defer out.Flush()

	fmt.Fscan(in, &t)

	for ; t > 0; t-- {

		fmt.Fscan(in, &a)
		fmt.Fscan(in, &b)

		solve(a, b)

	}

}

func solve(a string, b string) {

	index := 0
	flag := true

	if len(a) >= len(b) {

		for i := 0; i < len(a); i++ {

			if a[i] != b[index] {
				flag = false
			}

			index++

			if index == len(b) {
				index = 0
			}

		}

		if a[len(a)-1] != b[len(b)-1] {
			flag = false
		}

		if flag {
			for i := 0; i < Lcm(len(a), len(b)); i++ {

				fmt.Fprintf(out, "%c", b[index])

				index++

				if index == len(b) {
					index = 0
				}

				if i == Lcm(len(a), len(b))-1 {
					fmt.Fprintf(out, "\n")
				}

			}
		} else {
			fmt.Fprintln(out, "-1")
		}

	} else {

		for i := 0; i < len(b); i++ {

			if b[i] != a[index] {
				flag = false
			}

			index++

			if index == len(a) {
				index = 0
			}

		}

		if a[len(a)-1] != b[len(b)-1] {
			flag = false
		}

		if flag {
			for i := 0; i < Lcm(len(a), len(b)); i++ {

				fmt.Fprintf(out, "%c", a[index])

				index++

				if index == len(a) {
					index = 0
				}

				if i == Lcm(len(a), len(b))-1 {
					fmt.Fprintf(out, "\n")
				}

			}
		} else {
			fmt.Fprintln(out, "-1")
		}

	}

}

//最大公因數
func Gcd(a int, b int) int {
	var twoCounter uint

	for {
		if a == b || b == 0 {
			return a << twoCounter
		} else if a == 0 {
			return b << twoCounter
		} else if a&1 == 0 {
			a >>= 1

			if b&1 == 0 {
				b >>= 1

				twoCounter += 1
			}
		} else if b&1 == 0 {
			b >>= 1
		} else if a > b {
			a = (a - b) >> 1
		} else {
			b = (b - a) >> 1
		}
	}
}

//最小公倍數
func Lcm(a int, b int) int {
	return a * b / Gcd(a, b)
}

package main

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

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

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

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

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func sbytes() []byte {
	scanner.Scan()
	return scanner.Bytes()
}

func main() {
	defer writer.Flush()
	for t := sint64(); t > 0; t-- {
		ss := sstring()
		tt := sstring()
		printf("%s\n", sol(ss, tt))
	}
}

func sol(s, t string) string {
	si, ti := 0, 0
	count := 0
	flag := false
	for {
		if s[si] != t[ti] {
			return "-1"
		}
		count++
		if si == 0 && ti == 0 && flag {
			break
		}
		flag = true
		si++
		si %= len(s)
		ti++
		ti %= len(t)
	}
	ret := ""
	for i := 0; i < count/len(s); i++ {
		ret += s
	}
	return ret
}