Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a1, a2, ..., ak.Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another n - k cities, and, of course, flour delivery should be paid — for every kilometer of path between storage and bakery Masha should pay 1 ruble.Formally, Masha will pay x roubles, if she will open the bakery in some city b (ai ≠ b for every 1 ≤ i ≤ k) and choose a storage in some city s (s = aj for some 1 ≤ j ≤ k) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 105, 0 ≤ k ≤ n) — the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then m lines follow. Each of them contains three integers u, v and l (1 ≤ u, v ≤ n, 1 ≤ l ≤ 109, u ≠ v) meaning that there is a road between cities u and v of length of l kilometers . If k > 0, then the last line of the input contains k distinct integers a1, a2, ..., ak (1 ≤ ai ≤ n) — the number of cities having flour storage located in. If k = 0 then this line is not presented in the input.

Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the n cities, print  - 1 in the only line.

NoteImage illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened.

package main

import "container/heap"
import "bufio"
import "os"
import "strconv"

type Item struct {
	value    int
	priority int64
	index    int
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].priority < pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

var in *bufio.Scanner
var out *bufio.Writer

const inf = int64(10000000000000000)

var n, m, k, e int
var adj, next, last, dist []int
var storage, fixed []bool
var best []int64
var queue PriorityQueue

func add(u int, v int, l int) {
	adj = append(adj, v)
	dist = append(dist, l)
	next = append(next, last[u])
	last[u] = e
	e++
}

func main() {
	in = bufio.NewScanner(os.Stdin)
	out = bufio.NewWriter(os.Stdout)

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan()
	n, _ = strconv.Atoi(in.Text())

	in.Scan()
	m, _ = strconv.Atoi(in.Text())

	in.Scan()
	k, _ = strconv.Atoi(in.Text())

	for i := 0; i <= n; i++ {
		last = append(last, -1)
		storage = append(storage, false)
		best = append(best, inf)
		fixed = append(fixed, false)
	}
	e = 0

	for i := 0; i < m; i++ {
		in.Scan()
		u, _ := strconv.Atoi(in.Text())
		in.Scan()
		v, _ := strconv.Atoi(in.Text())
		in.Scan()
		l, _ := strconv.Atoi(in.Text())
		add(u, v, l)
		add(v, u, l)
	}

	root := 0

	for i := 0; i < k; i++ {
		in.Scan()
		a, _ := strconv.Atoi(in.Text())
		storage[a] = true
		add(root, a, 0)
	}

	best[root] = 0

	queue = append(queue, &Item{value: root, priority: best[root], index: 0})
	heap.Init(&queue)

	for queue.Len() > 0 {
		item := heap.Pop(&queue).(*Item)
		u := item.value

		if !fixed[u] {
			fixed[u] = true
			for i := last[u]; i != -1; i = next[i] {
				v := adj[i]
				cost := int64(dist[i])
				if best[v] > best[u]+cost {
					best[v] = best[u] + cost
					newItem := &Item{value: v, priority: best[v]}
					heap.Push(&queue, newItem)
				}
			}
		}
	}

	res := inf
	for i := 1; i <= n; i++ {
		if !storage[i] {
			if res > best[i] {
				res = best[i]
			}
		}
	}

	if res >= inf {
		res = -1
	}

	out.WriteString(strconv.FormatInt(res, 10))
	out.WriteByte('\n')
}

package main

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

type Road struct {
	dest   int
	length int
}

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

	roads := make([][]Road, n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; i < m; i++ {
		scanner.Scan()
		u, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		scanner.Scan()
		v, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		scanner.Scan()
		l, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}

		roads[u-1] = append(roads[u-1], Road{v, l})
		roads[v-1] = append(roads[v-1], Road{u, l})
	}

	storage := make(map[int]int)
	for i := 0; i < k; i++ {
		scanner.Scan()
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		storage[a] = a
	}

	if len(storage) < 0 {
		fmt.Println(-1)
		return
	}

	minimal := -1
	for i := 0; i < n; i++ {
		if _, exist := storage[i+1]; !exist { // Non storage city
			for j := 0; j < len(roads[i]); j++ {
				if _, exist := storage[roads[i][j].dest]; exist { // Storage city
					if minimal < 0 || minimal > roads[i][j].length {
						minimal = roads[i][j].length
					}
				}
			}
		}
	}
	fmt.Println(minimal)
}

package main

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

type edge struct {
	to  int
	len int
}

type vertex struct {
	edges []edge
}

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

	var u, v, l int
	g := make([]vertex, n+1, n+1)
	bs := bufio.NewScanner(os.Stdin)
	bs.Split(bufio.ScanWords)
	for i := 0; i < m; i++ {
		//fmt.Scan(&u, &v, &l)
		bs.Scan()
		u, _ = strconv.Atoi(bs.Text())
		bs.Scan()
		v, _ = strconv.Atoi(bs.Text())
		bs.Scan()
		l, _ = strconv.Atoi(bs.Text())

		eu := edge{v, l}
		g[u].edges = append(g[u].edges, eu)
		ev := edge{u, l}
		g[v].edges = append(g[v].edges, ev)
	}

	an := make([]int, n+1, n+1)
	for i := 0; i < k; i++ {
		//fmt.Scan(&ax)
		bs.Scan()
		ax, _ := strconv.Atoi(bs.Text())
		an[ax] = 1
	}

	ans := -1
	for i := 1; i <= n; i++ {
		if an[i] == 0 {
			continue
		}
		for j := 0; j < len(g[i].edges); j++ {
			v = g[i].edges[j].to
			l = g[i].edges[j].len
			if an[v] == 0 && (ans == -1 || ans > l) {
				ans = l
			}
		}
	}

	fmt.Println(ans)
}

package main

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

type TupleInt struct {
	first  int
	second int
	third  int
}

func main() {
	in := NewScanner()
	var _, m, k int
	_ = in.NextInt()
	m = in.NextInt()
	k = in.NextInt()
	edge := make([]TupleInt, m)
	for i := 0; i < m; i++ {
		list := in.NextIntArray()
		edge[i] = TupleInt{list[0], list[1], list[2]}

	}
	a := map[int]bool{}

	for i := 0; i < k; i++ {
		var v int
		v = in.NextInt()
		a[v] = true
	}
	mn := -1
	for _, v := range edge {
		_, ok := a[v.first]
		_, ok2 := a[v.second]
		if ok == ok2 {
			continue
		}
		if mn == -1 || mn > v.third {
			mn = v.third
		}

	}
	fmt.Println(mn)
}

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) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			result = append(result, v)
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	result = append(result, v)

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

package main

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

type TupleInt struct {
	first  int
	second int
	third  int
}

func main() {
	in := NewScanner()
	var _, m, k int
	_ = in.NextInt()
	m = in.NextInt()
	k = in.NextInt()
	edge := make([]TupleInt, m)
	for i := 0; i < m; i++ {
		var u, v, l int
		u = in.NextInt()
		v = in.NextInt()
		l = in.NextInt()
		edge[i] = TupleInt{u, v, l}

	}
	a := map[int]bool{}

	for i := 0; i < k; i++ {
		var v int
		v = in.NextInt()
		a[v] = true
	}
	mn := -1
	for _, v := range edge {
		_, ok := a[v.first]
		_, ok2 := a[v.second]
		if ok == ok2 {
			continue
		}
		if mn == -1 || mn > v.third {
			mn = v.third
		}

	}
	fmt.Println(mn)
}

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) NextLine() string {
	if s.p >= len(s.buf) {
		s.readLine()
	}

	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}

	return string(s.buf[start:s.p])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.NextLine())
	s.p++
	return v
}

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
		}
	}
	s.p = 0

}

package main

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

type TupleInt struct {
	first  int
	second int
	third  int
}

func main() {
	in := bufio.NewScanner(os.Stdin)
	in.Split(bufio.ScanWords)
	var _, m, k int
	in.Scan()
	_, _ = strconv.Atoi(in.Text())
	in.Scan()
	m, _ = strconv.Atoi(in.Text())
	in.Scan()
	k, _ = strconv.Atoi(in.Text())
	edge := make([]TupleInt, m)
	for i := 0; i < m; i++ {
		var u, v, l int
		in.Scan()
		u, _ = strconv.Atoi(in.Text())
		in.Scan()
		v, _ = strconv.Atoi(in.Text())
		in.Scan()
		l, _ = strconv.Atoi(in.Text())
		edge[i] = TupleInt{u, v, l}

	}
	a := map[int]bool{}

	for i := 0; i < k; i++ {
		var v int
		in.Scan()
		v, _ = strconv.Atoi(in.Text())
		a[v] = true
	}
	mn := -1
	for _, v := range edge {
		_, ok := a[v.first]
		_, ok2 := a[v.second]
		if ok == ok2 {
			continue
		}
		if mn == -1 || mn > v.third {
			mn = v.third
		}

	}
	fmt.Println(mn)
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math/rand"
	"os"
)

const INF  = 1000000001

type Pair struct {
	first, second int
}

func sort(arr []int) []int {
	if len(arr) < 2 {
		return arr
	}
	left := 0
	right := len(arr) - 1
	pivot := rand.Int() % len(arr)

	arr[pivot], arr[right] = arr[right], arr[pivot]

	for i := 0; i < len(arr); i++ {
		if arr[i] < arr[right] {
			arr[i], arr[left] = arr[left], arr[i]
			left++
		}
	}

	arr[left], arr[right] = arr[right], arr[left]

	sort(arr[:left])
	sort(arr[left+1:])
	return arr
}

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

func solution(reader io.Reader, writer io.Writer) {
	var n, m, k int
	fmt.Fscanf(reader, "%d %d %d\n", &n, &m, &k)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = INF
	}

	l := make([]int, m)
	r := make([]int, m)
	w := make([]int, m)

	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d %d %d\n", &l[i], &r[i], &w[i])
		l[i]--
		r[i]--
	}

	h := make(map[int]bool)

	for i := 0; i < k; i++ {
		var l int
		fmt.Fscanf(reader, "%d", &l)
		l--
		h[l] = true
	}

	res := INF
	for i := 0; i < m; i++ {
		_, ok1 := h[l[i]]
		_, ok2 := h[r[i]]
		if (ok1 && !ok2) || (!ok1 && ok2) {
			res = min(res, w[i])
		}
	}
	if res == INF {
		res = -1
	}
	fmt.Println(res)
}

