// Codeforces 1144 C compet
package main

import (
	"bufio"
	"fmt"
	"strings"
	"strconv"
	"os"
	"sort"
)
var in *bufio.Reader

func readFive() (int,int,int,int,int) {
	var a [5]int
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("first read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for i:=0; i<len(ss); i++ {
		a[i], err = strconv.Atoi(ss[i])
		if err != nil {
			fmt.Println("n atoi failure", err)
			panic(err)
		}
	}
	return a[0],a[1],a[2],a[3],a[4]
}

func readLineNumbs(n int) []int {
	a := make([]int, n)
	delim := byte(' ')
	for i:=0; i<n; i++ {
		if i==(n-1) {
			delim = byte('\n')
		}
		s, err := in.ReadString(delim)
		s = strings.Trim(s, " \n\r")
		if err != nil {
			fmt.Println("read failure", err)
			panic(err)
		}
		aa,err := strconv.Atoi(s)
		if err != nil {
			fmt.Println("aa conv failed", err)
			panic(err)
		}
		a[i] = aa
	}
	return a
}

func readString() string {
	delim := byte('\n')
	s, err := in.ReadString(delim)
	s = strings.Trim(s, " \n\r")
	if err != nil {
		fmt.Println("read failure", err)
		panic(err)
	}
	return s
}

var n int
var a []int
var inca []int
var deca []int
var canDo bool

func readData() {
	in = bufio.NewReader(os.Stdin)
	n,_,_,_,_ = readFive()
	a = readLineNumbs(n)
}

func solve() {
	sort.Ints(a)
	inca = make([]int, 0)
	deca = make([]int, 0)
	nsame := 0
	last := -1
	canDo = true
	addInc := true
	for i:=0; i<n; i++ {
		if a[i] == last {
			if nsame==2 {
				canDo = false
				return
			} else {
				if addInc {
					inca = append(inca, a[i])
				} else {
					deca = append(deca, a[i])
				}
				nsame=2
			}
		} else {
			if addInc {
				inca = append(inca, a[i])
			} else {
				deca = append(deca, a[i])
			}
			addInc = !addInc
			nsame = 1
			last = a[i]
		}
	}
	// reverse deca
	lda := len(deca)
	da := make([]int, lda)
	for i:=0; i<lda; i++ {
		da[i] = deca[lda - i - 1]
	}
	deca = da
}

func printRes() {
	if !canDo {
		fmt.Println("NO")
		return
	}
	fmt.Println("YES")
	fmt.Println(len(inca))
	for i:=0; i<len(inca); i++ {
		fmt.Print(inca[i]," ")
	}
	fmt.Println()
	fmt.Println(len(deca))
	for i:=0; i<len(deca); i++ {
		fmt.Print(deca[i]," ")
	}
	fmt.Println()
}

func main() {
	readData()
	solve()
	printRes()
}

package main

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

func main() {
	var n, flag, last int
	scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Fscanln(scr, &n)
	a := make([]int, n)
	i := make([]int, 0, n)
	d := make([]int, 0, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(scr, "%d", &a[i])
	}
	sort.Sort(sort.IntSlice(a))
	for x, y := range a {
		if x == 0 {
			last = y
			i = append(i, y)
		} else {
			if y > last {
				i = append(i, y)
			} else {
				d = append(d, y)
			}
			last = y
		}
	}
	for x, y := range d {
		if x == 0 {
			last = y
		} else {
			if y <= last {
				flag = 2
				break
			}
			last = y
		}
	}
	if flag == 2 {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")

		fmt.Println(len(i))
		for _, y := range i {
			fmt.Printf("%d ", y)
		}
		fmt.Printf("\n")

		fmt.Println(len(d))
		for i := len(d) - 1; i >= 0; i-- {
			fmt.Printf("%d ", d[i])
		}
	}

}

package main

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

var scanner *bufio.Scanner
var writer *bufio.Writer

func toInt(buf []byte) (n int) {
    for _, v := range buf {
        n = n*10 + int(v-'0')
    }
    return
}