func main() {

	//stdin, err := os.Open("file.in")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	//stdout, err := os.Create("file.out")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)
	defer writer.Flush()

	solution(reader, writer)
}

package main

import "bufio"
import "os"
import "strconv"

var in *bufio.Scanner
var out *bufio.Writer

var n, m, k, e int
var adj, next, last, dist []int
var storage []bool
var best []int64

func add(u int, v int, l int) {
	adj[e] = v
	dist[e] = l
	next[e] = last[u]
	last[u] = e
	e++
}

func main() {
	in = bufio.NewScanner(os.Stdin)
	out = bufio.NewWriter(os.Stdout)

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan()
	n, _ = strconv.Atoi(in.Text())

	in.Scan()
	m, _ = strconv.Atoi(in.Text())

	in.Scan()
	k, _ = strconv.Atoi(in.Text())

	adj = make([]int, m*2+1)
	next = make([]int, m*2+1)
	dist = make([]int, m*2+1)
	last = make([]int, n+1)
	storage = make([]bool, n+1)
	best = make([]int64, n+1)

	for i := 0; i <= n; i++ {
		last[i] = -1
		storage[i] = false
		best[i] = -1
	}
	e = 0

	for i := 0; i < m; i++ {
		in.Scan()
		u, _ := strconv.Atoi(in.Text())
		in.Scan()
		v, _ := strconv.Atoi(in.Text())
		in.Scan()
		l, _ := strconv.Atoi(in.Text())
		add(u, v, l)
		add(v, u, l)
	}

	queue := make([]int, n+1)
	front := 0
	back := 0

	for i := 0; i < k; i++ {
		in.Scan()
		a, _ := strconv.Atoi(in.Text())
		storage[a] = true
		best[a] = 0
		queue[back] = a
		back++
	}

	for front < back {
		u := queue[front]
		front++

		for i := last[u]; i != -1; i = next[i] {
			v := adj[i]
			cost := int64(dist[i])
			if best[v] == -1 {
				best[v] = best[u] + cost
				queue[back] = v
				back++
			}
		}
	}

	res := int64(-1)
	for i := 1; i <= n; i++ {
		if !storage[i] {
			if (res == -1) || (res > best[i]) {
				res = best[i]
			}
		}
	}

	out.WriteString(strconv.FormatInt(res, 10))
	out.WriteByte('\n')
}

package main

import "fmt"

type edge struct {
	u int
	v int
	l int
}

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

	edges := make([]edge, m+1, m+1)
	for i := 0; i < m; i++ {
		fmt.Scan(&edges[i].u, &edges[i].v, &edges[i].l)
	}

	an := make([]int, k, k)
	for i := 0; i < k; i++ {
		fmt.Scan(&an[i])
	}

	ans := -1
	for i := 0; i < k; i++ {
		for j := 0; j < m; j++ {
			if edges[j].u == an[i] || edges[j].v == an[i] {
				if ans == -1 || ans > edges[j].l {
					ans = edges[j].l
				}
			}
		}
	}

	fmt.Println(ans)
}

package main

import "fmt"

type edge struct {
	to  int
	len int
}

type vertex struct {
	edges []edge
}

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

	var u, v, l int
	g := make([]vertex, n+1, n+1)
	for i := 0; i < m; i++ {
		fmt.Scan(&u, &v, &l)

		eu := edge{v, l}
		g[u].edges = append(g[u].edges, eu)
		ev := edge{u, l}
		g[v].edges = append(g[v].edges, ev)
	}

	var ax int
	an := make([]int, n+1, n+1)
	for i := 0; i < k; i++ {
		fmt.Scan(&ax)
		an[ax] = 1
	}

	ans := -1
	for i := 1; i <= n; i++ {
		if an[i] == 0 {
			continue
		}
		for j := 0; j < len(g[i].edges); j++ {
			v = g[i].edges[j].to
			l = g[i].edges[j].len
			if an[v] == 0 && ans == -1 || ans > l {
				ans = l
			}
		}
	}

	fmt.Println(ans)
}

package main

import (
	"fmt"
)

func main() {
	var n, m, k int
	fmt.Scan(&n, &m, &k)
	edge := make([][]int, n)
	for i := 0; i < n; i++ {
		edge[i] = make([]int, n)
	}

	for i := 0; i < m; i++ {
		var u, v, l int
		fmt.Scan(&u, &v, &l)
		edge[u - 1][v - 1] = l
		edge[v - 1][u - 1] = l
	}
	a := make([]int, k)
	for i := 0; i < k; i++ {
		fmt.Scan(&a[i])
	}
	mn := -1
	for i := 0; i < k; i++ {
		for j := 0; j < n; j++ {
			h := edge[a[i] - 1][j]
			if h == 0 {
				continue
			}
			if mn == -1 || mn > h {
				mn = h
			}
		}
	}
	fmt.Println(mn)
}

package main

import (
	"fmt"
)

func main() {
	var n, m, k int
	fmt.Scan(&n, &m, &k)
	edge := make([][]int, n)
	for i := 0; i < n; i++ {
		edge[i] = make([]int, n)
	}

	for i := 0; i < m; i++ {
		var u, v, l int
		fmt.Scan(&u, &v, &l)
		if edge[u - 1][v - 1] == 0 || edge[u - 1][v - 1] > l {
			edge[u - 1][v - 1] = l
			edge[v - 1][u - 1] = l
		}
	}
	a := make([]int, k)
	for i := 0; i < k; i++ {
		fmt.Scan(&a[i])
	}
	mn := -1
	for i := 0; i < k; i++ {
		for j := 0; j < n; j++ {
			h := edge[a[i] - 1][j]
			if h == 0 {
				continue
			}
			if mn == -1 || mn > h {
				mn = h
			}
		}
	}
	fmt.Println(mn)
}

package main

import (
	"fmt"
	"sort"
)

type TupleInt struct {
	first  int
	second int
}

func main() {
	var n, m, k int
	fmt.Scan(&n, &m, &k)
	edge := make([][]TupleInt, n + 1)
	for i := 0; i <= n; i++ {
		edge[i] = make([]TupleInt, 0)
	}

	for i := 0; i < m; i++ {
		var u, v, l int
		fmt.Scan(&u, &v, &l)
		edge[u] = append(edge[u], TupleInt{v, l})
		edge[v] = append(edge[v], TupleInt{u, l})

	}
	a := map[int]bool{}

	for i := 0; i < k; i++ {
		var v int
		fmt.Scan(&v)
		a[v] = true
	}
	mn := -1
	for i := 0; i < n; i++ {
		if _, ok := a[i]; !ok {
			continue
		}
		ll := len(edge[i])
		for j := 0; j < ll; j++ {
			h := edge[i][j]
			if mn == -1 || mn > h.second {
				if _, ok := a[h.first]; !ok {
					mn = h.second
				}
			}
		}
	}
	fmt.Println(mn)
}

func inArray(sorted []int, value int) bool {
	result := sort.SearchInts(sorted, value)
	if result == len(sorted) {
		return false
	}
	return sorted[result] == value
}

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


Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has n clock stations, station number i is at point (xi, yi) of the plane. As the player visits station number i, he increases the current time on his timer by ai. The stations are for one-time use only, so if the player visits some station another time, the time on his timer won't grow.A player spends d·dist time units to move between stations, where dist is the distance the player has covered and d is some constant. The distance between stations i and j is determined as |xi - xj| + |yi - yj|.Initially, the player is at station number 1, and the player has strictly more than zero and strictly less than one units of time. At station number 1 one unit of money can increase the time on the timer by one time unit (you can buy only integer number of time units).Now Yaroslav is wondering, how much money he needs to get to station n. Help Yaroslav. Consider the time to buy and to increase the timer value negligibly small.

The first line contains integers n and d (3 ≤ n ≤ 100, 103 ≤ d ≤ 105) — the number of stations and the constant from the statement. The second line contains n - 2 integers: a2, a3, ..., an - 1 (1 ≤ ai ≤ 103). The next n lines contain the coordinates of the stations. The i-th of them contains two integers xi, yi (-100 ≤ xi, yi ≤ 100). It is guaranteed that no two stations are located at the same point.

In a single line print an integer — the answer to the problem.

package main

import (
	"errors"
	"fmt"
	"math"
	"strconv"
)

// Route 描述从顶点From到顶点To经过的顶点Via和权重Cost
type Route struct {
	From   Vertex
	To     Vertex
	Via    Vertex
	Weight float64
}

// Vertex 即Graph中的顶点v
type Vertex struct {
	id   int
	Name string
}

// Edge 即Graph中的边e
type Edge struct {
	id     int
	From   *Vertex
	To     *Vertex
	Weight float64
}

// Graph 描述整张图，且Graph是非协程安全的
type Graph struct {
	vertices []*Vertex
	edges    []*Edge

	// nameToID["foo"] := 顶点foo的ID
	nameToID map[string]int
	// idToOutEdges[0] := 从ID为0的顶点出发的所有边的ID
	idToOutEdges map[int][]int
}

// NewGraph 创建一个空图
func NewGraph() *Graph {
	return &Graph{
		vertices: make([]*Vertex, 0),
		edges:    make([]*Edge, 0),

		nameToID:     make(map[string]int),
		idToOutEdges: make(map[int][]int),
	}
}

// AddEdge 添加一条边到Graph中，如果顶点from或顶点to不在图中，则创建它们，允许重边被添加
func (g *Graph) AddEdge(from string, to string, weight float64) error {
	if weight < 0 {
		return errors.New("weight should not be negative")
	}

	fromID, found := g.nameToID[from]
	if !found {
		v := &Vertex{
			Name: from,
			id:   len(g.vertices),
		}
		g.vertices = append(g.vertices, v)
		g.nameToID[from] = v.id
		fromID = v.id
	}

	toID, found := g.nameToID[to]
	if !found {
		v := &Vertex{
			Name: to,
			id:   len(g.vertices),
		}
		g.vertices = append(g.vertices, v)
		g.nameToID[to] = v.id
		toID = v.id
	}

	e := &Edge{
		From:   g.vertices[fromID],
		To:     g.vertices[toID],
		Weight: weight,
		id:     len(g.edges),
	}
	g.edges = append(g.edges, e)

	if _, found := g.idToOutEdges[fromID]; !found {
		g.idToOutEdges[fromID] = make([]int, 0)
	}
	g.idToOutEdges[fromID] = append(g.idToOutEdges[fromID], e.id)

	return nil
}

// ShortestPath 求出从顶点from出发到所有其他顶点的最短路径，如果顶点from不存在则返回错误
func (g *Graph) ShortestPath(from string) ([]Route, error) {
	fromID, found := g.nameToID[from]
	if !found {
		return nil, fmt.Errorf("there is no such vertex named %s", from)
	}

	verticesNum := len(g.vertices)
	minWeight := make([]float64, verticesNum) // minWeight[i] := 从ID为fromID的顶点到ID为i的顶点的最小权重
	for i := 0; i < verticesNum; i++ {
		minWeight[i] = math.MaxFloat64
	}
	done := make([]bool, verticesNum) // done[i] := ID为i的顶点已被求出最短路
	for i := 0; i < verticesNum; i++ {
		done[i] = false
	}
	via := make([]int, verticesNum) // via[i] := 从ID为fromID的顶点到ID为i的顶点的下一跳节点ID
	for i := 0; i < verticesNum; i++ {
		via[i] = -1
	}

	minWeight[fromID] = 0
	for {
		// 找到未被求出最短路，且minWeight最小的的顶点ID
		fromID := -1
		for i := 0; i < verticesNum; i++ {
			if done[i] {
				continue
			}
			if minWeight[i] == math.MaxFloat64 {
				continue
			}
			if fromID == -1 || minWeight[i] < minWeight[fromID] {
				fromID = i
			}
		}

		if fromID == -1 {
			// 所有顶点都已被求出最短路
			break
		}

		// 松弛ID为v的顶点的所有出边
		for _, outEdgeID := range g.idToOutEdges[fromID] {
			edge := g.edges[outEdgeID]
			toID := edge.To.id
			if minWeight[toID] == math.MaxFloat64 || minWeight[fromID]+edge.Weight < minWeight[toID] {
				minWeight[toID] = minWeight[fromID] + edge.Weight
				if via[fromID] == -1 {
					via[toID] = toID
				} else {
					via[toID] = via[fromID]
				}
			}
		}

		done[fromID] = true
	}

	routes := make([]Route, 0)
	for i := 0; i < verticesNum; i++ {
		if via[i] == -1 {
			continue
		}
		routes = append(routes, Route{
			From:   *g.vertices[fromID],
			To:     *g.vertices[i],
			Via:    *g.vertices[via[i]],
			Weight: minWeight[i],
		})
	}

	return routes, nil
}

func main() {
	graph := NewGraph()
	var n, d int
	var a []int
	var x, y []int
	fmt.Scanf("%d%d", &n, &d)
	fmt.Scanf("\n")
	a = append(a, 0)
	for i := 1; i < n-1; i++ {
		var x int
		fmt.Scanf("%d", &x)
		a = append(a, x)
	}
	fmt.Scanf("\n")
	a = append(a, 0)
	for i := 0; i < n; i++ {
		var q, w int
		fmt.Scanf("%d%d\n", &q, &w)
		x = append(x, q)
		y = append(y, w)
	}

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			cost := (abs(x[i]-x[j])+abs(y[i]-y[j]))*d - a[j]
			graph.AddEdge(strconv.Itoa(i), strconv.Itoa(j), float64(cost))
		}
	}

	routes, _ := graph.ShortestPath("0")
	for _, route := range routes {
		if route.To.Name == strconv.Itoa(n-1) {
			fmt.Println(int(route.Weight + 0.000000005))
			break
		}
	}
}

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

package main

import (
	"errors"
	"fmt"
	"strconv"
)

const (
	UNSET = -1
)

type Route struct {
	From string
	To   string
	Via  string
	Cost int
}

type Vertex struct {
	Name string
	id   int
}

type Edge struct {
	From string
	To   string
	Cost int
}

type Graph struct {
	vertices    []*Vertex
	cost        [][]int
	name2vertex map[string]*Vertex
}

// Construct a empty graph.
func NewGraph() *Graph {
	graph := new(Graph)
	graph.vertices = make([]*Vertex, 0)
	graph.name2vertex = make(map[string]*Vertex)
	return graph
}

// Find if "name" is in graph
func (g *Graph) FindVertex(name string) bool {
	if _, ok := g.name2vertex[name]; !ok {
		return false
	}
	return true
}

// Get all vertex.
// An error is returned if there is no such vertex named "name".
func (g *Graph) GetAllVertices() []string {
	vertices := make([]string, len(g.vertices))
	for i := 0; i < len(vertices); i++ {
		vertices[i] = g.vertices[i].Name
	}
	return vertices
}

// Add a vertex into graph.
// An error is returned if the vertex already exists.
func (g *Graph) AddVertex(name string) error {
	if v, ok := g.name2vertex[name]; !ok {
		v = &Vertex{
			id:   len(g.vertices),
			Name: name,
		}
		g.vertices = append(g.vertices, v)
		g.name2vertex[name] = v
		return nil
	} else {
		return errors.New(fmt.Sprintf("%s already exists", name))
	}
}

// Initialize graph after add Vertices.
// We need this method since we use adjacency matrix to implement the graph.
func (g *Graph) Init() {
	num := len(g.vertices)
	g.cost = make([][]int, num)
	for i := range g.cost {
		g.cost[i] = make([]int, num)
		for j := range g.cost[i] {
			g.cost[i][j] = UNSET
		}
	}
}

// Make a snapshot
// REQUIRE: Init graph firstly.
func (g *Graph) Snapshot() *Graph {
	newGraph := NewGraph()
	newGraph.cost = make([][]int, len(g.vertices))
	for i := range newGraph.cost {
		newGraph.cost[i] = make([]int, len(g.vertices))
		for j := range newGraph.cost[i] {
			newGraph.cost[i][j] = g.cost[i][j]
		}
	}
	for k, v := range g.name2vertex {
		newV := &Vertex{
			id:   v.id,
			Name: v.Name,
		}
		newGraph.vertices = append(newGraph.vertices, newV)
		newGraph.name2vertex[k] = newV
	}
	return newGraph
}

// Add a edge into graph.
// The cost of edge will be overridden if there are multiple edges from "from" to "to".
// An error is returned if there is no such vertex named "from" or "to", or cost is negative.
// REQUIRE: Init graph firstly.
func (g *Graph) AddEdge(from string, to string, cost int) error {
	if cost < 0 {
		return errors.New("cost should not be negative")
	}

	var f, t *Vertex
	var ok bool
	if f, ok = g.name2vertex[from]; !ok {
		return errors.New("there is no such vertex named " + from)
	}
	if t, ok = g.name2vertex[to]; !ok {
		return errors.New("there is no such vertex named " + to)
	}

	g.cost[f.id][t.id] = cost
	return nil
}

// Get edge from graph.
// An error is returned if there is no such vertex named "from" or "to".
// REQUIRE: Init graph firstly.
func (g *Graph) GetEdge(from string, to string) (*Edge, error) {
	var f, t *Vertex
	var ok bool
	if f, ok = g.name2vertex[from]; !ok {
		return nil, errors.New("there is no such vertex named " + from)
	}
	if t, ok = g.name2vertex[to]; !ok {
		return nil, errors.New("there is no such vertex named " + to)
	}
	return &Edge{From: from, To: to, Cost: g.cost[f.id][t.id]}, nil
}

// Relax the graph start with "name".
// This method is routine-safe since the graph is read-only.
// REQUIRE: Init graph firstly.
func (g *Graph) RelaxStartWith(name string) ([]*Route, error) {
	var start *Vertex
	var ok bool
	if start, ok = g.name2vertex[name]; !ok {
		return nil, errors.New("there is no such vertex named " + name)
	}

	num := len(g.vertices)
	relaxed := make([]bool, num)
	for i := range relaxed {
		relaxed[i] = false
	}
	minCost := make([]int, num)
	for i := range minCost {
		minCost[i] = UNSET
	}
	via := make([][]*Vertex, num)
	for i := range via {
		via[i] = make([]*Vertex, num)
		for j := range via[i] {
			via[i][j] = nil
		}
	}

	// Dijkstra without heap optimization.
	minCost[start.id] = 0
	for {
		// Find a vertex to relax.
		var u *Vertex = nil
		for _, v := range g.vertices {
			if relaxed[v.id] {
				continue
			}
			if minCost[v.id] != UNSET && (u == nil || minCost[v.id] < minCost[u.id]) {
				u = v
			}
		}

		// There is no vertex to relax.
		if u == nil {
			break
		}

		// Relax vertex u
		for _, v := range g.vertices {
			if g.cost[u.id][v.id] == UNSET {
				continue
			}
			if minCost[v.id] == UNSET || minCost[u.id]+g.cost[u.id][v.id] < minCost[v.id] {
				minCost[v.id] = minCost[u.id] + g.cost[u.id][v.id]
				if via[start.id][u.id] == nil {
					via[start.id][v.id] = v
				} else {
					via[start.id][v.id] = via[start.id][u.id]
				}
			}
		}

		relaxed[u.id] = true
	}

	route := make([]*Route, 0)
	for _, v := range g.vertices {
		if via[start.id][v.id] == nil {
			continue
		}
		route = append(route, &Route{
			From: start.Name,
			To:   v.Name,
			Via:  via[start.id][v.id].Name,
			Cost: minCost[v.id],
		})
	}
	return route, nil
}

// Relax the graph end with "name".
// This method is routine-safe since the graph is read-only.
// REQUIRE: Init graph firstly.
func (g *Graph) RelaxEndWith(name string) ([]*Route, error) {
	var end *Vertex
	var ok bool
	if end, ok = g.name2vertex[name]; !ok {
		return nil, errors.New("there is no such vertex named " + name)
	}

	num := len(g.vertices)
	relaxed := make([]bool, num)
	for i := range relaxed {
		relaxed[i] = false
	}
	minCost := make([]int, num)
	for i := range minCost {
		minCost[i] = UNSET
	}
	via := make([][]*Vertex, num)
	for i := range via {
		via[i] = make([]*Vertex, num)
		for j := range via[i] {
			via[i][j] = nil
		}
	}

	// Dijkstra without heap optimization.
	minCost[end.id] = 0
	for {
		// Find a vertex to relax.
		var u *Vertex = nil
		for _, v := range g.vertices {
			if relaxed[v.id] {
				continue
			}
			if minCost[v.id] != UNSET && (u == nil || minCost[v.id] < minCost[u.id]) {
				u = v
			}
		}

		// There is no vertex to relax.
		if u == nil {
			break
		}

		// Relax vertex u
		for _, v := range g.vertices {
			if g.cost[v.id][u.id] == UNSET {
				continue
			}
			if minCost[v.id] == UNSET || minCost[u.id]+g.cost[v.id][u.id] < minCost[v.id] {
				minCost[v.id] = minCost[u.id] + g.cost[u.id][v.id]
				if via[u.id][end.id] == nil {
					via[v.id][end.id] = end
				} else {
					via[v.id][end.id] = u
				}
			}
		}

		relaxed[u.id] = true
	}

	route := make([]*Route, 0)
	for _, v := range g.vertices {
		if via[v.id][end.id] == nil {
			continue
		}
		route = append(route, &Route{
			From: v.Name,
			To:   end.Name,
			Via:  via[v.id][end.id].Name,
			Cost: minCost[v.id],
		})
	}
	return route, nil
}