func nextInt() int {
    scanner.Scan()
    return toInt(scanner.Bytes())
}

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

    N := nextInt()
    arr := []int{}
    for i := 0; i < N; i++ {
        x := nextInt()
        arr = append(arr, x)
    }
    sort.Ints(arr)
    aneh := []int{}
    invalid := false
    for i := 1; i < N; i++ {
        if arr[i] == arr[i-1] {
            if len(aneh) > 0 && aneh[len(aneh)-1] == arr[i] {
                invalid = true
                break
            } else {
                aneh = append(aneh, arr[i])
            }
        }
    }
    if invalid {
        writer.WriteString("NO")
    } else {
        writer.WriteString("YES\n")
        writer.WriteString(strconv.Itoa(N - len(aneh)) + "\n")
        writer.WriteString(strconv.Itoa(arr[0]))
        for i := 1; i < N; i++ {
            if arr[i] != arr[i-1] {
                writer.WriteRune(' ')
                writer.WriteString(strconv.Itoa(arr[i]));
            }
        }
        writer.WriteRune('\n')
        writer.WriteString(strconv.Itoa(len(aneh)) + "\n")
        for i := len(aneh)-1; i >= 0; i-- {
            writer.WriteString(strconv.Itoa(aneh[i]))
            writer.WriteRune(' ')
        }
        writer.WriteRune('\n')
    }
    writer.Flush()
}

package main

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

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

    scanner.Scan()
    N := toInt(scanner.Bytes())
    arr := []int{}
    for i := 0; i < N; i++ {
        scanner.Scan()
        x := toInt(scanner.Bytes())
        arr = append(arr, x)
    }
    sort.Ints(arr)
    aneh := []int{}
    invalid := false
    for i := 1; i < N; i++ {
        if arr[i] == arr[i-1] {
            if len(aneh) > 0 && aneh[len(aneh)-1] == arr[i] {
                invalid = true
                break
            } else {
                aneh = append(aneh, arr[i])
            }
        }
    }
    if invalid {
        writer.WriteString("NO")
    } else {
        writer.WriteString("YES\n")
        writer.WriteString(strconv.Itoa(N - len(aneh)) + "\n")
        writer.WriteString(strconv.Itoa(arr[0]))
        for i := 1; i < N; i++ {
            if arr[i] != arr[i-1] {
                writer.WriteRune(' ')
                writer.WriteString(strconv.Itoa(arr[i]));
            }
        }
        writer.WriteRune('\n')
        writer.WriteString(strconv.Itoa(len(aneh)) + "\n")
        for i := len(aneh)-1; i >= 0; i-- {
            writer.WriteString(strconv.Itoa(aneh[i]))
            writer.WriteRune(' ')
        }
        writer.WriteRune('\n')
    }
    writer.Flush()
}

func toInt(buf []byte) (n int) {
    for _, v := range buf {
        n = n*10 + int(v-'0')
    }
    return
}

package main

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

func main()  {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var n int
	fmt.Fscanln(in,&n)
	a := make([]int,n,n)
	for i := 0 ;i  < n;i ++{
		fmt.Fscan(in,&a[i])
	}
	m := map[int]int{}
	inc := make([]int,0)
	dec := make([]int,0)
	sort.Ints(a)
	ans := false
	for i := 0 ; i< n;i++{
		m[a[i]]++
		if(m[a[i]] == 1){
			inc = append(inc,a[i])
		}
		if m[a[i]] == 2{
			dec = append(dec,a[i])
		}
		if(m[a[i]] >= 3){
			ans = true
		}
	}
	if(ans){
		fmt.Fprintf(out,"%s","NO")
		return
	}

	fmt.Fprintf(out,"%s\n","YES")
	fmt.Fprintln(out,len(inc))
	for _,val := range inc{
		fmt.Fprint(out,val," ")
	}
	fmt.Fprintln(out)
	fmt.Fprintln(out,len(dec))
	for i := len(dec) - 1 ; i >= 0;i--{
		fmt.Fprint(out,dec[i]," ")
	}

}

package main

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

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 getLine() string {
	s, _ := reader.ReadString('\n')
	for len(s) > 0 && (s[len(s)-1] == '\n' || s[len(s)-1] == '\r') {
		s = s[:len(s)-1]
	}
	return s
}