func main() {
	g := NewGraph()
	var n, d int
	var a []int
	var x, y []int
	fmt.Scanf("%d%d", &n, &d)
	fmt.Scanf("\n")
	a = append(a, 0)
	for i := 1; i < n-1; i++ {
		var x int
		fmt.Scanf("%d", &x)
		a = append(a, x)
	}
	fmt.Scanf("\n")
	a = append(a, 0)
	for i := 0; i < n; i++ {
		var q, w int
		fmt.Scanf("%d%d\n", &q, &w)
		x = append(x, q)
		y = append(y, w)
		g.AddVertex(strconv.Itoa(i))
	}
	g.Init()

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			cost := (abs(x[i]-x[j])+abs(y[i]-y[j]))*d - a[j]
			g.AddEdge(strconv.Itoa(i), strconv.Itoa(j), cost)
		}
	}

	route, _ := g.RelaxStartWith("0")
	for _, r := range route {
		if r.To == strconv.Itoa(n-1) {
			fmt.Println(r.Cost)
			break
		}
	}
}

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

package main

import (
	"errors"
	"fmt"
	"strconv"
)

const (
	UNSET = -1
)

type Route struct {
	From *Vertex
	To   *Vertex
	Via  *Vertex
	Cost int
}

type Vertex struct {
	Name string
	id   int
}

type Graph struct {
	Vertices    []*Vertex
	cost        [][]int
	name2vertex map[string]*Vertex
}

// Construct a empty graph.
func NewGraph() *Graph {
	graph := new(Graph)
	graph.Vertices = make([]*Vertex, 0)
	graph.name2vertex = make(map[string]*Vertex)
	return graph
}

// Get pointer to vertex via name.
// An error is returned if there is no such vertex named "name".
func (g *Graph) GetVertex(name string) (*Vertex, error) {
	if v, ok := g.name2vertex[name]; ok {
		return v, nil
	} else {
		return nil, errors.New("No such vertex")
	}
}

// Add a vertex into graph.
// An error is returned if the vertex already exists.
func (g *Graph) AddVertex(name string) (*Vertex, error) {
	if v, ok := g.name2vertex[name]; !ok {
		v = &Vertex{
			id:   len(g.Vertices),
			Name: name,
		}
		g.Vertices = append(g.Vertices, v)
		g.name2vertex[name] = v
		return v, nil
	} else {
		return nil, errors.New(fmt.Sprintf("%s already exists", name))
	}
}

// Initialize graph after add Vertices.
// We need this method since we use adjacency matrix to implement the graph.
func (g *Graph) Init() {
	num := len(g.Vertices)
	g.cost = make([][]int, num)
	for i := range g.cost {
		g.cost[i] = make([]int, num)
		for j := range g.cost[i] {
			g.cost[i][j] = UNSET
		}
	}
}

// Make a snapshot
// REQUIRE: Init graph firstly.
func (g *Graph) Snapshot() *Graph {
	newGraph := NewGraph()
	newGraph.cost = make([][]int, len(g.Vertices))
	for i := range newGraph.cost {
		newGraph.cost[i] = make([]int, len(g.Vertices))
		for j := range newGraph.cost[i] {
			newGraph.cost[i][j] = g.cost[i][j]
		}
	}
	for k, v := range g.name2vertex {
		newV := &Vertex{
			id:   v.id,
			Name: v.Name,
		}
		newGraph.Vertices = append(newGraph.Vertices, newV)
		newGraph.name2vertex[k] = newV
	}
	return newGraph
}

// Add a edge into graph.
// The cost of edge will be overridden if there are multiple edges from "from" to "to".
// An error is returned if these Vertices are invalid or cost is negative.
// REQUIRE: Init graph firstly.
func (g *Graph) AddEdge(from *Vertex, to *Vertex, cost int) error {
	if from == nil || to == nil {
		return errors.New("*Vertex should not be nil")
	}
	if cost < 0 {
		return errors.New("cost should not be negative")
	}
	if from.id >= len(g.Vertices) || to.id >= len(g.Vertices) {
		return errors.New(fmt.Sprintf("%+v or %+v is invalid", *from, *to))
	}

	g.cost[from.id][to.id] = cost
	return nil
}

// Relax the graph from a certain vertex.
// This method is routine-safe since the graph is read-only.
// REQUIRE: Init graph firstly.
func (g *Graph) Relax(from *Vertex) []*Route {
	num := len(g.Vertices)
	relaxed := make([]bool, num)
	for i := range relaxed {
		relaxed[i] = false
	}
	minCost := make([]int, num)
	for i := range minCost {
		minCost[i] = UNSET
	}
	via := make([][]*Vertex, num)
	for i := range via {
		via[i] = make([]*Vertex, num)
		for j := range via[i] {
			via[i][j] = nil
		}
	}

	// Dijkstra without heap optimization.
	minCost[from.id] = 0
	for {
		// Find a vertex to relax.
		var u *Vertex = nil
		for _, v := range g.Vertices {
			if relaxed[v.id] {
				continue
			}
			if minCost[v.id] != UNSET && (u == nil || minCost[v.id] < minCost[u.id]) {
				u = v
			}
		}

		// There is no vertex to relax.
		if u == nil {
			break
		}

		// Relax vertex u
		for _, v := range g.Vertices {
			if g.cost[u.id][v.id] == UNSET {
				continue
			}
			if minCost[v.id] == UNSET || minCost[u.id]+g.cost[u.id][v.id] < minCost[v.id] {
				minCost[v.id] = minCost[u.id] + g.cost[u.id][v.id]
				if via[from.id][u.id] == nil {
					via[from.id][v.id] = v
				} else {
					via[from.id][v.id] = via[from.id][u.id]
				}
			}
		}

		relaxed[u.id] = true
	}

	route := make([]*Route, 0)
	for _, v := range g.Vertices {
		if via[from.id][v.id] == nil {
			continue
		}
		route = append(route, &Route{
			From: from,
			To:   v,
			Via:  via[from.id][v.id],
			Cost: minCost[v.id],
		})
	}
	return route
}

func main() {
	g := NewGraph()
	var n, d int
	var a []int
	var x, y []int
	fmt.Scanf("%d%d", &n, &d)
	// fmt.Println(n)
	// fmt.Println(d)
	fmt.Scanf("\n")
	a = append(a, 0)
	for i := 1; i < n-1; i++ {
		var x int
		fmt.Scanf("%d", &x)
		// fmt.Println(x)
		a = append(a, x)
	}
	fmt.Scanf("\n")
	a = append(a, 0)
	for i := 0; i < n; i++ {
		var q, w int
		fmt.Scanf("%d%d\n", &q, &w)
		//fmt.Printf("%d %d\n", q, w)
		x = append(x, q)
		y = append(y, w)
		g.AddVertex(strconv.Itoa(i))
	}
	g.Init()

	// fmt.Println(n)
	// fmt.Println(d)
	// fmt.Println(a)
	// fmt.Println(x)
	// fmt.Println(y)

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			u, _ := g.GetVertex(strconv.Itoa(i))
			v, _ := g.GetVertex(strconv.Itoa(j))

			cost := (abs(x[i]-x[j])+abs(y[i]-y[j]))*d - a[j]
			g.AddEdge(u, v, cost)
		}
	}

	v, _ := g.GetVertex("0")
	route := g.Relax(v)
	for _, r := range route {
		if r.To.Name == strconv.Itoa(n-1) {
			fmt.Println(r.Cost)
			break
		}
	}
}

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

package main

import (
	"errors"
	"fmt"
	"strconv"
)

const (
	UNSET = -1
)

type Route struct {
	From string
	To   string
	Via  string
	Cost int
}

type Vertex struct {
	Name string
	id   int
}

type Edge struct {
	From string
	To   string
	Cost int
}

type Graph struct {
	vertices    []*Vertex
	cost        [][]int
	name2vertex map[string]*Vertex
}

// Construct a empty graph.
func NewGraph() *Graph {
	graph := new(Graph)
	graph.vertices = make([]*Vertex, 0)
	graph.name2vertex = make(map[string]*Vertex)
	return graph
}

// Find if "name" is in graph
func (g *Graph) FindVertex(name string) bool {
	if _, ok := g.name2vertex[name]; !ok {
		return false
	}
	return true
}

// Get all vertex.
// An error is returned if there is no such vertex named "name".
func (g *Graph) GetAllVertices() []string {
	vertices := make([]string, len(g.vertices))
	for i := 0; i < len(vertices); i++ {
		vertices[i] = g.vertices[i].Name
	}
	return vertices
}

// Add a vertex into graph.
// An error is returned if the vertex already exists.
func (g *Graph) AddVertex(name string) error {
	if v, ok := g.name2vertex[name]; !ok {
		v = &Vertex{
			id:   len(g.vertices),
			Name: name,
		}
		g.vertices = append(g.vertices, v)
		g.name2vertex[name] = v
		return nil
	} else {
		return errors.New(fmt.Sprintf("%s already exists", name))
	}
}

// Initialize graph after add Vertices.
// We need this method since we use adjacency matrix to implement the graph.
func (g *Graph) Init() {
	num := len(g.vertices)
	g.cost = make([][]int, num)
	for i := range g.cost {
		g.cost[i] = make([]int, num)
		for j := range g.cost[i] {
			g.cost[i][j] = UNSET
		}
	}
}

// Make a snapshot
// REQUIRE: Init graph firstly.
func (g *Graph) Snapshot() *Graph {
	newGraph := NewGraph()
	newGraph.cost = make([][]int, len(g.vertices))
	for i := range newGraph.cost {
		newGraph.cost[i] = make([]int, len(g.vertices))
		for j := range newGraph.cost[i] {
			newGraph.cost[i][j] = g.cost[i][j]
		}
	}
	for k, v := range g.name2vertex {
		newV := &Vertex{
			id:   v.id,
			Name: v.Name,
		}
		newGraph.vertices = append(newGraph.vertices, newV)
		newGraph.name2vertex[k] = newV
	}
	return newGraph
}

// Add a edge into graph.
// The cost of edge will be overridden if there are multiple edges from "from" to "to".
// An error is returned if there is no such vertex named "from" or "to", or cost is negative.
// REQUIRE: Init graph firstly.
func (g *Graph) AddEdge(from string, to string, cost int) error {
	if cost < 0 {
		return errors.New("cost should not be negative")
	}

	var f, t *Vertex
	var ok bool
	if f, ok = g.name2vertex[from]; !ok {
		return errors.New("there is no such vertex named " + from)
	}
	if t, ok = g.name2vertex[to]; !ok {
		return errors.New("there is no such vertex named " + to)
	}

	g.cost[f.id][t.id] = cost
	return nil
}

// Get edge from graph.
// An error is returned if there is no such vertex named "from" or "to".
// REQUIRE: Init graph firstly.
func (g *Graph) GetEdge(from string, to string) (*Edge, error) {
	var f, t *Vertex
	var ok bool
	if f, ok = g.name2vertex[from]; !ok {
		return nil, errors.New("there is no such vertex named " + from)
	}
	if t, ok = g.name2vertex[to]; !ok {
		return nil, errors.New("there is no such vertex named " + to)
	}
	return &Edge{From: from, To: to, Cost: g.cost[f.id][t.id]}, nil
}

// Relax the graph start with "name".
// This method is routine-safe since the graph is read-only.
// REQUIRE: Init graph firstly.
func (g *Graph) RelaxStartWith(name string) ([]*Route, error) {
	var start *Vertex
	var ok bool
	if start, ok = g.name2vertex[name]; !ok {
		return nil, errors.New("there is no such vertex named " + name)
	}

	num := len(g.vertices)
	relaxed := make([]bool, num)
	for i := range relaxed {
		relaxed[i] = false
	}
	minCost := make([]int, num)
	for i := range minCost {
		minCost[i] = UNSET
	}
	via := make([][]*Vertex, num)
	for i := range via {
		via[i] = make([]*Vertex, num)
		for j := range via[i] {
			via[i][j] = nil
		}
	}

	// Dijkstra without heap optimization.
	minCost[start.id] = 0
	for {
		// Find a vertex to relax.
		var u *Vertex = nil
		for _, v := range g.vertices {
			if relaxed[v.id] {
				continue
			}
			if minCost[v.id] != UNSET && (u == nil || minCost[v.id] < minCost[u.id]) {
				u = v
			}
		}

		// There is no vertex to relax.
		if u == nil {
			break
		}

		// Relax vertex u
		for _, v := range g.vertices {
			if g.cost[u.id][v.id] == UNSET {
				continue
			}
			if minCost[v.id] == UNSET || minCost[u.id]+g.cost[u.id][v.id] < minCost[v.id] {
				minCost[v.id] = minCost[u.id] + g.cost[u.id][v.id]
				if via[start.id][u.id] == nil {
					via[start.id][v.id] = v
				} else {
					via[start.id][v.id] = via[start.id][u.id]
				}
			}
		}

		relaxed[u.id] = true
	}

	route := make([]*Route, 0)
	for _, v := range g.vertices {
		if via[start.id][v.id] == nil {
			continue
		}
		route = append(route, &Route{
			From: start.Name,
			To:   v.Name,
			Via:  via[start.id][v.id].Name,
			Cost: minCost[v.id],
		})
	}
	return route, nil
}

// Relax the graph end with "name".
// This method is routine-safe since the graph is read-only.
// REQUIRE: Init graph firstly.
func (g *Graph) RelaxEndWith(name string) ([]*Route, error) {
	var end *Vertex
	var ok bool
	if end, ok = g.name2vertex[name]; !ok {
		return nil, errors.New("there is no such vertex named " + name)
	}

	num := len(g.vertices)
	relaxed := make([]bool, num)
	for i := range relaxed {
		relaxed[i] = false
	}
	minCost := make([]int, num)
	for i := range minCost {
		minCost[i] = UNSET
	}
	via := make([][]*Vertex, num)
	for i := range via {
		via[i] = make([]*Vertex, num)
		for j := range via[i] {
			via[i][j] = nil
		}
	}

	// Dijkstra without heap optimization.
	minCost[end.id] = 0
	for {
		// Find a vertex to relax.
		var u *Vertex = nil
		for _, v := range g.vertices {
			if relaxed[v.id] {
				continue
			}
			if minCost[v.id] != UNSET && (u == nil || minCost[v.id] < minCost[u.id]) {
				u = v
			}
		}

		// There is no vertex to relax.
		if u == nil {
			break
		}

		// Relax vertex u
		for _, v := range g.vertices {
			if g.cost[v.id][u.id] == UNSET {
				continue
			}
			if minCost[v.id] == UNSET || g.cost[v.id][u.id]+minCost[u.id] < minCost[v.id] {
				minCost[v.id] = g.cost[v.id][u.id] + minCost[u.id]
				if via[u.id][end.id] == nil {
					via[v.id][end.id] = end
				} else {
					via[v.id][end.id] = u
				}
			}
		}

		relaxed[u.id] = true
	}

	route := make([]*Route, 0)
	for _, v := range g.vertices {
		if via[v.id][end.id] == nil {
			continue
		}
		route = append(route, &Route{
			From: v.Name,
			To:   end.Name,
			Via:  via[v.id][end.id].Name,
			Cost: minCost[v.id],
		})
	}
	return route, nil
}

func main() {
	g := NewGraph()
	var n, d int
	var a []int
	var x, y []int
	fmt.Scanf("%d%d", &n, &d)
	fmt.Scanf("\n")
	a = append(a, 0)
	for i := 1; i < n-1; i++ {
		var x int
		fmt.Scanf("%d", &x)
		a = append(a, x)
	}
	fmt.Scanf("\n")
	a = append(a, 0)
	for i := 0; i < n; i++ {
		var q, w int
		fmt.Scanf("%d%d\n", &q, &w)
		x = append(x, q)
		y = append(y, w)
		g.AddVertex(strconv.Itoa(i))
	}
	g.Init()

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			cost := (abs(x[i]-x[j])+abs(y[i]-y[j]))*d - a[j]
			g.AddEdge(strconv.Itoa(i), strconv.Itoa(j), cost)
		}
	}

	route, _ := g.RelaxEndWith(strconv.Itoa(n - 1))
	for _, r := range route {
		if r.From == "0" {
			fmt.Println(r.Cost)
			break
		}
	}
}

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

package main

import (
	"errors"
	"fmt"
	"strconv"
)

const (
	UNSET = -1
)

type Route struct {
	From string
	To   string
	Via  string
	Cost int
}

type Vertex struct {
	Name string
	id   int
}

type Edge struct {
	From string
	To   string
	Cost int
}

type Graph struct {
	vertices    []*Vertex
	cost        [][]int
	name2vertex map[string]*Vertex
}

// Construct a empty graph.
func NewGraph() *Graph {
	graph := new(Graph)
	graph.vertices = make([]*Vertex, 0)
	graph.name2vertex = make(map[string]*Vertex)
	return graph
}

// Find if "name" is in graph
func (g *Graph) FindVertex(name string) bool {
	if _, ok := g.name2vertex[name]; !ok {
		return false
	}
	return true
}

// Get all vertex.
// An error is returned if there is no such vertex named "name".
func (g *Graph) GetAllVertices() []string {
	vertices := make([]string, len(g.vertices))
	for i := 0; i < len(vertices); i++ {
		vertices[i] = g.vertices[i].Name
	}
	return vertices
}

// Add a vertex into graph.
// An error is returned if the vertex already exists.
func (g *Graph) AddVertex(name string) error {
	if v, ok := g.name2vertex[name]; !ok {
		v = &Vertex{
			id:   len(g.vertices),
			Name: name,
		}
		g.vertices = append(g.vertices, v)
		g.name2vertex[name] = v
		return nil
	} else {
		return errors.New(fmt.Sprintf("%s already exists", name))
	}
}

// Initialize graph after add Vertices.
// We need this method since we use adjacency matrix to implement the graph.
func (g *Graph) Init() {
	num := len(g.vertices)
	g.cost = make([][]int, num)
	for i := range g.cost {
		g.cost[i] = make([]int, num)
		for j := range g.cost[i] {
			g.cost[i][j] = UNSET
		}
	}
}

// Make a snapshot
// REQUIRE: Init graph firstly.
func (g *Graph) Snapshot() *Graph {
	newGraph := NewGraph()
	newGraph.cost = make([][]int, len(g.vertices))
	for i := range newGraph.cost {
		newGraph.cost[i] = make([]int, len(g.vertices))
		for j := range newGraph.cost[i] {
			newGraph.cost[i][j] = g.cost[i][j]
		}
	}
	for k, v := range g.name2vertex {
		newV := &Vertex{
			id:   v.id,
			Name: v.Name,
		}
		newGraph.vertices = append(newGraph.vertices, newV)
		newGraph.name2vertex[k] = newV
	}
	return newGraph
}

// Add a edge into graph.
// The cost of edge will be overridden if there are multiple edges from "from" to "to".
// An error is returned if there is no such vertex named "from" or "to", or cost is negative.
// REQUIRE: Init graph firstly.
func (g *Graph) AddEdge(from string, to string, cost int) error {
	if cost < 0 {
		return errors.New("cost should not be negative")
	}

	var f, t *Vertex
	var ok bool
	if f, ok = g.name2vertex[from]; !ok {
		return errors.New("there is no such vertex named " + from)
	}
	if t, ok = g.name2vertex[to]; !ok {
		return errors.New("there is no such vertex named " + to)
	}

	g.cost[f.id][t.id] = cost
	return nil
}