func main() {
	// STDOUT MUST BE FLUSHED MANUALLY!!!
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	var input []int
	for ; n >= 1; n-- {
		var a int
		scanf("%d", &a)
		input = append(input, a)
	}
	sort.Ints(input)
	status := 1
	var inc = input[:1]
	var inc2 []int
	check := true
	for i := 1; i < len(input) && check; i++ {
		switch status {
		case 1:
			if input[i] == input[i-1] {
				status = 2
				inc2 = append(inc2, input[i])
			} else {
				inc = append(inc, input[i])
			}
		case 2:
			if input[i] == input[i-1] {
				check = false
			} else {
				inc = append(inc, input[i])
				status = 1
			}
		}
	}
	if check {
		printf("YES\n")
		printf("%d\n", len(inc))
		if len(inc) > 0 {
			printf("%d", inc[0])
		}
		for i := 1; i < len(inc); i++ {
			printf(" %d", inc[i])
		}
		printf("\n")
		printf("%d\n", len(inc2))
		if len(inc2) > 0 {
			printf("%d", inc2[len(inc2)-1])
		}
		for i := len(inc2) - 2; i >= 0; i-- {
			printf(" %d", inc2[i])
		}
		printf("\n")
	} else {
		printf("NO\n")
	}
}

package main

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

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

	var n int
	fmt.Fscanln(in, &n)

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

	inc := make([]int, 0)
	dec := make([]int, 0)

	sort.Ints(a)

	fail := false
	times := make(map[int]int)
	for _, val := range a {
		if times[val] == 0 {
			inc = append(inc, val)
		} else if times[val] == 1 {
			dec = append(dec, val)
		} else {
			fail = true
			break
		}
		times[val] += 1
	}

	if fail {
		fmt.Fprintln(out, "NO")
	} else {
		fmt.Fprintln(out, "YES")
		fmt.Fprintln(out, len(inc))
		for _, val := range inc {
			fmt.Fprint(out, val, " ")
		}
		fmt.Fprintln(out)
		fmt.Fprintln(out, len(dec))
		for i := len(dec) - 1; i >= 0; i-- {
			fmt.Fprint(out, dec[i], " ")
		}
		fmt.Fprintln(out)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanln(in, &n)

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

	inc := make([]int, 0)
	dec := make([]int, 0)

	sort.Ints(a)

	fail := false
	times := make(map[int]int)
	for _, val := range a {
		if times[val] == 0 {
			inc = append(inc, val)
		} else if times[val] == 1 {
			dec = append(dec, val)
		} else {
			fail = true
			break
		}
		times[val] += 1
	}

	if fail {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")
		fmt.Println(len(inc))
		for _, val := range inc {
			fmt.Print(val, " ")
		}
		fmt.Println()
		fmt.Println(len(dec))
		for i := len(dec) - 1; i >= 0; i-- {
			fmt.Print(dec[i], " ")
		}
		fmt.Println()
	}
}

package main

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

type mark struct {
	number int
	cnt int
}

func main()  {
	in := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanln(in, &n)
	data := make([]int, n , n)
	for i := 0 ;i < n ; i++ {
		fmt.Fscan(in, &data[i])
	}
	sort.Ints(data)
	m := mark {number:-1, cnt:0}
	one := make([]int, 0, n)
	two := make([]int, 0, n)
	for _, v := range data {
		if m.number == v{
			m.cnt ++
			if m.cnt > 2 {
				fmt.Println("NO")
				return
			}
			two = append(two, v)
 		} else {
 			one = append(one, v)
 			m.cnt  = 1
 			m.number = v
		}
	}
	fmt.Println("YES")

	fmt.Println(len(one))
	for _, v :=  range one {
		fmt.Printf("%d ", v)
	}
	fmt.Println()
	fmt.Println(len(two))
	for i := len(two) - 1; i >= 0; i -- {
		fmt.Printf("%d ", two[i])
	}
	fmt.Println()
}

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

package main

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