// Get edge from graph.
// An error is returned if there is no such vertex named "from" or "to".
// REQUIRE: Init graph firstly.
func (g *Graph) GetEdge(from string, to string) (*Edge, error) {
	var f, t *Vertex
	var ok bool
	if f, ok = g.name2vertex[from]; !ok {
		return nil, errors.New("there is no such vertex named " + from)
	}
	if t, ok = g.name2vertex[to]; !ok {
		return nil, errors.New("there is no such vertex named " + to)
	}
	return &Edge{From: from, To: to, Cost: g.cost[f.id][t.id]}, nil
}

// Relax the graph start with "name".
// This method is routine-safe since the graph is read-only.
// REQUIRE: Init graph firstly.
func (g *Graph) RelaxStartWith(name string) ([]*Route, error) {
	var start *Vertex
	var ok bool
	if start, ok = g.name2vertex[name]; !ok {
		return nil, errors.New("there is no such vertex named " + name)
	}

	num := len(g.vertices)
	relaxed := make([]bool, num)
	for i := range relaxed {
		relaxed[i] = false
	}
	minCost := make([]int, num)
	for i := range minCost {
		minCost[i] = UNSET
	}
	via := make([][]*Vertex, num)
	for i := range via {
		via[i] = make([]*Vertex, num)
		for j := range via[i] {
			via[i][j] = nil
		}
	}

	// Dijkstra without heap optimization.
	minCost[start.id] = 0
	for {
		// Find a vertex to relax.
		var u *Vertex = nil
		for _, v := range g.vertices {
			if relaxed[v.id] {
				continue
			}
			if minCost[v.id] != UNSET && (u == nil || minCost[v.id] < minCost[u.id]) {
				u = v
			}
		}

		// There is no vertex to relax.
		if u == nil {
			break
		}

		// Relax vertex u
		for _, v := range g.vertices {
			if g.cost[u.id][v.id] == UNSET {
				continue
			}
			if minCost[v.id] == UNSET || minCost[u.id]+g.cost[u.id][v.id] < minCost[v.id] {
				minCost[v.id] = minCost[u.id] + g.cost[u.id][v.id]
				if via[start.id][u.id] == nil {
					via[start.id][v.id] = v
				} else {
					via[start.id][v.id] = via[start.id][u.id]
				}
			}
		}

		relaxed[u.id] = true
	}

	route := make([]*Route, 0)
	for _, v := range g.vertices {
		if via[start.id][v.id] == nil {
			continue
		}
		route = append(route, &Route{
			From: start.Name,
			To:   v.Name,
			Via:  via[start.id][v.id].Name,
			Cost: minCost[v.id],
		})
	}
	return route, nil
}

// Relax the graph end with "name".
// This method is routine-safe since the graph is read-only.
// REQUIRE: Init graph firstly.
func (g *Graph) RelaxEndWith(name string) ([]*Route, error) {
	var end *Vertex
	var ok bool
	if end, ok = g.name2vertex[name]; !ok {
		return nil, errors.New("there is no such vertex named " + name)
	}

	num := len(g.vertices)
	relaxed := make([]bool, num)
	for i := range relaxed {
		relaxed[i] = false
	}
	minCost := make([]int, num)
	for i := range minCost {
		minCost[i] = UNSET
	}
	via := make([][]*Vertex, num)
	for i := range via {
		via[i] = make([]*Vertex, num)
		for j := range via[i] {
			via[i][j] = nil
		}
	}

	// Dijkstra without heap optimization.
	minCost[end.id] = 0
	for {
		// Find a vertex to relax.
		var u *Vertex = nil
		for _, v := range g.vertices {
			if relaxed[v.id] {
				continue
			}
			if minCost[v.id] != UNSET && (u == nil || minCost[v.id] < minCost[u.id]) {
				u = v
			}
		}

		// There is no vertex to relax.
		if u == nil {
			break
		}

		// Relax vertex u
		for _, v := range g.vertices {
			if g.cost[v.id][u.id] == UNSET {
				continue
			}
			if minCost[v.id] == UNSET || minCost[u.id]+g.cost[v.id][u.id] < minCost[v.id] {
				minCost[v.id] = minCost[u.id] + g.cost[u.id][v.id]
				if via[u.id][end.id] == nil {
					via[v.id][end.id] = end
				} else {
					via[v.id][end.id] = u
				}
			}
		}

		relaxed[u.id] = true
	}

	route := make([]*Route, 0)
	for _, v := range g.vertices {
		if via[v.id][end.id] == nil {
			continue
		}
		route = append(route, &Route{
			From: v.Name,
			To:   end.Name,
			Via:  via[v.id][end.id].Name,
			Cost: minCost[v.id],
		})
	}
	return route, nil
}

func main() {
	g := NewGraph()
	var n, d int
	var a []int
	var x, y []int
	fmt.Scanf("%d%d", &n, &d)
	fmt.Scanf("\n")
	a = append(a, 0)
	for i := 1; i < n-1; i++ {
		var x int
		fmt.Scanf("%d", &x)
		a = append(a, x)
	}
	fmt.Scanf("\n")
	a = append(a, 0)
	for i := 0; i < n; i++ {
		var q, w int
		fmt.Scanf("%d%d\n", &q, &w)
		x = append(x, q)
		y = append(y, w)
		g.AddVertex(strconv.Itoa(i))
	}
	g.Init()

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			cost := (abs(x[i]-x[j])+abs(y[i]-y[j]))*d - a[j]
			g.AddEdge(strconv.Itoa(i), strconv.Itoa(j), cost)
		}
	}

	route, _ := g.RelaxEndWith(strconv.Itoa(n - 1))
	for _, r := range route {
		if r.From == "0" {
			fmt.Println(r.Cost)
			break
		}
	}
}

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

package main

import (
	"errors"
	"fmt"
	"strconv"
)

const (
	UNSET = -1
)

type Route struct {
	From *Vertex
	To   *Vertex
	Via  *Vertex
	Cost int
}

type Vertex struct {
	Name string
	id   int
}

type Graph struct {
	Vertices    []*Vertex
	cost        [][]int
	name2vertex map[string]*Vertex
}

// Construct a empty graph.
func NewGraph() *Graph {
	graph := new(Graph)
	graph.Vertices = make([]*Vertex, 0)
	graph.name2vertex = make(map[string]*Vertex)
	return graph
}

// Get pointer to vertex via name.
// An error is returned if there is no such vertex named "name".
func (g *Graph) GetVertex(name string) (*Vertex, error) {
	if v, ok := g.name2vertex[name]; ok {
		return v, nil
	} else {
		return nil, errors.New("No such vertex")
	}
}

// Add a vertex into graph.
// An error is returned if the vertex already exists.
func (g *Graph) AddVertex(name string) (*Vertex, error) {
	if v, ok := g.name2vertex[name]; !ok {
		v = &Vertex{
			id:   len(g.Vertices),
			Name: name,
		}
		g.Vertices = append(g.Vertices, v)
		g.name2vertex[name] = v
		return v, nil
	} else {
		return nil, errors.New(fmt.Sprintf("%s already exists", name))
	}
}

// Initialize graph after add Vertices.
// We need this method since we use adjacency matrix to implement the graph.
func (g *Graph) Init() {
	num := len(g.Vertices)
	g.cost = make([][]int, num)
	for i := range g.cost {
		g.cost[i] = make([]int, num)
		for j := range g.cost[i] {
			g.cost[i][j] = UNSET
		}
	}
}

// Make a snapshot
// REQUIRE: Init graph firstly.
func (g *Graph) Snapshot() *Graph {
	newGraph := NewGraph()
	newGraph.cost = make([][]int, len(g.Vertices))
	for i := range newGraph.cost {
		newGraph.cost[i] = make([]int, len(g.Vertices))
		for j := range newGraph.cost[i] {
			newGraph.cost[i][j] = g.cost[i][j]
		}
	}
	for k, v := range g.name2vertex {
		newV := &Vertex{
			id:   v.id,
			Name: v.Name,
		}
		newGraph.Vertices = append(newGraph.Vertices, newV)
		newGraph.name2vertex[k] = newV
	}
	return newGraph
}

// Add a edge into graph.
// The cost of edge will be overridden if there are multiple edges from "from" to "to".
// An error is returned if these Vertices are invalid or cost is negative.
// REQUIRE: Init graph firstly.
func (g *Graph) AddEdge(from *Vertex, to *Vertex, cost int) error {
	if from == nil || to == nil {
		return errors.New("*Vertex should not be nil")
	}
	if cost < 0 {
		return errors.New("cost should not be negative")
	}
	if from.id >= len(g.Vertices) || to.id >= len(g.Vertices) {
		return errors.New(fmt.Sprintf("%+v or %+v is invalid", *from, *to))
	}

	g.cost[from.id][to.id] = cost
	return nil
}

// Relax the graph from a certain vertex.
// This method is routine-safe since the graph is read-only.
// REQUIRE: Init graph firstly.
func (g *Graph) Relax(from *Vertex) []*Route {
	num := len(g.Vertices)
	relaxed := make([]bool, num)
	for i := range relaxed {
		relaxed[i] = false
	}
	minCost := make([]int, num)
	for i := range minCost {
		minCost[i] = UNSET
	}
	via := make([][]*Vertex, num)
	for i := range via {
		via[i] = make([]*Vertex, num)
		for j := range via[i] {
			via[i][j] = nil
		}
	}

	// Dijkstra without heap optimization.
	minCost[from.id] = 0
	for {
		// Find a vertex to relax.
		var u *Vertex = nil
		for _, v := range g.Vertices {
			if relaxed[v.id] {
				continue
			}
			if minCost[v.id] != UNSET && (u == nil || minCost[v.id] < minCost[u.id]) {
				u = v
			}
		}

		// There is no vertex to relax.
		if u == nil {
			break
		}

		// Relax vertex u
		for _, v := range g.Vertices {
			if g.cost[u.id][v.id] == UNSET {
				continue
			}
			if minCost[v.id] == UNSET || minCost[u.id]+g.cost[u.id][v.id] < minCost[v.id] {
				minCost[v.id] = minCost[u.id] + g.cost[u.id][v.id]
				if via[from.id][u.id] == nil {
					via[from.id][v.id] = v
				} else {
					via[from.id][v.id] = via[from.id][u.id]
				}
			}
		}

		relaxed[u.id] = true
	}

	route := make([]*Route, 0)
	for _, v := range g.Vertices {
		if via[from.id][v.id] == nil {
			continue
		}
		route = append(route, &Route{
			From: from,
			To:   v,
			Via:  via[from.id][v.id],
			Cost: minCost[v.id],
		})
	}
	return route
}