type Solution struct {
	Exists    bool
	Inc       []int
	IncLength int
	Dec       []int
	DecLength int
}

func reverse(a []int, n int) []int {
	for i := 0; i < n/2; i++ {
		a[i], a[n-i-1] = a[n-i-1], a[i]
	}
	return a
}

func printArray(writer *bufio.Writer, a []int, n int) {
	for i := 0; i < n; i++ {
		fmt.Fprintf(writer, "%d ", a[i])
	}
	fmt.Fprintf(writer, "\n")
}

func Solve(n int, a []int) Solution {
	sort.Ints(a)
	inc, incLength := []int{}, 0
	dec, decLength := []int{}, 0
	for i := 0; i < n; i++ {
		if incLength == 0 {
			inc = append(inc, a[i])
			incLength += 1
		} else if a[i] > inc[incLength-1] {
			inc = append(inc, a[i])
			incLength += 1
		} else if decLength == 0 {
			dec = append(dec, a[i])
			decLength += 1
		} else if a[i] > dec[decLength-1] {
			dec = append(dec, a[i])
			decLength += 1
		} else {
			return Solution{Exists: false}
		}
	}
	return Solution{
		Exists:    true,
		Inc:       inc,
		IncLength: incLength,
		Dec:       reverse(dec, decLength),
		DecLength: decLength,
	}
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &a[i])
	}
	fmt.Fscanf(reader, "\n")

	solution := Solve(n, a)
	if !solution.Exists {
		fmt.Fprintf(writer, "NO\n")
	} else {
		fmt.Fprintf(writer, "YES\n")
		fmt.Fprintf(writer, "%d\n", solution.IncLength)
		printArray(writer, solution.Inc, solution.IncLength)
		fmt.Fprintf(writer, "%d\n", solution.DecLength)
		printArray(writer, solution.Dec, solution.DecLength)
	}
}

package main

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

func main() {
	var n, flag, last int
	scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Fscanln(scr, &n)
	a := make([]int, n)
	i := make([]int, 0, n)
	d := make([]int, 0, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(scr, "%d", &a[i])
	}
	sort.Sort(sort.IntSlice(a))
	for x, y := range a {
		if x == 0 {
			last = y
			i = append(i, y)
		} else {
			if y > last {
				i = append(i, y)
			} else {
				d = append(d, y)
			}
			last = y
		}
	}
	for x, y := range d {
		if x == 0 {
			last = y
		} else {
			if y <= last {
				flag = 2
				break
			}
		}
	}
	if flag == 2 {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")

		fmt.Println(len(i))
		for _, y := range i {
			fmt.Printf("%d ", y)
		}
		fmt.Printf("\n")

		fmt.Println(len(d))
		for i := len(d) - 1; i >= 0; i-- {
			fmt.Printf("%d ", d[i])
		}
	}

}

package main

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

func main() {
	var n, flag, last int
	scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Fscanln(scr, &n)
	a := make([]int, n)
	i := make([]int, 0, n)
	d := make([]int, 0, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(scr, "%d", &a[i])
	}
	sort.Sort(sort.IntSlice(a))
	for x, y := range a {
		if x == 0 {
			last = y
			i = append(i, y)
		} else {
			if y > last {
				i = append(i, y)
			} else {
				d = append(d, y)
			}
			last = y
		}
	}
	for x, y := range d {
		if x == 0 {
			last = y
		} else {
			if y <= last {
				flag = 2
				break
			}
		}
	}
	if flag == 2 {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")

		fmt.Println(len(d))
		for _, y := range d {
			fmt.Printf("%d ", y)
		}
		fmt.Printf("\n")

		fmt.Println(len(i))
		for j := len(i) - 1; j >= 0; j-- {
			fmt.Printf("%d ", i[j])
		}
	}

}

package main

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