func main() {
	g := NewGraph()
	var n, d int
	var a []int
	var x, y []int
	fmt.Scanf("%d%d", &n, &d)
	a = append(a, 0)
	for i := 1; i < n-1; i++ {
		var x int
		fmt.Scanf("%d", &x)
		a = append(a, x)
	}
	a = append(a, 0)
	for i := 0; i < n; i++ {
		var q, w int
		fmt.Scanf("%d%d", &q, &w)
		x = append(x, q)
		y = append(y, w)
		g.AddVertex(strconv.Itoa(i))
	}
	g.Init()

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			u, _ := g.GetVertex(strconv.Itoa(i))
			v, _ := g.GetVertex(strconv.Itoa(j))

			cost := (abs(x[i]-x[j])+abs(y[i]-y[j]))*d - a[j]
			g.AddEdge(u, v, cost)
		}
	}

	v, _ := g.GetVertex("0")
	route := g.Relax(v)
	for _, r := range route {
		if r.To.Name == strconv.Itoa(n-1) {
			fmt.Println(r.Cost)
			break
		}
	}
}

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


Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $$$a$$$ minutes to feel refreshed.Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in $$$b$$$ minutes.Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than $$$a$$$ minutes in total, then he sets his alarm to go off in $$$c$$$ minutes after it is reset and spends $$$d$$$ minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another $$$c$$$ minutes and tries to fall asleep for $$$d$$$ minutes again.You just want to find out when will Polycarp get out of his bed or report that it will never happen.Please check out the notes for some explanations of the example.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The only line of each testcase contains four integers $$$a, b, c, d$$$ ($$$1 \le a, b, c, d \le 10^9$$$) — the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.

For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.

NoteIn the first testcase Polycarp wakes up after $$$3$$$ minutes. He only rested for $$$3$$$ minutes out of $$$10$$$ minutes he needed. So after that he sets his alarm to go off in $$$6$$$ minutes and spends $$$4$$$ minutes falling asleep. Thus, he rests for $$$2$$$ more minutes, totaling in $$$3+2=5$$$ minutes of sleep. Then he repeats the procedure three more times and ends up with $$$11$$$ minutes of sleep. Finally, he gets out of his bed. He spent $$$3$$$ minutes before the first alarm and then reset his alarm four times. The answer is $$$3+4 \cdot 6 = 27$$$.The second example is almost like the first one but Polycarp needs $$$11$$$ minutes of sleep instead of $$$10$$$. However, that changes nothing because he gets $$$11$$$ minutes with these alarm parameters anyway.In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is $$$b=9$$$.In the fourth testcase Polycarp wakes up after $$$5$$$ minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :(

// https://codeforces.com/contest/1355/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
var input io.Reader

func main() {
	var (
		T int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &T)
	for i := 0; i < T; i++ {
		fmt.Println(solver())
	}
}

func solver() int64 {
	var a, b, c, d int
	fmt.Fscan(input, &a, &b, &c, &d)
	if b >= a {
		return int64(b)
	}

	if d >= c {
		return -1
	}

	remain := a - b
	sleep := c - d
	steps := remain / sleep
	if remain % sleep > 0 {
		steps++
	}

	return int64(sleep + d) * int64(steps)	+ int64(b)
}

package main

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

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

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

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.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 (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

func main() {
	defer writer.Flush()

	T := reader.NextInt()
	for t:=0;t<T;t++ {
		a,b,c,d:=reader.NextInt64(),reader.NextInt64(),reader.NextInt64(),reader.NextInt64()
		solve(a,b,c,d)
	}
}

func solve(a,b,c,d int64){
	if(b>=a){
		writer.Printf("%d \n",b)
		return
	}
	if(d>=c){
		writer.Printf("-1 \n")
		return
	}
	times:=int64(0)
	// totalSleep:=b
	times=(a-b +c-d-1)/(c-d)
	// for totalSleep<a {
	// 	totalSleep= totalSleep+(c-d)
	// 	times++
	// }
	writer.Printf("%d \n",b+(times*c))
}

/*
URL:
https://codeforces.com/problemset/problem/1354/A
*/

package main

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

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

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

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

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

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

const (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

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

var (
	t          int
	a, b, c, d int64
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		a, b, c, d = ReadInt64_4()

		solve()
	}
}

func solve() {
	if b >= a {
		fmt.Println(b)
		return
	}

	if c-d <= 0 {
		fmt.Println(-1)
		return
	}

	n := Kiriage(a-b, c-d)
	fmt.Println(b + n*c)
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int64) int64 {
	return (a + (b - 1)) / b
}

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

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

var (
	// ReadString returns a WORD string.
	ReadString 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()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

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

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

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

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

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

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

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

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

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

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scan(&t)
	var answer = make([]int64, t)
	for i := 0; i < t; i++ {
		var a, b, c, d int64
		fmt.Scan(&a)
		fmt.Scan(&b)
		fmt.Scan(&c)
		fmt.Scan(&d)
		answer[i] = sleepCounter(a, b, c, d)
	}
	for _, ans := range answer {
		fmt.Println(ans)
	}
}

func sleepCounter(a, b, c, d int64) int64 {
	var totalTime int64 = b
	if a == b || a < b {
		return b
	}
	if c < d || c == d {
		return -1
	}
	var iterations int64
	if ((a - b) % (c - d)) == 0 {
		iterations = ((a - b) / (c - d))
	} else {
		iterations = ((a - b) / (c - d)) + 1
	}

	totalTime += (iterations * c)
	return totalTime
}

package main

import "fmt"
import "math"

func main() {
	var t, a, b, c, d, i, times int64

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

	for i = 0; i < t; i++ {
		fmt.Scanf("%d%d%d%d\n", &a, &b, &c, &d)

		if b >= a {
			fmt.Printf("%d\n", b)
			continue
		}
		if b < a {
			if c <= d {
				b = -1
				fmt.Printf("%d\n", b)
				continue
			}
			if c > d {
				times = int64(math.Ceil(float64(a-b)/float64(c-d)))
				fmt.Printf("%d\n", b + c*times)
				continue
			}
		}
	}
}

package main

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

func main() {
	for t := ScanInt(); t > 0; t-- {
		a, b, c, d := ScanInt(), ScanInt(), ScanInt(), ScanInt()
		P(solve(a, b, c, d))
	}
	//P(solve(5, 9, 4, 10))

	out.Flush()
}

func solve(a, b, c, d int) int64 {
	if a <= b {
		return int64(b)
	}
	if d >= c {
		return -1
	}

	a -= b
	sum := int64(b)
	sum += (int64(c) * int64(a/(c-d)))
	if (a % (c - d)) > 0 {
		sum += int64(c)
	}

	return sum
}

/*********************** I/O ***********************/
var in *bufio.Scanner
var out *bufio.Writer

func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)
	out = bufio.NewWriter(os.Stdout)
}

func P(args ...interface{}) {
	print("\n", args...)
}

func PS(args ...interface{}) {
	print(" ", args...)
	print("\n", nil)
}

func print(seperator string, args ...interface{}) {
	for _, arg := range args {
		str := ""
		switch v := arg.(type) {
		case byte:
			str = string(v)
		case rune:
			str = string(v)
		case int:
			str = strconv.Itoa(v)
		case int64:
			str = strconv.FormatInt(v, 10)
		case string:
			str = v
		}
		out.WriteString(str + seperator)
	}
}

func ScanWord() string { in.Scan(); return in.Text() }
func ScanWords(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanInt() int { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ScanInt()
	}
	return a
}

func MnMx(args ...int) (int, int) {
	minVal, maxVal := math.MaxInt32, math.MinInt32
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int) int { mn, _ := MnMx(args...); return mn }
func Mx(args ...int) int { _, mx := MnMx(args...); return mx }
func LCM(a, b int) int   { return a / GCD(a, b) * b }
func GCD(a, b int) int {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

package main

import "fmt"

func main() {
	var t int
	var rt, firstAlarm, subAlarm, tts int64

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		var res int64
		fmt.Scan(&rt, &firstAlarm, &subAlarm, &tts)

		if firstAlarm >= rt {
			fmt.Println(firstAlarm)
			continue
		}

		if tts >= subAlarm {
			fmt.Println(-1)
			continue
		}

		sleepLeft := rt - firstAlarm
		res = res + firstAlarm

		sleepTime := subAlarm - tts
		cycles := sleepLeft / sleepTime
		if sleepLeft%sleepTime != 0 {
			cycles = cycles + 1
		}

		fmt.Println(res + (cycles * subAlarm))
	}
}

package main

import(
	"fmt"
)

func solve(a int64, b int64, c int64, d int64) int64{
	if b >= a {
		return b
	}
	if d >= c{
		return -1
	}
	t := b
	a -= b
	step := c - d
	if step == 0 {
		return -1
	}
	 cnt := (a + step - 1)/step
	return t + cnt * c
}

func main(){
	var T int
	var a, b, c, d int64
	fmt.Scanf("%d\n", &T)
	for t := 0; t < T; t++{
		fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &d)
		fmt.Printf("%v\n", solve(a, b, c, d))
	}
}

package main

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

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

	var t int
	fmt.Fscan(r, &t)
	for i := 0; i < t; i++ {
		var a, b, c, d int64
		fmt.Fscan(r, &a, &b, &c, &d)
		if b >= a {
			fmt.Fprintln(w, b)
		} else if d >= c {
			fmt.Fprintln(w, -1)
		} else {
			x := (a - b) / (c - d)
			y := (a - b) % (c - d)
			if y > 0 {
				x++
			}
			fmt.Fprintln(w, b+(c*x))
		}
	}
}

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt64() int64
	NextUInt64() uint64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.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 (impl *wordScannerImpl) NextUInt64() uint64 {
	impl.Scan()
	bb := impl.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

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

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

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

const (
	INF = math.MaxInt64
	MOD = 1e9 + 7
)

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		a, b, c, d := reader.NextInt64(), reader.NextInt64(), reader.NextInt64(), reader.NextInt64()
		writer.Printf("%d\n", sol(a, b, c, d))
	}
}

func sol(a, b, c, d int64) int64 {
	if b >= a {
		return b
	}
	if d >= c {
		return -1
	}
	ret := b
	left := a - b
	diff := c - d
	if left%diff == 0 {
		ret += (c * left / diff)
	} else {
		ret += (c * (left/diff + 1))
	}
	return ret
}

package main

import (
	"fmt"
	"math"
)

func solve() {
	var a, b, c, d int64
	fmt.Scan(&a, &b, &c, &d)
	ans := b
	k := math.Max(float64(c-d), 0)
	if a <= ans {
		fmt.Println(ans)
	} else {
		if k == 0 {
			fmt.Println(-1)
		} else {
			t := int64((a - ans + int64(k) - 1) / int64(k))
			ans += t * c
			fmt.Println(ans)
		}
	}
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		var a, b, c, d int64
		fmt.Fscan(in, &a, &b, &c, &d)
		a -= b
		if a <= 0 {
			fmt.Fprintln(out, b)
			continue
		}
		dd := c - d
		if dd <= 0 {
			fmt.Fprintln(out, -1)
			continue
		}
		fmt.Fprintln(out, (a+dd-1)/dd*c+b)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := int64(1)
	fmt.Fscanf(in, "%d\n", &t)
	//fmt.Println("debug", t)
	for tt := int64(0); tt < t; tt++ {
		a, b, c, d := int64(0), int64(0), int64(0), int64(0)
		fmt.Fscanf(in, "%d %d %d %d\n", &a, &b, &c, &d)
		if b >= a {
			fmt.Fprintf(out, "%d\n", b)
		} else {
			if d >= c {
				fmt.Fprintf(out, "-1\n")
			} else {
				needRound := (a - b) / (c - d)
				needTime := needRound * c
				ans := b
				ans += needTime
				total := needRound*(c-d) + b
				stillNeed := a - total
				//fmt.Println(needRound, needTime, total, stillNeed)
				if stillNeed > 0 {
					ans += c
				}
				fmt.Fprintf(out, "%d\n", ans)
			}
		}
	}
	return
}

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

func same(s string, ss string) bool {
	a := make([]int, 26)
	for i := 0; i < len(s); i++ {
		b := int(s[i] - 'a')
		a[b]++
	}
	for i := 0; i < len(ss); i++ {
		b := int(ss[i] - 'a')
		a[b]--
		if a[b] == -1 {
			return false
		}
	}
	for i := 0; i < 26; i++ {
		if a[i] != 0 {
			return false
		}
	}
	return true
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	var answer = make([]int, t)
	for i := 0; i < t; i++ {
		var a, b, c, d int
		fmt.Scan(&a)
		fmt.Scan(&b)
		fmt.Scan(&c)
		fmt.Scan(&d)
		answer[i] = sleepCounter(a, b, c, d)
	}
	for _, ans := range answer {
		fmt.Println(ans)
	}
}

func sleepCounter(a, b, c, d int) int {
	var totalSleep int = b
	var totalTime int = b
	for totalSleep < a {
		totalTime += c
		if c < d {
			return -1
		}
		totalSleep += (c - d)
	}
	return totalTime
}

package main

import "fmt"

func main() {
	var t, a, b, c, d, sleep int

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

	for i := 0; i < t; i++ {
		fmt.Scanf("%d%d%d%d\n", &a, &b, &c, &d)

		if b >= a {
			fmt.Printf("%d\n", b)
			continue
		}
		if b < a {
			if c <= d {
				b = -1
				fmt.Printf("%d\n", b)
				continue
			}
			if c > d {
				sleep = b
				for sleep < a {
					sleep = sleep + (c - d)
					b = b + c
				}
				fmt.Printf("%d\n", b)
				continue
			}
		}
	}
}

package main

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

func main() {
	for t := ScanInt(); t > 0; t-- {
		a, b, c, d := ScanInt(), ScanInt(), ScanInt(), ScanInt()
		P(solve(a, b, c, d))
	}
	//P(solve(5, 9, 4, 10))

	out.Flush()
}

func solve(a, b, c, d int) int64 {
	if a <= b {
		return int64(b)
	}
	if d >= c {
		return -1
	}

	a -= b
	sum := int64(b)
	sum += int64(c*(a/(c-d)))
	if (a%(c-d)) > 0 {
		sum += int64(c)
	}

	return sum
}

/*********************** I/O ***********************/
var in *bufio.Scanner
var out *bufio.Writer

func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)
	out = bufio.NewWriter(os.Stdout)
}

func P(args ...interface{}) {
	print("\n", args...)
}

func PS(args ...interface{}) {
	print(" ", args...)
	print("\n", nil)
}

func print(seperator string, args ...interface{}) {
	for _, arg := range args {
		str := ""
		switch v := arg.(type) {
		case byte:
			str = string(v)
		case rune:
			str = string(v)
		case int:
			str = strconv.Itoa(v)
		case int64:
			str = strconv.FormatInt(v, 10)
		case string:
			str = v
		}
		out.WriteString(str + seperator)
	}
}

func ScanWord() string { in.Scan(); return in.Text() }
func ScanWords(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanInt() int { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ScanInt()
	}
	return a
}

func MnMx(args ...int) (int, int) {
	minVal, maxVal := math.MaxInt32, math.MinInt32
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int) int { mn, _ := MnMx(args...); return mn }
func Mx(args ...int) int { _, mx := MnMx(args...); return mx }
func LCM(a, b int) int   { return a / GCD(a, b) * b }
func GCD(a, b int) int {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

package main

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

func main() {
	for t := ScanInt(); t > 0; t-- {
		a, b, c, d := ScanInt(), ScanInt(), ScanInt(), ScanInt()
		P(solve(a, b, c, d))
	}
	//P(solve(5, 9, 4, 10))

	out.Flush()
}

func solve(a, b, c, d int) int {
	if a <= b {
		return b
	}
	if d >= c {
		return -1
	}

	a -= b
	sum := b
	for a > 0 {
		sum += (c)
		a -= (c - d)
	}
	return sum
}

/*********************** I/O ***********************/
var in *bufio.Scanner
var out *bufio.Writer

func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)
	out = bufio.NewWriter(os.Stdout)
}

func P(args ...interface{}) {
	print("\n", args...)
}

func PS(args ...interface{}) {
	print(" ", args...)
	print("\n", nil)
}

func print(seperator string, args ...interface{}) {
	for _, arg := range args {
		str := ""
		switch v := arg.(type) {
		case byte:
			str = string(v)
		case rune:
			str = string(v)
		case int:
			str = strconv.Itoa(v)
		case int64:
			str = strconv.FormatInt(v, 10)
		case string:
			str = v
		}
		out.WriteString(str + seperator)
	}
}

func ScanWord() string { in.Scan(); return in.Text() }
func ScanWords(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanInt() int { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ScanInt()
	}
	return a
}

func MnMx(args ...int) (int, int) {
	minVal, maxVal := math.MaxInt32, math.MinInt32
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int) int { mn, _ := MnMx(args...); return mn }
func Mx(args ...int) int { _, mx := MnMx(args...); return mx }
func LCM(a, b int) int   { return a / GCD(a, b) * b }
func GCD(a, b int) int {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

package main

import "fmt"

func main() {
	var t, rt, firstAlarm, subAlarm, tts int

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		res := 0
		fmt.Scan(&rt, &firstAlarm, &subAlarm, &tts)

		if firstAlarm >= rt {
			fmt.Println(firstAlarm)
			continue
		}

		if tts >= subAlarm {
			fmt.Println(-1)
			continue
		}

		sleepLeft := rt - firstAlarm
		res = res + firstAlarm

		sleepTime := subAlarm - tts
		cycles := sleepLeft / sleepTime
		if sleepLeft%sleepTime != 0 {
			cycles = cycles + 1
		}

		fmt.Println(res + (cycles * subAlarm))
	}
}

package main

import "fmt"

func main() {
	var t, rt, firstAlarm, subAlarm, tts, res int

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&rt, &firstAlarm, &subAlarm, &tts)

		if firstAlarm >= rt {
			fmt.Println(firstAlarm)
			continue
		}

		if tts >= subAlarm {
			fmt.Println(-1)
			continue
		}

		sleepLeft := rt - firstAlarm
		res = res + firstAlarm

		sleepTime := subAlarm - tts
		cycles := sleepLeft / sleepTime
		if sleepLeft%sleepTime != 0 {
			cycles = cycles + 1
		}

		fmt.Println(res + (cycles * subAlarm))
	}
}

package main

import "fmt"

func main() {
	var t, rt, firstAlarm, subAlarm, tts, res int

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&rt, &firstAlarm, &subAlarm, &tts)

		if firstAlarm >= rt {
			fmt.Println(firstAlarm)
			continue
		}

		if tts >= subAlarm {
			fmt.Println(-1)
			continue
		}

		sleepLeft := rt - firstAlarm
		res = res + firstAlarm

		sleepTime := subAlarm - tts
		cycles := sleepLeft / sleepTime
		if sleepLeft%sleepTime != 0 {
			cycles++
		}

		fmt.Println(res + (cycles * subAlarm))
	}
}

package main

import(
	"fmt"
)

func solve(a int, b int, c int, d int) int{
	if b >= a {
		return b
	}
	if d >= c{
		return -1
	}
	t := b
	a -= b
	step := c - d
	if step == 0 {
		return -1
	}
	 cnt := (a + step - 1)/step
	return t + cnt * c
}

func main(){
	var T int
	var a, b, c, d int
	fmt.Scanf("%d\n", &T)
	for t := 0; t < T; t++{
		fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &d)
		fmt.Printf("%v\n", solve(a, b, c, d))
	}
}

package main

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

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

	var t int
	fmt.Fscan(r, &t)
	for i := 0; i < t; i++ {
		var a, b, c, d int
		fmt.Fscan(r, &a, &b, &c, &d)
		if b >= a {
			fmt.Fprintln(w, b)
		} else if d >= c {
			fmt.Fprintln(w, -1)
		} else {
			n := b
			for b < a {
				n += c
				b += c - d
			}
			fmt.Fprintln(w, n)
		}
	}
}

package main

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

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

	var t int
	fmt.Fscan(r, &t)
	for i := 0; i < t; i++ {
		var a, b, c, d int
		fmt.Fscan(r, &a, &b, &c, &d)
		if b >= a {
			fmt.Fprintln(w, b)
		} else if d >= c {
			fmt.Fprintln(w, -1)
		} else {
			x := (a - b) / (c - d)
			y := (a - b) % (c - d)
			if y > 0 {
				x++
			}
			fmt.Fprintln(w, b+(c*x))
		}
	}
}