func main() {
	var n, flag, last int
	scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Fscanln(scr, &n)
	a := make([]int, n)
	i := make([]int, 0, n)
	d := make([]int, 0, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(scr, "%d", &a[i])
	}
	sort.Sort(sort.IntSlice(a))
	for x, y := range a {
		if x == 0 {
			last = y
			i = append(i, y)
		} else {
			if y > last {
				i = append(i, y)
			} else {
				d = append(d, y)
			}
			last = y
		}
	}
	for x, y := range d {
		if x == 0 {
			last = y
		} else {
			if y < last {
				flag = 2
				break
			}
		}
	}
	if flag == 2 {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")

		fmt.Println(len(i))
		for _, y := range i {
			fmt.Printf("%d ", y)
		}
		fmt.Printf("\n")

		fmt.Println(len(d))
		for i := len(d) - 1; i >= 0; i-- {
			fmt.Printf("%d ", d[i])
		}
	}

}

package main

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

func main()  {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var n int
	fmt.Fscanln(in,&n)
	a := make([]int,n,n)
	m := map[int]int{}
	ans := false
	for i := 0 ; i< n;i++{
		fmt.Fscan(in,&a[i])
		m[a[i]]++
		if(m[a[i]] >= 3){
			ans = true
		}
	}
	if(ans){
		fmt.Fprintf(out,"%s","NO")
		return
	}
	b := make([]int,n)
	B := []int{}
	cnt := 0
	for i := 0 ; i < n ;i++{
		if(m[a[i]] >= 2){
			cnt ++
			b = append(b,a[i])
			B = append(B,a[i])
			m[a[i]] --
			a[i] = -1
		}
	}
	sort.Ints(B)
	sort.Ints(a)
	fmt.Fprintf(out,"%s\n","YES")
	fmt.Fprintf(out,"%d\n",len(B))
	for _,i :=range B{
		fmt.Fprintf(out,"%d ",i)
	}
	fmt.Println()
	fmt.Fprintf(out,"%d\n",n - len(B))
	for i := n - 1 ; i >= 0;i--{
		if(a[i] >= 0){
			fmt.Fprintf(out,"%d ",a[i])
		}
	}

}

package main

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

func main()  {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var n int
	fmt.Fscanf(in,"%d\n",&n)
	a := make([]int,n,n)
	m := map[int]int{}
	ans := false
	for i := 0 ; i< n;i++{
		fmt.Fscanf(in,"%d\n",&a[i])
		m[a[i]]++
		if(m[a[i]] >= 3){
			ans = true
		}
	}
	if(ans){
		fmt.Println("NO")
		return
	}
	b := make([]int,n)
	B := []int{}
	cnt := 0
	for i := 0 ; i < n ;i++{
		if(m[a[i]] >= 2){
			cnt ++
			b = append(b,a[i])
			B = append(B,a[i])
			m[a[i]] --
			a[i] = -1
		}
	}
	sort.Ints(B)
	sort.Ints(a)
	fmt.Println("YES")
	fmt.Println(len(B))
	for _,i :=range B{
		fmt.Print(i," ")
	}
	fmt.Println()
	fmt.Println(n - len(B))
	for i := n - 1 ; i >= 0;i--{
		if(a[i] >= 0){
			fmt.Print(a[i]," ")
		}
	}

}

package main

import (
	"fmt"
	"sort"
)

type mark struct {
	number int
	cnt int
}

func main()  {
	var n int
	fmt.Scan(&n)
	data := make([]int, n , n)
	for i := 0 ;i < n ; i++ {
		fmt.Scan(&data[i])
	}
	sort.Ints(data)
	m := mark {number:-1, cnt:0}
	one := make([]int, 0, n)
	two := make([]int, 0, n/2 + 2)
	for i := 0 ; i < n ; i ++ {
		if m.number == data[i] {
			m.cnt ++
			if m.cnt > 2 {
				fmt.Println("NO")
				return
			}
			two = append(two, data[i])
 		} else {
 			one = append(one, data[i])
 			m.cnt  = 1
 			m.number = data[i]
		}
	}
	fmt.Println("YES")

	fmt.Println(len(one))
	for _, v :=  range one {
		fmt.Printf("%d ", v)
	}
	fmt.Println()

	fmt.Println(len(two))
	for i := len(two) - 1; i >= 0; i -- {
		fmt.Printf("%d ", data[i])
	}
	fmt.Println()

}


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


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


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

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

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