package main

import(
	"fmt"
)

func main(){
	var n int
	fmt.Scanf("%d", &n)
	arr := make([]int64, n)
	for i := 0; i < n; i++{
		fmt.Scan(&arr[i])
		sum := (1 + arr[i])*arr[i]/2
		var b, j int64 = 0, 1
		for b = arr[i]; b > 1; b >>= 1{
			j = j << 1 +1
		}
		arr[i] = sum - 2*j
	}
	for _, m := range arr{
		fmt.Printf("%d\n", m)
	}
}

package main

import (
    "fmt"
    "math"
)

var pows []int64

func main() {
    var t int
    fmt.Scanln(&t)

    ns := make([]int64, t)

    for i := range ns {
        fmt.Scanln(&ns[i])
    }

    max := maxInSlice(ns)

    pows = make([]int64, maxLog(max) + 1)

    pows[0] = int64(1)

    for i := 1; i < len(pows); i++ {
        pows[i] = pows[i - 1] + int64(math.Pow(2.0, float64(i)))
    }

    for _, n := range ns {
        fmt.Println(sumNegPows(n))
    }
}

func maxInSlice(arr []int64) int64 {
    max := arr[0]

    for _, v := range arr {
        if v > max {
            max = v
        }
    }

    return max
}

func maxLog(x int64) int64 {
    return int64(math.Floor(math.Log2(float64(x))))
}

func sumNegPows(n int64) int64 {
    var sum int64

    if n % 2 == 0 {
        sum = int64((1 + n) * (n / 2))
    } else {
        sum = int64(n * ((n - 1) / 2) + n)
    }

    sum += int64(-2 * pows[maxLog(n)])

    return sum
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var i, n int
	fmt.Scanf("%d\n", &i)
	for j := 0; j < i; j++ {
		fmt.Scanf("%d\n", &n)
		solve(n)
	}
}

func solve(m int) error {
	n := int64(m)
	var total int64 = n * (n + 1) / 2
	maxPower := math.Floor(math.Log2(float64(n)))
	dd := 2 * (math.Pow(2, maxPower+1) - 1)
	fmt.Printf("%d\n", total-int64(dd))
	return nil

}

package main

import "fmt"

func main() {
	var l uint
	var a,b,n,r int64
	var i int

	fmt.Scanln(&i)
	for i>0 {
		fmt.Scanln(&n)
		a=n*(n+1)/2
		l=0
		for n >= 1<<l { l++ }
		b=^(^0<<l)
		r=a-b-b
		fmt.Println(r)
		i--
	}
}

package main

import "fmt"
import "strconv"

func calc(n int64) string {
  var f int64 = n * (n + 1) / 2
  var i int64 = 1
  for i <= n {
    f = f - 2 * i
    i = i * 2
  }
  return strconv.FormatInt(f, 10)
}

func main() {
  var n int64
  fmt.Scan(&n)
  for i := int64(0); i < n; i++ {
    var k int64
    fmt.Scan(&k)
    fmt.Println(calc(k))
  }
}

// Test1 project Test1.go
package main

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

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

func scan(a ...interface{}) {
    fmt.Fscan(reader, a...)
}

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

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

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

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

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

func main() {
    for t := nextInt(); t > 0; t-- {
        n := nextInt64()
        sum := (1 + n) * n / 2
        for pow2 := int64(1); pow2 <= n; pow2 = pow2 << 1 {
            sum -= pow2 * 2
        }
        fmt.Println(sum)
    }
}

package main

import (
    "fmt"
)

func main() {
    t, n := 0, int64(0)
    for fmt.Scan(&t); t > 0; t-- {
        fmt.Scan(&n)
        sum := n*(n+1)/2
        for i := int64(1); i <= n; i <<= 1 {
            sum -= 2*i
        }
        fmt.Println(sum)
    }
}

// -*- mode:go;mode:go-playground -*-
// snippet of code @ 2015-11-18 09:43:58
//
// run snippet with Ctl-Return

package main

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

func sumTwoPowers(n int64) int64 {
	max := int64(1)

	for max <= n {
		max *= 2
	}
	return max - 1
}

func sumAll(n int64) int64 {
	return n * (1 + n) / 2
}

func trickySum(n int64) int64 {
	allsum := sumAll(n)
	twosum := sumTwoPowers(n)
	return allsum - 2*twosum
}

/*
等比数列求和
a1(1-q^n)
----------
1-q

1 (1 - 2^n)
----------- = 2^n - 1
1 - 2

1 2 4

2 ^ 3 - 1
*/

//1 2 3 4

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	lines, _ := strconv.Atoi(scanner.Text())

	for i := 0; i < lines; i++ {
		scanner.Scan()
		n, _ := strconv.ParseInt(scanner.Text(), 10, 64)
		fmt.Println(trickySum(n))
	}
}

package main

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

func calc(n int64, ws *bufio.Writer, before, next chan bool) {
	tot := (n*(n+1))/2
	ch := make(chan int64, 100)

	go func(){
		for i := int64(1); i <= n; i *= 2 {
			ch <- i*2
		}
		close(ch)
	}()

	for x := range ch{
		tot -= x
	}
	a := <-before
	ws.WriteString(fmt.Sprintln(tot))
	next <- a
}

func main(){
	rs := bufio.NewReader(os.Stdin)
	ws := bufio.NewWriter(os.Stdout)

	input, _ := rs.ReadString('\n')
	t, _ := strconv.ParseUint(strings.TrimSpace(input), 10, 64)

	first := make(chan bool)

	oldFirst := first

	for i := uint64(0); i < t; i++ {
		input, _ := rs.ReadString('\n')
		n, _ := strconv.ParseInt(strings.TrimSpace(input), 10, 64)
		second := make(chan bool)
		go calc(n, ws,first, second)
		first = second
	}

	oldFirst <- true
	<-first

	ws.Flush()
}

package main

import(
  "fmt"
)

func main() {
    var t int
    fmt.Scanln(&t)
    var n int64
    var sub int64 = 0
    var j int64 = 1
    for i := 0; i < t; i++ {

        fmt.Scanln(&n)

        sub = 0
        j = 1

        for ; j <= n; j*=2 {
            sub += j
        }

        var sum int64 = n*(n+1)/2 - 2*sub
        fmt.Println(sum)
    }
}

package main

import (
	"fmt"
)

var ps = fmt.Printf
var ss = fmt.Scanf

const mod int = 1000000007

func main() {
	t, n := 0, 0
	ss("%d\n", &t)
	for t > 0 {
		ss("%d\n", &n)
		var sum int64 = int64(n) * int64(n+1)
		sum /= 2
		var sum2, j int64 = 0, 1
		for j <= int64(n) {
			sum2 += j * 2
			j = j * 2
		}
		ps("%d\n", sum-sum2)
		t = t - 1
	}
}

package main

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

type Scanner struct {
	r            io.Reader
	split        bufio.SplitFunc
	maxTokenSize int
	token, buf   []byte
	start, end   int
}

func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        bufio.ScanWords,
		maxTokenSize: 16777216,
		buf:          make([]byte, 4096),
	}
}

func (s *Scanner) advance(n int) bool {
	if n < 0 || n > s.end-s.start {
		return false
	}
	s.start += n
	return true
}

func (s *Scanner) Text() string {
	return string(s.token)
}

func (s *Scanner) Scan() bool {
	for {
		if s.end > s.start {
			advance, token, err := s.split(s.buf[s.start:s.end], false)
			if err != nil || !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				return true
			}
		}
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		if s.end == len(s.buf) {
			if len(s.buf) >= s.maxTokenSize {
				return false
			}
			newSize := len(s.buf) * 2
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		for loop := 0; ; {
			n, _ := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if n > 0 {
				break
			}
			loop++
			if loop > 100 {
				break
			}
		}
	}
}

func (s *Scanner) Split(split bufio.SplitFunc) {
	s.split = split
}

var w *bufio.Writer = bufio.NewWriter(os.Stdout)
var sc *Scanner = NewScanner(os.Stdin)

func next() string { sc.Scan(); return sc.Text() }

func ni32() int {
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	return n
}

func ni64() int64 {
	sc.Scan()
	n, _ := strconv.ParseInt(sc.Text(), 10, 64)
	return n
}

func pri32(i ...int) {
	for _, ii := range i {
		w.WriteString(strconv.Itoa(ii))
		sp()
	}
}
func pri64(i ...int64) {
	for _, ii := range i {
		w.WriteString(strconv.FormatInt(ii, 10))
		sp()
	}
}
func sp()   { w.WriteByte(' ') }
func endl() { w.WriteByte('\n') }

func Sum(n int64) (result int64) {

	var i uint64
	result = (n*(n+1))/2
	for n > 0 {

		i += 1
		n >>= 1

	}

	result = result - ((1<<i)-1)<<1
	return
}

func SumFinal(slice []int64) []int64 {

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

		slice[i] = Sum(slice[i])

	}
	return slice

}

func main() {
	defer w.Flush()
	var t int64 = ni64()
	var x int64
	var i int64
	slice := make([]int64, t)
	for i = 0; i < t; i++ {
		x = ni64()
		slice[i] = x
	}

	pri64(SumFinal(slice)...)
	endl()
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)

func init() {
	scanner.Split(bufio.ScanWords)
}

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

func scanInt64() int64 {
	scanner.Scan()
	v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return v
}

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

func scanInts(n int) []int {
	l := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		l[i], _ = strconv.Atoi(scanner.Text())
	}

	return l
}

func scanInts64(n int64) []int64 {
	l := make([]int64, n)
	for i := int64(0); i < n; i++ {
		scanner.Scan()
		l[i], _ = strconv.ParseInt(scanner.Text(), 10, 64)
	}

	return l
}

func scanBool() bool {
	scanner.Scan()
	v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return v == 1
}

func scanBools(n int64) []bool {
	l := make([]bool, n)
	for i := int64(0); i < n; i++ {
		scanner.Scan()
		v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
		l[i] = v == 1
	}

	return l
}

func main() {
	t := scanInt()

	for i := 0; i < t; i++ {
		n := scanInt64()
		fmt.Println(sum(n))
	}
}

func sum(n int64) int64 {
	s := n * (1 + n) / 2

	for i := int64(1); i <= n; i *= 2 {
		s -= i * 2
	}

	return s
}

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

	return -a
}

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

	return b
}

package main

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

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

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

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

func Sum(n int) (result int) {

	i:=1
	result = (n*(n+1))/2
	for i<=n {

		result = result - i*2
		i = i << 1

	}
	return
}

func SumFinal(slice []int) []int {

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

		slice[i] = Sum(slice[i])

	}
	return slice

}

func main() {
	defer writer.Flush()
	var t int = ReadInt32()
	var x int
	slice := make([]int, t)
	for i := 0; i < t; i++ {
		x = ReadInt32()
		slice[i] = x
	}
	PrintInts(SumFinal(slice)...)
}

package main

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

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

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

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

func Sum(n int) (result int) {

	i:=1
	result = (n*(n+1))/2
	for i<=n {

		result = result - i*2
		i = i << 1

	}
	return
}

func SumFinal(slice []int) []int {

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

		slice[i] = Sum(slice[i])

	}
	return slice

}

func main() {
	defer writer.Flush()
	var t int = ReadInt32()
	var x int
	slice := make([]int, t)
	for i := 0; i < t; i++ {
		x = ReadInt32()
		slice[i] = x
	}
	writer.WriteByte('\n')
	PrintInts(SumFinal(slice)...)
}

package main

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

type Scanner struct {
	r            io.Reader
	split        bufio.SplitFunc
	maxTokenSize int
	token, buf   []byte
	start, end   int
}

func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        bufio.ScanWords,
		maxTokenSize: 16777216,
		buf:          make([]byte, 4096),
	}
}

func (s *Scanner) advance(n int) bool {
	if n < 0 || n > s.end-s.start {
		return false
	}
	s.start += n
	return true
}

func (s *Scanner) Text() string {
	return string(s.token)
}

func (s *Scanner) Scan() bool {
	for {
		if s.end > s.start {
			advance, token, err := s.split(s.buf[s.start:s.end], false)
			if err != nil || !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				return true
			}
		}
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		if s.end == len(s.buf) {
			if len(s.buf) >= s.maxTokenSize {
				return false
			}
			newSize := len(s.buf) * 2
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		for loop := 0; ; {
			n, _ := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if n > 0 {
				break
			}
			loop++
			if loop > 100 {
				break
			}
		}
	}
}

func (s *Scanner) Split(split bufio.SplitFunc) {
	s.split = split
}

var w *bufio.Writer = bufio.NewWriter(os.Stdout)
var sc *Scanner = NewScanner(os.Stdin)

func next() string { sc.Scan(); return sc.Text() }

func ni32() int {
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	return n
}

func ni64() int64 {
	sc.Scan()
	n, _ := strconv.ParseInt(sc.Text(), 10, 64)
	return n
}

func pri32(i ...int) {
	for _, ii := range i {
		w.WriteString(strconv.Itoa(ii))
		sp()
	}
}
func pri64(i ...int64) {
	for _, ii := range i {
		w.WriteString(strconv.FormatInt(ii, 10))
		sp()
	}
}
func sp()   { w.WriteByte(' ') }
func endl() { w.WriteByte('\n') }

func Sum(n int) (result int) {

	i:=1
	result = (n*(n+1))/2
	for i<=n {

		result = result - i*2
		i = i << 1

	}
	return
}

func SumFinal(slice []int) []int {

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

		slice[i] = Sum(slice[i])

	}
	return slice

}

func main() {
	defer w.Flush()
	var t int = ni32()
	var x int
	slice := make([]int, t)
	for i := 0; i < t; i++ {
		x = ni32()
		slice[i] = x
	}
	pri32(SumFinal(slice)...)
	endl()
}

package main

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

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

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

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

func Sum(n int) (result int) {

	i:=1
	result = (n*(n+1))/2
	for i<=n {

		result = result - i*2
		i = i << 1

	}
	return
}

func SumFinal(slice []int) []int {

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

		slice[i] = Sum(slice[i])

	}
	return slice

}

func main() {
	var t int = ReadInt32()
	var x int
	slice := make([]int, t)
	for i := 0; i < t; i++ {
		x = ReadInt32()
		slice[i] = x
	}
	PrintInts(SumFinal(slice)...)
}

package main

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

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

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

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

func Sum(n int) (result int) {

	i:=1
	result = (n*(n+1))/2
	for i<=n {

		result = result - i*2
		i = i << 1

	}
	return
}

func SumFinal(slice []int) []int {

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

		slice[i] = Sum(slice[i])

	}
	return slice

}

func main() {
	defer writer.Flush()
	var t int = ReadInt32()
	var x int
	slice := make([]int, t)
	for i := 0; i < t; i++ {
		x = ReadInt32()
		slice[i] = x
	}
	PrintInts(SumFinal(slice)...)
}

package main

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

type Scanner struct {
	r            io.Reader
	split        bufio.SplitFunc
	maxTokenSize int
	token, buf   []byte
	start, end   int
}

func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        bufio.ScanWords,
		maxTokenSize: 16777216,
		buf:          make([]byte, 4096),
	}
}

func (s *Scanner) advance(n int) bool {
	if n < 0 || n > s.end-s.start {
		return false
	}
	s.start += n
	return true
}

func (s *Scanner) Text() string {
	return string(s.token)
}

func (s *Scanner) Scan() bool {
	for {
		if s.end > s.start {
			advance, token, err := s.split(s.buf[s.start:s.end], false)
			if err != nil || !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				return true
			}
		}
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		if s.end == len(s.buf) {
			if len(s.buf) >= s.maxTokenSize {
				return false
			}
			newSize := len(s.buf) * 2
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		for loop := 0; ; {
			n, _ := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if n > 0 {
				break
			}
			loop++
			if loop > 100 {
				break
			}
		}
	}
}

func (s *Scanner) Split(split bufio.SplitFunc) {
	s.split = split
}

var w *bufio.Writer = bufio.NewWriter(os.Stdout)
var sc *Scanner = NewScanner(os.Stdin)

func next() string { sc.Scan(); return sc.Text() }

func ni32() int {
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	return n
}

func ni64() int64 {
	sc.Scan()
	n, _ := strconv.ParseInt(sc.Text(), 10, 64)
	return n
}

func pri32(i ...int) {
	for _, ii := range i {
		w.WriteString(strconv.Itoa(ii))
		sp()
	}
}
func pri64(i ...int64) {
	for _, ii := range i {
		w.WriteString(strconv.FormatInt(ii, 10))
		sp()
	}
}
func sp()   { w.WriteByte(' ') }
func endl() { w.WriteByte('\n') }

func Sum(n int64) (result int64) {

	var i uint64
	result = (n*(n+1))/2
	for n > 0 {

		i += 1
		n >>= 1

	}
	result = result - (1<<(i-1))<<1
	return
}

func SumFinal(slice []int64) []int64 {

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

		slice[i] = Sum(slice[i])

	}
	return slice

}

func main() {
	defer w.Flush()
	var t int64 = ni64()
	var x int64
	var i int64
	slice := make([]int64, t)
	for i = 0; i < t; i++ {
		x = ni64()
		slice[i] = x
	}

	pri64(SumFinal(slice)...)
	endl()
}

package main

import (
    "fmt"
    "math"
)

var pows []int

func main() {
    var t int
    fmt.Scanln(&t)

    ns := make([]int, t)

    for i := range ns {
        fmt.Scanln(&ns[i])
    }

    max := maxInSlice(ns)

    pows = make([]int, maxLog(max) + 1)

    pows[0] = 1

    for i := 1; i < len(pows); i++ {
        pows[i] = pows[i - 1] + int(math.Pow(2.0, float64(i)))
    }

    for _, n := range ns {
        fmt.Println(sumNegPows(n))
    }
}

func maxInSlice(arr []int) int {
    max := arr[0]

    for _, v := range arr {
        if v > max {
            max = v
        }
    }

    return max
}

func maxLog(x int) int {
    return int(math.Floor(math.Log2(float64(x))))
}

func sumNegPows(n int) int64 {
    var sum int64

    if n % 2 == 0 {
        sum = int64((1 + n) * (n / 2))
    } else {
        sum = int64(n * ((n - 1) / 2) + n)
    }

    sum += int64(-2 * pows[maxLog(n)])

    return sum
}

package main

import (
    "fmt"
    "math"
)

var pows []int

func main() {
    var t int
    fmt.Scanf("%d", &t)

    ns := make([]int, t)

    for i := range ns {
        fmt.Scanf("%d", &ns[i])
    }

    max := maxInSlice(ns)

    pows = make([]int, maxLog(max) + 1)

    for i := range pows {
        pows[i] = int(math.Pow(2.0, float64(i)))
    }

    for _, n := range ns {
        fmt.Println(sumNegPows(n))
    }
}

func maxInSlice(arr []int) int {
    max := arr[0]

    for _, v := range arr {
        if v > max {
            max = v
        }
    }

    return max
}

func maxLog(x int) int {
    return int(math.Floor(math.Log2(float64(x))))
}

func sumNegPows(n int) int {
    var sum int = 0

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

    for i := 0; i < maxLog(n) + 1; i++ {
        sum -= 2 * pows[i]
    }

    return sum
}

package main

import (
    "fmt"
    "math"
)

var pows []int

func main() {
    var t int
    fmt.Scanln(&t)

    ns := make([]int, t)

    for i := range ns {
        fmt.Scanln(&ns[i])
    }

    max := maxInSlice(ns)

    pows = make([]int, maxLog(max) + 1)

    for i := range pows {
        pows[i] = int(math.Pow(2.0, float64(i)))
    }

    for _, n := range ns {
        fmt.Println(sumNegPows(n))
    }
}

func maxInSlice(arr []int) int {
    max := arr[0]

    for _, v := range arr {
        if v > max {
            max = v
        }
    }

    return max
}

func maxLog(x int) int {
    return int(math.Floor(math.Log2(float64(x))))
}

func sumNegPows(n int) int {
    var sum int = 0

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

    for i := 0; i < maxLog(n) + 1; i++ {
        sum -= 2 * pows[i]
    }

    return sum
}

package main

import (
    "fmt"
    "math"
)

var pows []int64

func main() {
    var t int
    fmt.Scanln(&t)

    ns := make([]int, t)

    for i := range ns {
        fmt.Scanln(&ns[i])
    }

    max := maxInSlice(ns)

    pows = make([]int64, maxLog(max) + 1)

    pows[0] = int64(1)

    for i := 1; i < len(pows); i++ {
        pows[i] = pows[i - 1] + int64(math.Pow(2.0, float64(i)))
    }

    for _, n := range ns {
        fmt.Println(sumNegPows(n))
    }
}

func maxInSlice(arr []int) int {
    max := arr[0]

    for _, v := range arr {
        if v > max {
            max = v
        }
    }

    return max
}

func maxLog(x int) int64 {
    return int64(math.Floor(math.Log2(float64(x))))
}

func sumNegPows(n int) int64 {
    var sum int64

    if n % 2 == 0 {
        sum = int64((1 + n) * (n / 2))
    } else {
        sum = int64(n * ((n - 1) / 2) + n)
    }

    sum += int64(-2 * pows[maxLog(n)])

    return sum
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var i, n int
fmt.Scanf("%d", &i)
	for j := 0; j < i; j++ {
fmt.Scanf("%d", &n)
		solve(n)
	}
}

func solve(m int) error {
	n := int64(m)
	var total int64 = n * (n + 1) / 2
	maxPower := math.Floor(math.Log2(float64(n)))
	dd := 2*(math.Pow(2, maxPower + 1) - 1)
	fmt.Printf("%d\n", total-int64(dd))
	return nil

}

package main

import "fmt"

func main() {
	var l uint
	var a,b,n,r int64
	var i int

	fmt.Scanf("%d",&i)
	for i>0 {
		fmt.Scanf("%d",&n)
		a=n*(n+1)/2
		l=0
		for n >= 1<<l { l++ }
		b=^(^0<<l)
		r=a-b-b
		fmt.Println(r)
		i--
	}
}

package main

import "fmt"
import "strconv"

func calc(n int) string {
  f := n * (n + 1) / 2
  i := 1
  for i <= n {
    f = f - 2 * i
    i = i * 2
  }
  return strconv.Itoa(f)
}

func main() {
  var n int
  fmt.Scan(&n)
  for i :=  0; i < n; i++ {
    var k int
    fmt.Scan(&k)
    fmt.Println(calc(k))
  }
}

package main

import "fmt"
import "strconv"

func calc(n int) string {
  f := n
  return strconv.Itoa(f)
}

func main() {
  var n int
  fmt.Scan(&n)
  for i :=  0; i < n; i++ {
    var k int
    fmt.Scan(&k)
    fmt.Println(calc(k))
  }
}

package main

import(
	"fmt"
)

func main(){
	var n int
	fmt.Scanf("%d", &n)
	arr := make([]int64, n)
	for i := 0; i < n; i++{

		fmt.Scanf("%d", &arr[i])
		sum := (1 + arr[i])*arr[i]/2
		var b, j int64
		for b = arr[i]; b > 0; b >>= 1{
			j++
		}
		b = 1
		for ; j >= 0; j-- {
			b = (b << 1) +1
			j --
		}

		arr[i] = sum - 2*b
	}

	for _, m := range arr{
		fmt.Printf("%d\n", m)
	}

}

package main

import(
	"fmt"
)

func main(){
	var n int
	fmt.Scanf("%d", &n)
	arr := make([]int64, n)
	for i := 0; i < n; i++{

		fmt.Scanf("%d", &arr[i])
		sum := (1 + arr[i])*arr[i]/2
		var b, j int64 = 0, 1
		for b = arr[i]; b > 1; b >>= 1{
			j = j << 1 +1
		}

		arr[i] = sum - 2*j
	}

	for _, m := range arr{
		fmt.Printf("%d\n", m)
	}

}

package main

import(
	"fmt"
)

func getpow(x int64) int64{
	if x >>= 1; x != 0 {
		x = getpow(x)
		x = (x << 1) + 1

	}else{
		x = 1
	}
	return x
}

func main(){
	var n int
	fmt.Scanf("%d", &n)
	arr := make([]int64, n)
	for i := 0; i < n; i++{

		fmt.Scanf("%d", &arr[i])
		sum := (1 + arr[i])*arr[i]/2
		b:= getpow(arr[i])
		arr[i] = sum - 2*b
	}

	for _, m := range arr{
		fmt.Printf("%d\n", m)
	}

}

// -*- mode:go;mode:go-playground -*-
// snippet of code @ 2015-11-18 09:43:58
//
// run snippet with Ctl-Return

package main

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

func sumTwoPowers(n int64) int64 {
	max := int64(1)

	for max <= n {
		max *= 2
	}
	return max - 1
}

func sumAll(n int64) int64 {
	return (n / 2) * (1 + n)
}

func trickySum(n int64) int64 {
	allsum := sumAll(n)
	twosum := sumTwoPowers(n)
	return allsum - 2*twosum
}

/*
等比数列求和
a1(1-q^n)
----------
1-q

1 (1 - 2^n)
----------- = 2^n - 1
1 - 2

1 2 4

2 ^ 3 - 1
*/

//1 2 3 4

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	lines, _ := strconv.Atoi(scanner.Text())

	for i := 0; i < lines; i++ {
		scanner.Scan()
		n, _ := strconv.ParseInt(scanner.Text(), 10, 64)
		fmt.Println(trickySum(n))
	}
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)

func init() {
	scanner.Split(bufio.ScanWords)
}

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

func scanInt64() int64 {
	scanner.Scan()
	v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return v
}

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

func scanInts(n int) []int {
	l := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		l[i], _ = strconv.Atoi(scanner.Text())
	}

	return l
}

func scanInts64(n int64) []int64 {
	l := make([]int64, n)
	for i := int64(0); i < n; i++ {
		scanner.Scan()
		l[i], _ = strconv.ParseInt(scanner.Text(), 10, 64)
	}

	return l
}

func scanBool() bool {
	scanner.Scan()
	v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return v == 1
}

func scanBools(n int64) []bool {
	l := make([]bool, n)
	for i := int64(0); i < n; i++ {
		scanner.Scan()
		v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
		l[i] = v == 1
	}

	return l
}

func main() {
	t := scanInt()

	for i := 0; i < t; i++ {
		n := scanInt()
		fmt.Println(sum(n))
	}
}

func sum(n int) int {
	s := n * (1 + n) / 2

	for i := 1; i <= n; i *= 2 {
		s -= i * 2
	}

	return s
}

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

	return -a
}

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

	return b
}


package main

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

func OpenFile(fpath string) *os.File {
	f, err := os.Open(fpath)
	Assert(err == nil)
	return f
}

func Assert(b bool)  {
	if !b {
		panic("Assertion error")
	}
}

func GetLine(scanner *bufio.Scanner) string {
	ok := scanner.Scan()
	if err := scanner.Err(); err != nil {
		panic(err)
	}
	Assert(ok) // EOF
	return scanner.Text()
}

//type Int int
type Int int64

func ReadIntLine(scanner *bufio.Scanner) []Int {
	lst := make([]Int, 0)
	for _, s := range strings.Fields(GetLine(scanner)) {
		i, err := strconv.Atoi(s)
		Assert(err == nil)
		lst = append(lst, Int(i))
	}
	return lst
}

func ReadIntoInts(scanner *bufio.Scanner, ints... *Int) {
	for i, v := range ReadIntLine(scanner) {
		*ints[i] = v
	}
}

// SliceIndex(len(slice), func(i int) bool { return slice[i] == value })
func SliceIndex(limit int, predicate func(i int) bool) int {
	for i := 0; i < limit; i++ {
		if predicate(i) {
			return i
		}
	}
	return -1
}

func Ternary(c bool, a, b interface{}) interface{} {
	if c { return a }
	return b
}

func Min(a, b Int) Int { if a < b {return a}; return b }
func Max(a, b Int) Int { if a < b {return b}; return a }

func main() {
	f := os.Stdin
	//f := strings.NewReader(`3 0
//1 2 3
//3 2 1`)

//	f := strings.NewReader(`5 1
//7 4 2 1 0
//1 2 3 4 5`)

//	f := strings.NewReader(`4 3
//13 10 7 4
//4 7 10 13`)

//	f := strings.NewReader(`10 4
//36 80 90 80 14 84 22 29 35 45
//100 2 1 98 28 89 52 37 15 77`)

	//f = OpenFile("/home/ilya/opt/programming/tasks/724E_gen.txt")

	sc := bufio.NewScanner(f)
	// 64k too small
	sc.Buffer(nil, math.MaxInt32)

	var n, c Int
	ReadIntoInts(sc, &n, &c)

	pLst := ReadIntLine(sc)
	sLst := ReadIntLine(sc)

	var fLst [1e4+10]Int

	for i := Int(0); i < n; i++ {
		x := i + 1
		p, s := pLst[i], sLst[i]

		pcy := p + c * x

		for y := x; y > 0; y-- {
			f := s+fLst[y-1]
			if y == x {
				fLst[y] = f
			} else {
				fLst[y] = Min(pcy+fLst[y], f)
			}

			pcy -= c
		}
		fLst[0] += p
	}

	res := Int(math.MaxInt64)
	for i := Int(0); i <= n; i++ {
		res = Min(res, fLst[i])
	}

	fmt.Println(res)
}

package main

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

func OpenFile(fpath string) *os.File {
	f, err := os.Open(fpath)
	Assert(err == nil)
	return f
}

func Assert(b bool)  {
	if !b {
		panic("Assertion error")
	}
}

func GetLine(scanner *bufio.Scanner) string {
	ok := scanner.Scan()
	if err := scanner.Err(); err != nil {
		panic(err)
	}
	Assert(ok) // EOF
	return scanner.Text()
}

func ReadIntLine(scanner *bufio.Scanner) []int {
	lst := make([]int, 0)
	for _, s := range strings.Fields(GetLine(scanner)) {
		i, err := strconv.Atoi(s)
		Assert(err == nil)
		lst = append(lst, i)
	}
	return lst
}

func ReadIntoInts(scanner *bufio.Scanner, ints... *int) {
	for i, v := range ReadIntLine(scanner) {
		*ints[i] = v
	}
}

// SliceIndex(len(slice), func(i int) bool { return slice[i] == value })
func SliceIndex(limit int, predicate func(i int) bool) int {
	for i := 0; i < limit; i++ {
		if predicate(i) {
			return i
		}
	}
	return -1
}

func Ternary(c bool, a, b interface{}) interface{} {
	if c { return a }
	return b
}

func main() {
	f := os.Stdin
//	f := strings.NewReader(`3 0
//1 2 3
//3 2 1`)

//	f := strings.NewReader(`5 1
//7 4 2 1 0
//1 2 3 4 5`)

//	f := strings.NewReader(`4 3
//13 10 7 4
//4 7 10 13`)

//	f := strings.NewReader(`10 4
//36 80 90 80 14 84 22 29 35 45
//100 2 1 98 28 89 52 37 15 77`)

	//f = OpenFile("/home/ilya/opt/programming/tasks/724E_gen.txt")

	sc := bufio.NewScanner(f)
	// 64k too small
	sc.Buffer(nil, math.MaxInt32)

	var n, c int
	ReadIntoInts(sc, &n, &c)

	pLst := ReadIntLine(sc)
	sLst := ReadIntLine(sc)

	var fLst [1e4+10]int64

	min := func(a, b int64) int64 { if a < b {return a}; return b }

	for i := 0; i < n; i++ {
		x := int64(i + 1)
		p, s := int64(pLst[i]), int64(sLst[i])

		pcy := p + int64(c) * x

		Assert(p >= 0 && s >= 0)

		for y := x; y > 0; y-- {
			f := s+fLst[y-1]
			if y == x {
				fLst[y] = f
			} else {
				fLst[y] = min(pcy+fLst[y], f)
			}

			pcy -= int64(c)
		}
		fLst[0] += p
	}

	res := int64(math.MaxInt64)
	for i := 0; i <= n; i++ {
		res = min(res, fLst[i])
	}

	fmt.Println(res)
}

package main

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

func OpenFile(fpath string) *os.File {
	f, err := os.Open(fpath)
	Assert(err == nil)
	return f
}

func Assert(b bool)  {
	if !b {
		panic("Assertion error")
	}
}

func GetLine(scanner *bufio.Scanner) string {
	ok := scanner.Scan()
	if err := scanner.Err(); err != nil {
		panic(err)
	}
	Assert(ok) // EOF
	return scanner.Text()
}

func ReadIntLine(scanner *bufio.Scanner) []int {
	lst := make([]int, 0)
	for _, s := range strings.Fields(GetLine(scanner)) {
		i, err := strconv.Atoi(s)
		Assert(err == nil)
		lst = append(lst, i)
	}
	return lst
}

func ReadIntoInts(scanner *bufio.Scanner, ints... *int) {
	for i, v := range ReadIntLine(scanner) {
		*ints[i] = v
	}
}

// SliceIndex(len(slice), func(i int) bool { return slice[i] == value })
func SliceIndex(limit int, predicate func(i int) bool) int {
	for i := 0; i < limit; i++ {
		if predicate(i) {
			return i
		}
	}
	return -1
}

func Ternary(c bool, a, b interface{}) interface{} {
	if c { return a }
	return b
}

func main() {
	f := os.Stdin
//	f := strings.NewReader(`3 0
//1 2 3
//3 2 1`)

//	f := strings.NewReader(`5 1
//7 4 2 1 0
//1 2 3 4 5`)

//	f := strings.NewReader(`4 3
//13 10 7 4
//4 7 10 13`)

//	f := strings.NewReader(`10 4
//36 80 90 80 14 84 22 29 35 45
//100 2 1 98 28 89 52 37 15 77`)

	//f = OpenFile("/home/ilya/opt/programming/tasks/724E_gen.txt")

	sc := bufio.NewScanner(f)
	// 64k too small
	sc.Buffer(nil, math.MaxInt32)

	var n, c int
	ReadIntoInts(sc, &n, &c)

	pLst := ReadIntLine(sc)
	sLst := ReadIntLine(sc)

	var fLst [1e4+10]uint64

	min := func(a, b uint64) uint64 { if a < b {return a}; return b }

	for i := 0; i < n; i++ {
		x := i + 1
		p, s := uint64(pLst[i]), uint64(sLst[i])

		pcy := p + uint64(c * x)

		for y := x; y > 0; y-- {
			f := s+fLst[y-1]
			if y == x {
				fLst[y] = f
			} else {
				fLst[y] = min(pcy+fLst[y], f)
			}

			pcy -= uint64(c)
		}
		fLst[0] += p
	}

	res := uint64(math.MaxUint64)
	for i := 0; i <= n; i++ {
		res = min(res, fLst[i])
	}

	fmt.Println(res)
}

package main

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

func OpenFile(fpath string) *os.File {
	f, err := os.Open(fpath)
	Assert(err == nil)
	return f
}

func Assert(b bool)  {
	if !b {
		panic("Assertion error")
	}
}

func GetLine(scanner *bufio.Scanner) string {
	ok := scanner.Scan()
	if err := scanner.Err(); err != nil {
		panic(err)
	}
	Assert(ok) // EOF
	return scanner.Text()
}

func ReadIntLine(scanner *bufio.Scanner) []int {
	lst := make([]int, 0)
	for _, s := range strings.Fields(GetLine(scanner)) {
		i, err := strconv.Atoi(s)
		Assert(err == nil)
		lst = append(lst, i)
	}
	return lst
}

func ReadIntoInts(scanner *bufio.Scanner, ints... *int) {
	for i, v := range ReadIntLine(scanner) {
		*ints[i] = v
	}
}

// SliceIndex(len(slice), func(i int) bool { return slice[i] == value })
func SliceIndex(limit int, predicate func(i int) bool) int {
	for i := 0; i < limit; i++ {
		if predicate(i) {
			return i
		}
	}
	return -1
}

func Ternary(c bool, a, b interface{}) interface{} {
	if c { return a }
	return b
}

func main() {
	f := os.Stdin
//	f := strings.NewReader(`3 0
//1 2 3
//3 2 1`)

//	f := strings.NewReader(`5 1
//7 4 2 1 0
//1 2 3 4 5`)

//	f := strings.NewReader(`4 3
//13 10 7 4
//4 7 10 13`)

//	f := strings.NewReader(`10 4
//36 80 90 80 14 84 22 29 35 45
//100 2 1 98 28 89 52 37 15 77`)

	//f = OpenFile("/home/ilya/opt/programming/tasks/724E_gen.txt")

	sc := bufio.NewScanner(f)
	// 64k too small
	sc.Buffer(nil, math.MaxInt32)

	var n, c int
	ReadIntoInts(sc, &n, &c)

	pLst := ReadIntLine(sc)
	sLst := ReadIntLine(sc)

	var fLst [1e4+10]int64

	min := func(a, b int64) int64 { if a < b {return a}; return b }

	for i := 0; i < n; i++ {
		x := i + 1
		p, s := int64(pLst[i]), int64(sLst[i])

		pcy := p + int64(c * x)

		Assert(p >= 0 && s >= 0)

		for y := x; y > 0; y-- {
			f := s+fLst[y-1]
			if y == x {
				fLst[y] = f
			} else {
				fLst[y] = min(pcy+fLst[y], f)
			}

			pcy -= int64(c)
		}
		fLst[0] += p
	}

	res := int64(math.MaxInt64)
	for i := 0; i <= n; i++ {
		res = min(res, fLst[i])
	}

	fmt.Println(res)
}

package main

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

func OpenFile(fpath string) *os.File {
	f, err := os.Open(fpath)
	Assert(err == nil)
	return f
}

func Assert(b bool)  {
	if !b {
		panic("Assertion error")
	}
}

func GetLine(scanner *bufio.Scanner) string {
	ok := scanner.Scan()
	if err := scanner.Err(); err != nil {
		panic(err)
	}
	Assert(ok) // EOF
	return scanner.Text()
}

func ReadIntLine(scanner *bufio.Scanner) []int {
	lst := make([]int, 0)
	for _, s := range strings.Fields(GetLine(scanner)) {
		i, err := strconv.Atoi(s)
		Assert(err == nil)
		lst = append(lst, i)
	}
	return lst
}

func ReadIntoInts(scanner *bufio.Scanner, ints... *int) {
	for i, v := range ReadIntLine(scanner) {
		*ints[i] = v
	}
}

// SliceIndex(len(slice), func(i int) bool { return slice[i] == value })
func SliceIndex(limit int, predicate func(i int) bool) int {
	for i := 0; i < limit; i++ {
		if predicate(i) {
			return i
		}
	}
	return -1
}

func Ternary(c bool, a, b interface{}) interface{} {
	if c { return a }
	return b
}

func main() {
	f := os.Stdin
//	f := strings.NewReader(`3 0
//1 2 3
//3 2 1`)

//	f := strings.NewReader(`5 1
//7 4 2 1 0
//1 2 3 4 5`)

//	f := strings.NewReader(`4 3
//13 10 7 4
//4 7 10 13`)

//	f := strings.NewReader(`10 4
//36 80 90 80 14 84 22 29 35 45
//100 2 1 98 28 89 52 37 15 77`)

	//f = OpenFile("/home/ilya/opt/programming/tasks/724E_gen.txt")

	sc := bufio.NewScanner(f)
	// 64k too small
	sc.Buffer(nil, math.MaxInt32)

	var n, c int
	ReadIntoInts(sc, &n, &c)

	pLst := ReadIntLine(sc)
	sLst := ReadIntLine(sc)

	var fLst [1e4+10]int64

	min := func(a, b int64) int64 { if a < b {return a}; return b }

	for i := 0; i < n; i++ {
		x := i + 1
		p, s := int64(pLst[i]), int64(sLst[i])

		pcy := p + int64(c * x)

		for y := x; y > 0; y-- {
			f := s+fLst[y-1]
			if y == x {
				fLst[y] = f
			} else {
				fLst[y] = min(pcy+fLst[y], f)
			}

			pcy -= int64(c)
		}
		fLst[0] += p
	}

	res := int64(math.MaxInt64)
	for i := 0; i <= n; i++ {
		res = min(res, fLst[i])
	}

	fmt.Println(res)
}


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 s string
		fmt.Fscan(in, &s)
		loc := make([][]int, 26)
		for i, c := range s {
			idx := int(c - 'a')
			loc[idx] = append(loc[idx], i)
		}
		var sol string
		for i := 0; i < 26; i++ {
			for j := 25; j >= 0; j-- {
				bad := false
				if len(loc[j]) == 0 {
					continue
				}
				for k := 0; k < 26; k++ {
					if k == j || len(loc[k]) == 0 || loc[k][0] > loc[j][0] {
						continue
					}
					if loc[k][len(loc[k])-1] < loc[j][0] {
						bad = true
						break
					}
				}
				if bad {
					continue
				}
				for k := 0; k < 26; k++ {
					if k == j || len(loc[k]) == 0 || loc[k][0] > loc[j][0] {
						continue
					}
					for len(loc[k]) > 0 && loc[k][0] < loc[j][0] {
						loc[k] = loc[k][1:]
					}
				}
				loc[j] = nil
				sol += string(byte(j) + 'a')
				break
			}
		}
		fmt.Fprintln(out, sol)
	}
}

package main

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

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

	var T int
	var s []byte
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &s)
		c := [123]int{}
		for _, b := range s {
			c[b]++
		}
		t := []byte{}
		inT := [123]bool{}
		for _, b := range s {
			c[b]--
			if inT[b] {
				continue
			}
			for len(t) > 0 && c[t[len(t)-1]] > 0 && b >= t[len(t)-1] {
				inT[t[len(t)-1]] = false
				t = t[:len(t)-1]
			}
			t = append(t, b)
			inT[b] = true
		}
		Fprintf(out, "%s\n", t)
	}
}

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

package main
import."fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	T, s := 0, []byte{}
	for Scan(&T); T > 0; T-- {
		Scan(&s)
		c := [123]int{}
		for _, b := range s {
			c[b]++
		}
		t := []byte{}
		inT := [123]bool{}
		for _, b := range s {
			c[b]--
			if !inT[b] {
				for len(t) > 0 && c[t[len(t)-1]] > 0 && b >= t[len(t)-1] {
					inT[t[len(t)-1]] = false
					t = t[:len(t)-1]
				}
				t = append(t, b)
				inT[b] = true
			}
		}
		Printf("%s\n", t)
	}
}

package main

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

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

	solve := func(Case int) {
		var s, ans []byte
		Fscan(in, &s)
		cnt := ['z' + 1]int{}
		for _, b := range s {
			cnt[b]++
		}
		//n := len(s)
		//sufMax := make([]byte, n+1)
		//for i := n - 1; i >= 0; i-- {
		//	sufMax[i] = max(sufMax[i+1], s[i])
		//}

		stk := []byte{}
		for _, b := range s {
			if cnt[b] == 0 {
				continue
			}
			for len(stk) > 0 && b >= stk[len(stk)-1] {
				v := stk[len(stk)-1]
				cnt[v]--
				stk = stk[:len(stk)-1]
			}
			stk = append(stk, b)
			if cnt[b] == 1 {
				ans = append(ans, stk...)
				for _, c := range stk {
					cnt[c] = 0
				}
				stk = nil
			}
		}

		//o:
		//	for cur := 0; cur < n; {
		//		mxPos := cur
		//		for i := cur; i < n; i++ {
		//			b := s[i]
		//			if cnt[b] <= 0 {
		//				continue
		//			}
		//			if b == sufMax[i] {
		//				ans = append(ans, b)
		//				for _, c := range s[cur:i] {
		//					cnt[c]--
		//				}
		//				cnt[b] = 0 // delete
		//				cur = i + 1
		//				continue o
		//			}
		//			if b > s[mxPos] {
		//				mxPos = i
		//			}
		//			if cnt[b] == 1 {
		//				ans = append(ans, s[mxPos])
		//				if i > mxPos {
		//					ans = append(ans, b)
		//				}
		//				for _, c := range s[cur:i] {
		//					cnt[c]--
		//				}
		//				cnt[s[mxPos]] = 0 // delete
		//				cur = i + 1
		//				continue o
		//			}
		//		}
		//		break
		//	}
		Fprintln(out, string(ans))
	}

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

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}
}

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

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


package main

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

const (
	Inf = 2000000009
	MaxN = 200005
	MaxL = 20
)

type voucher struct {
	l, r, price int
}

func (v *voucher) size() int {
	return v.r - v.l + 1
}

var n, x int
var v []voucher
var rmq [MaxN][MaxL]int

func min(args ...int) int {
	a := args[0]
	for i := 1; i < len(args); i++ {
		if a > args[i] {
			a = args[i]
		}
	}
	return a
}

func buildRmq() {
	for i := 0; i < n; i++ {
		rmq[i][0] = v[i].price
	}

	for p := uint(1); 1 << p <= n; p++ {
		for i := 0; i < n; i++ {
			end := min(i + (1 << p), n) - (1 << (p-1))
			rmq[i][p] = min(rmq[i][p-1], rmq[end][p-1])
		}
	}
}

// gets the minimum from the interval [l; r]
func query(l, r int) int {
	if l == r {
		return rmq[l][0]
	}
	pow := uint(math.Log2(float64(r - l + 1)))
	return min(rmq[l][pow], rmq[r-(1<<pow)+1][pow])
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &x)
	v = make([]voucher, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d %d\n", &v[i].l, &v[i].r, &v[i].price)
	}
	sort.Slice(v, func(i, j int) bool {
		if v[i].size() < v[j].size() {
			return true
		}
		if v[i].size() > v[j].size() {
			return false
		}
		return v[i].r < v[j].r
	})

	buildRmq()

	//for i := 0; i < n; i++ {
	//	for j := 0; j < n; j++ {
	//		fmt.Println(i, j, query(min(i, j), i+j - min(i, j)))
	//	}
	//}

	//fmt.Println(v)
	//for i := 0; i < n; i++ {
	//	fmt.Print(v[i].size(), " ")
	//}
	//fmt.Println()
	//for i := 0; i < n; i++ {
	//	fmt.Println(rmq[i][:15])
	//}

	ans := Inf
	for i := 0; i < n; i++ {
		val := x - v[i].size()
		// Fix the search size
		ind1 := sort.Search(n, func(i int) bool {
			return v[i].size() >= val
		})
		if ind1 == n || v[ind1].size() != val {
			continue
		}
		ind2 := sort.Search(n, func(i int) bool {
			return v[i].size() > val
		})

		// Another binary search to find where the right end becomes bigger
		// so we need to check for a minimum in the interval [ind1; ind2)
		q := v[ind1:ind2]
		ind3 := sort.Search(len(q), func(index int) bool {
			return q[index].r >= v[i].l
		})
		//fmt.Println(">>", i, ind1, ind2, ind3)
		if ind3 == len(q) {
			ind3 = ind2 - 1
		} else {
			ind3 = ind1 + ind3 - 1
			if ind3 < ind1 {
				continue
			}
		}
		newPrice := v[i].price + query(ind1, ind3)
		if newPrice < ans {
			ans = newPrice
		}
	}
	if ans == Inf {
		ans = -1
	}
	fmt.Println(ans)
}

package main

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

type point struct {
	x    int
	l, r int
	c    int
	open int
}

func solve() {
	n := readInt()
	x := readInt()
	q := make([]point, n*2)
	for i := 0; i < n; i++ {
		l := readInt()
		r := readInt()
		c := readInt()
		q[i*2] = point{l, l, r, c, -1}
		q[i*2+1] = point{r, l, r, c, 1}
	}
	ans := math.MaxInt32
	sort.Sort(ByLeft(q))
	mm := map[int]int{}
	for i := 0; i < len(q); i++ {
		p := q[i]
		if p.open == -1 {
			y := p.r - p.l + 1
			if x >= y {
				if c, ok := mm[x-y]; ok {
					ans = min(ans, c+p.c)
				}
			}
		} else {
			y := p.r - p.l + 1
			if v, ok := mm[y]; ok {
				if p.c < v {
					mm[y] = p.c
				}
			} else {
				mm[y] = p.c
			}
		}
	}
	if ans == math.MaxInt32 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

type ByLeft []point

func (a ByLeft) Len() int      { return len(a) }
func (a ByLeft) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByLeft) Less(i, j int) bool {
	if a[i].x == a[j].x {
		return a[i].open < a[j].open
	}
	return a[i].x < a[j].x
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

type tour struct {
	l, r, cost int
}

func (p tour) Len() int {
	return p.r - p.l + 1
}

type tourSlice []tour

func (p tourSlice) Len() int {
	return len(p)
}

func (p tourSlice) Less(i, j int) bool {
	a, b := p[i], p[j]
	if a.Len() != b.Len() {
		return a.Len() < b.Len()
	}
	return a.r < b.r
}

func (p tourSlice) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

var scanner = bufio.NewScanner(os.Stdin)

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

func main() {
	scanner.Split(bufio.ScanWords)
	n, x := readInt32(), readInt32()
	tours := make([]tour, n)
	for i := range tours {
		l, r, cost := readInt32(), readInt32(), readInt32()
		tours[i] = tour{l, r, cost}
	}
	sort.Sort(tourSlice(tours))
	minCosts := findMinCosts(tours)
	res := math.MaxInt32
	for i := range tours {
		j := sort.Search(
			len(tours),
			func(j int) bool {
				return (tours[i].Len()+tours[j].Len() > x) ||
					((tours[i].Len()+tours[j].Len() == x) && (tours[i].r < tours[j].l))
			})
		if (j < len(tours)) && (tours[i].Len()+tours[j].Len() == x) && (res > tours[i].cost+minCosts[j]) {
			res = tours[i].cost + minCosts[j]
		}
	}
	if res == math.MaxInt32 {
		res = -1
	}
	fmt.Println(res)
}

func findMinCosts(tours []tour) []int {
	res := make([]int, len(tours))
	prevLen := tours[len(tours)-1].Len() + 1
	var minCost int
	for i := len(tours) - 1; i >= 0; i-- {
		if prevLen > tours[i].Len() {
			prevLen = tours[i].Len()
			minCost = tours[i].cost
		}
		if minCost > tours[i].cost {
			minCost = tours[i].cost
		}
		res[i] = minCost
	}
	return res
}

// Try Codeforces
// author: Leonardone @ NEETSDKASU
package main

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

var red = bufio.NewScanner(os.Stdin)

func read(vs ...interface{}) {
	red.Scan()
	tx := strings.Split(red.Text(), " ")
	for i, v := range vs {
		switch x := v.(type) {
		case *int:
			*x, _ = strconv.Atoi(tx[i])
		}
	}
}

const M = 2e5 + 10

func main() {
	var n, x int
	read(&n, &x)
	starts := make([]map[int]int, M)
	ends := make([]map[int]int, M)
	mins := make(map[int]int)
	for i := 0; i < n; i++ {
		var li, ri, ti int
		read(&li, &ri, &ti)
		d := ri - li + 1
		if starts[li] == nil {
			starts[li] = make(map[int]int)
		}
		if tp, ok := starts[li][d]; !ok || ti < tp {
			starts[li][d] = ti
		}
		if ends[ri] == nil {
			ends[ri] = make(map[int]int)
		}
		if tp, ok := ends[ri][d]; !ok || ti < tp {
			ends[ri][d] = ti
		}
	}
	ans := -1
	for i := 1; i <= 2e5; i++ {
		if starts[i] != nil {
			for k, v := range starts[i] {
				d := x - k
				if w, ok := mins[d]; ok {
					h := w + v
					if ans < 0 || h < ans {
						ans = h
					}
				}
			}
		}
		if ends[i] != nil {
			for k, v := range ends[i] {
				if w, ok := mins[k]; !ok || v < w {
					mins[k] = v
				}
			}
		}
	}
	fmt.Println(ans)
}

package main

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

type point struct {
	x    int
	l, r int
	c    int
	open int
}

func solve() {
	n := readInt()
	x := readInt()
	q := make([]point, n*2)
	for i := 0; i < n; i++ {
		l := readInt()
		r := readInt()
		c := readInt()
		q[i*2] = point{l, l, r, c, -1}
		q[i*2+1] = point{r, l, r, c, 1}
	}
	ans := int64(math.MaxInt64)
	sort.Sort(ByLeft(q))
	mm := map[int]int{}
	for i := 0; i < len(q); i++ {
		p := q[i]
		if p.open == -1 {
			y := p.r - p.l + 1
			if x >= y {
				if c, ok := mm[x-y]; ok {
					ans = min(ans, int64(c)+int64(p.c))
				}
			}
		} else {
			y := p.r - p.l + 1
			if v, ok := mm[y]; ok {
				if p.c < v {
					mm[y] = p.c
				}
			} else {
				mm[y] = p.c
			}
		}
	}
	if ans == math.MaxInt64 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

type ByLeft []point

func (a ByLeft) Len() int      { return len(a) }
func (a ByLeft) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByLeft) Less(i, j int) bool {
	if a[i].x == a[j].x {
		return a[i].open < a[j].open
	}
	return a[i].x < a[j].x
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

type point struct {
	x    int
	l, r int
	c    int
	open int
}

func solve() {
	n := readInt()
	x := readInt()
	q := make([]point, n*2)
	for i := 0; i < n; i++ {
		l := readInt()
		r := readInt()
		c := readInt()
		q[i*2] = point{l, l, r, c, 1}
		q[i*2+1] = point{r, l, r, c, -1}
	}
	ans := int64(math.MaxInt64)
	sort.Sort(ByLeft(q))
	mm := map[int]int{}
	for i := 0; i < len(q); i++ {
		p := q[i]
		if p.open == 1 {
			y := p.r - p.l + 1
			if x >= y {
				if c, ok := mm[x-y]; ok {
					ans = min(ans, int64(c)+int64(p.c))
				}
			}
		} else {
			y := p.r - p.l + 1
			if v, ok := mm[y]; ok {
				if p.c < v {
					mm[y] = p.c
				}
			} else {
				mm[y] = p.c
			}
		}
	}
	if ans == math.MaxInt64 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

type ByLeft []point

func (a ByLeft) Len() int      { return len(a) }
func (a ByLeft) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByLeft) Less(i, j int) bool {
	if a[i].x == a[j].x {
		return a[i].open < a[j].open
	}
	return a[i].x < a[j].x
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

type point struct {
	x    int
	l, r int
	c    int
	open int
}

func solve() {
	n := readInt()
	x := readInt()
	q := make([]point, n*2)
	for i := 0; i < n; i++ {
		l := readInt()
		r := readInt()
		c := readInt()
		q[i*2] = point{l, l, r, c, 1}
		q[i*2+1] = point{r, l, r, c, -1}
	}
	ans := int64(math.MaxInt64)
	sort.Sort(ByLeft(q))
	mm := map[int]int{}
	for i := 0; i < len(q); i++ {
		p := q[i]
		if p.open == 1 {
			y := p.r - p.l + 1
			if x > y {
				if c, ok := mm[x-y]; ok {
					ans = min(ans, int64(c)+int64(p.c))
				}
			}
		} else {
			y := p.r - p.l + 1
			if v, ok := mm[y]; ok {
				if p.c < v {
					mm[y] = p.c
				}
			} else {
				mm[y] = p.c
			}
		}
	}
	if ans == math.MaxInt64 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

type ByLeft []point

func (a ByLeft) Len() int      { return len(a) }
func (a ByLeft) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByLeft) Less(i, j int) bool {
	if a[i].x == a[j].x {
		return a[i].open < a[j].open
	}
	return a[i].x < a[j].x
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

type point struct {
	x    int
	l, r int
	c    int
	open bool
}

func solve() {
	n := readInt()
	x := readInt()
	q := make([]point, n*2)
	for i := 0; i < n; i++ {
		l := readInt()
		r := readInt()
		c := readInt()
		q[i*2] = point{l, l, r, c, true}
		q[i*2+1] = point{r, l, r, c, false}
	}
	ans := math.MaxInt32
	sort.Sort(ByLeft(q))
	mm := map[int]int{}
	for i := 0; i < len(q); i++ {
		p := q[i]
		if p.open {
			y := p.r - p.l + 1
			if x > y {
				if c, ok := mm[x-y]; ok {
					ans = min(ans, c+p.c)
				}
			}
		} else {
			y := p.r - p.l + 1
			if v, ok := mm[y]; ok {
				mm[y] = min(v, p.c)
			} else {
				mm[y] = p.c
			}
		}
	}
	if ans == math.MaxInt32 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

type ByLeft []point

func (a ByLeft) Len() int           { return len(a) }
func (a ByLeft) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByLeft) Less(i, j int) bool { return a[i].x < a[j].x }

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

type point struct {
	x    int
	l, r int
	c    int
	open bool
}

func solve() {
	n := readInt()
	x := readInt()
	q := make([]point, n*2)
	for i := 0; i < n; i++ {
		l := readInt()
		r := readInt()
		c := readInt()
		q[i*2] = point{l, l, r, c, true}
		q[i*2+1] = point{r, l, r, c, false}
	}
	ans := math.MaxInt32
	sort.Sort(ByLeft(q))
	mm := map[int]int{}
	for i := 0; i < len(q); i++ {
		p := q[i]
		if p.open {
			y := p.r - p.l + 1
			if c, ok := mm[x-y]; ok {
				ans = min(ans, c+p.c)
			}
		} else {
			y := p.r - p.l + 1
			if v, ok := mm[y]; ok {
				mm[y] = min(v, p.c)
			} else {
				mm[y] = p.c
			}
		}
	}
	if ans == math.MaxInt32 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

type ByLeft []point

func (a ByLeft) Len() int           { return len(a) }
func (a ByLeft) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByLeft) Less(i, j int) bool { return a[i].x < a[j].x }

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

type point struct {
	x    int
	l, r int
	c    int
	open int
}

func solve() {
	n := readInt()
	x := readInt()
	q := make([]point, n*2)
	for i := 0; i < n; i++ {
		l := readInt()
		r := readInt()
		c := readInt()
		q[i*2] = point{l, l, r, c, 1}
		q[i*2+1] = point{r, l, r, c, -1}
	}
	ans := math.MaxInt32
	sort.Sort(ByLeft(q))
	mm := map[int]int{}
	for i := 0; i < len(q); i++ {
		p := q[i]
		if p.open == 1 {
			y := p.r - p.l + 1
			if x > y {
				if c, ok := mm[x-y]; ok {
					ans = min(ans, c+p.c)
				}
			}
		} else {
			y := p.r - p.l + 1
			if v, ok := mm[y]; ok {
				mm[y] = min(v, p.c)
			} else {
				mm[y] = p.c
			}
		}
	}
	if ans == math.MaxInt32 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

type ByLeft []point

func (a ByLeft) Len() int      { return len(a) }
func (a ByLeft) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByLeft) Less(i, j int) bool {
	if a[i].x == a[j].x {
		return a[i].open < a[j].open
	}
	return a[i].x > a[j].x
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

type point struct {
	x    int
	l, r int
	c    int
	open int
}

func solve() {
	n := readInt()
	x := readInt()
	q := make([]point, n*2)
	for i := 0; i < n; i++ {
		l := readInt()
		r := readInt()
		c := readInt()
		q[i*2] = point{l, l, r, c, 1}
		q[i*2+1] = point{r, l, r, c, -1}
	}
	ans := math.MaxInt32
	sort.Sort(ByLeft(q))
	mm := map[int]int{}
	for i := 0; i < len(q); i++ {
		p := q[i]
		if p.open == 1 {
			y := p.r - p.l + 1
			if x > y {
				if c, ok := mm[x-y]; ok {
					ans = min(ans, c+p.c)
				}
			}
		} else {
			y := p.r - p.l + 1
			if v, ok := mm[y]; ok {
				mm[y] = min(v, p.c)
			} else {
				mm[y] = p.c
			}
		}
	}
	if ans == math.MaxInt32 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

type ByLeft []point

func (a ByLeft) Len() int      { return len(a) }
func (a ByLeft) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByLeft) Less(i, j int) bool {
	if a[i].x == a[j].x {
		return a[i].open < a[j].open
	}
	return a[i].x < a[j].x
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

type tour struct {
	l, r, cost int
}

func (p tour) Len() int {
	return p.r - p.l + 1
}

type tourSlice []tour

func (p tourSlice) Len() int {
	return len(p)
}

func (p tourSlice) Less(i, j int) bool {
	a, b := p[i], p[j]
	if a.Len() != b.Len() {
		return a.Len() < b.Len()
	}
	return a.r < b.r
}

func (p tourSlice) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

var scanner = bufio.NewScanner(os.Stdin)

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

func main() {
	scanner.Split(bufio.ScanWords)
	n, x := readInt32(), readInt32()
	tours := make([]tour, n)
	for i := range tours {
		l, r, cost := readInt32(), readInt32(), readInt32()
		tours[i] = tour{l, r, cost}
	}
	sort.Sort(tourSlice(tours))
	minCosts := findMinCosts(tours)
	res := math.MaxInt32
	for i := range tours {
		j := sort.Search(
			len(tours),
			func(j int) bool {
				return (tours[i].Len()+tours[j].Len() > x) ||
					((tours[i].Len()+tours[j].Len() == x) && (tours[i].r < tours[j].l))
			})
		if (j < len(tours)) && (tours[i].Len()+tours[j].Len() == x) && (res > tours[i].cost+minCosts[j]) {
			res = tours[i].cost + minCosts[j]
		}
	}
	if res == math.MaxInt32 {
		res = -1
	}
	fmt.Println(res)
}

func findMinCosts(tours []tour) []int {
	res := make([]int, len(tours))
	prevLen := tours[len(tours)-1].Len() + 1
	var minCost int
	for i := len(tours) - 1; i > 0; i-- {
		if prevLen > tours[i].Len() {
			prevLen = tours[i].Len()
			minCost = tours[i].cost
		}
		if minCost > tours[i].cost {
			minCost = tours[i].cost
		}
		res[i] = minCost
	}
	return res
}

package main

import (
	"fmt"
	"math"
	"sort"
)

type tour struct {
	l, r, cost int
}

func (p tour) Len() int {
	return p.r - p.l + 1
}

type tourSlice []tour

func (p tourSlice) Len() int {
	return len(p)
}

func (p tourSlice) Less(i, j int) bool {
	a, b := p[i], p[j]
	if a.Len() != b.Len() {
		return a.Len() < b.Len()
	}
	return a.r < b.r
}

func (p tourSlice) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func main() {
	var n, x int
	fmt.Scan(&n, &x)
	tours := make([]tour, n)
	for i := range tours {
		fmt.Scan(&tours[i].l, &tours[i].r, &tours[i].cost)
	}
	sort.Sort(tourSlice(tours))
	minCosts := findMinCosts(tours)
	res := math.MaxInt32
	for i := range tours {
		j := sort.Search(
			len(tours),
			func(j int) bool {
				return (tours[i].Len()+tours[j].Len() >= x) && (tours[i].r < tours[j].l)
			})
		if (j < n) && (tours[i].Len()+tours[j].Len() == x) && (res > tours[i].cost+minCosts[j]) {
			res = tours[i].cost + minCosts[j]
		}
	}
	if res == math.MaxInt32 {
		res = -1
	}
	fmt.Println(res)
}

func findMinCosts(tours []tour) []int {
	res := make([]int, len(tours))
	prevLen := tours[len(tours)-1].Len() + 1
	var minCost int
	for i := len(tours) - 1; i > 0; i-- {
		if prevLen > tours[i].Len() {
			prevLen = tours[i].Len()
			minCost = tours[i].cost
		}
		if minCost > tours[i].cost {
			minCost = tours[i].cost
		}
		res[i] = minCost
	}
	return res
}

package main

import (
	"fmt"
	"math"
	"sort"
)

type tour struct {
	l, r, cost int
}

func (p tour) Len() int {
	return p.r - p.l + 1
}

type tourSlice []tour

func (p tourSlice) Len() int {
	return len(p)
}

func (p tourSlice) Less(i, j int) bool {
	a, b := p[i], p[j]
	if a.Len() != b.Len() {
		return a.Len() < b.Len()
	}
	return a.r < b.r
}

func (p tourSlice) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func main() {
	var n, x int
	fmt.Scan(&n, &x)
	tours := make([]tour, n)
	for i := range tours {
		fmt.Scan(&tours[i].l, &tours[i].r, &tours[i].cost)
	}
	sort.Sort(tourSlice(tours))
	minCosts := findMinCosts(tours)
	res := math.MaxInt32
	for i := range tours {
		j := sort.Search(
			len(tours),
			func(j int) bool {
				return (tours[i].Len()+tours[j].Len() >= x) && (tours[i].r < tours[j].l)
			})
		if (j < n) && (tours[i].Len()+tours[j].Len() == x) && (res > tours[i].cost+minCosts[j]) {
			res = tours[i].cost + minCosts[j]
		}
	}
	if res == math.MaxInt32 {
		res = -1
	}
	fmt.Println(res)
}

func findMinCosts(tours []tour) []int {
	res := make([]int, len(tours))
	prevDate := tours[len(tours)-1].l + 1
	var minCost int
	for i := len(tours) - 1; i > 0; i-- {
		if prevDate > tours[i].l {
			prevDate = tours[i].l
			minCost = tours[i].cost
		}
		if minCost > tours[i].cost {
			minCost = tours[i].cost
		}
		res[i] = minCost
	}
	return res
}

package main

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

const (
	Inf = 2000000000
	MaxN = 200005
	MaxL = 20
)

type voucher struct {
	l, r, price int
}

func (v *voucher) size() int {
	return v.r - v.l + 1
}

var n, x int
var v []voucher
var rmq [MaxN][MaxL]int

func min(args ...int) int {
	a := args[0]
	for i := 1; i < len(args); i++ {
		if a > args[i] {
			a = args[i]
		}
	}
	return a
}

// gets the minimum from the interval [l; r]
func query(l, r int) int {
	pow := int(math.Log2(float64(r - l + 1)))
	return min(rmq[l][pow], rmq[r-pow][pow])
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &x)
	v = make([]voucher, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d %d\n", &v[i].l, &v[i].r, &v[i].price)
	}
	sort.Slice(v, func(i, j int) bool {
		if v[i].size() < v[j].size() {
			return true
		}
		if v[i].size() > v[j].size() {
			return false
		}
		return v[i].r < v[j].r
	})

	for i := 0; i < n; i++ {
		for j := 0; j < MaxL; j++ {
			rmq[i][j] = Inf
		}
	}
	for i := 0; i < n; i++ {
		rmq[i][0] = v[i].price
	}

	for j := uint(1); j < MaxL; j++ {
		if 1 << j > n {
			break
		}
		for i := 0; i < n; i++ {
			if (1 << (j - 1)) + i >= n {
				break
			}
			end := min(i + (1 << j), n)
			k := end - (1 << (j - 1))
			if k < i {
				break
			}
			rmq[i][j] = min(rmq[i][j-1], rmq[k][j-1])
		}
	}

	//fmt.Println(v)
	//for i := 0; i < n; i++ {
	//	fmt.Print(v[i].size(), " ")
	//}
	//fmt.Println()
	//for i := 0; i < n; i++ {
	//	fmt.Println(rmq[i][:10])
	//}

	ans := Inf
	for i := 0; i < n; i++ {
		val := x - v[i].size()
		// Fix the search size
		ind1 := sort.Search(n, func(i int) bool {
			return v[i].size() >= val
		})
		if ind1 == n || v[ind1].size() != val {
			continue
		}
		ind2 := sort.Search(n, func(i int) bool {
			return v[i].size() > val
		})

		// Another binary search to find where the right end becomes bigger
		// so we need to check for a minimum in the interval [ind1; ind2)
		ind3 := ind1 - 1 + sort.Search(ind2 - ind1, func(index int) bool {
			return v[ind1 + index].r >= v[i].l
		})
		//fmt.Println(">>", i, ind1, ind2, ind3)
		if ind3 < ind1 || v[ind3].r >= v[i].l {
			continue
		}
		newPrice := v[i].price + query(ind1, ind3)
		if newPrice < ans {
			ans = newPrice
		}
	}
	if ans == Inf {
		ans = -1
	}
	fmt.Println(ans)
}

package main

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

const (
	Inf = 2000000000
	MaxN = 200005
	MaxL = 20
)

type voucher struct {
	l, r, price int
}

func (v *voucher) size() int {
	return v.r - v.l + 1
}

var n, x int
var v []voucher
var rmq [MaxN][MaxL]int

func min(args ...int) int {
	a := args[0]
	for i := 1; i < len(args); i++ {
		if a > args[i] {
			a = args[i]
		}
	}
	return a
}

// gets the minimum from the interval [l; r]
func query(l, r int) int {
	pow := int(math.Log2(float64(r - l + 1)))
	return min(rmq[l][pow], rmq[r-pow][pow])
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &x)
	v = make([]voucher, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d %d\n", &v[i].l, &v[i].r, &v[i].price)
	}
	sort.Slice(v, func(i, j int) bool {
		if v[i].size() < v[j].size() {
			return true
		}
		if v[i].size() > v[j].size() {
			return false
		}
		return v[i].r < v[j].r
	})

	for i := 0; i < n; i++ {
		for j := 0; j < MaxL; j++ {
			rmq[i][j] = Inf
		}
	}
	for i := 0; i < n; i++ {
		rmq[i][0] = v[i].price
	}

	for j := uint(1); j < MaxL; j++ {
		if 1 << j > n {
			break
		}
		for i := 0; i < n; i++ {
			if (1 << (j - 1)) + i > n {
				break
			}
			end := min(i + (1 << j), n)
			k := end - (1 << (j - 1))
			if k < i {
				break
			}
			rmq[i][j] = min(rmq[i][j-1], rmq[k][j-1])
		}
	}

	//fmt.Println(v)
	//for i := 0; i < n; i++ {
	//	fmt.Print(v[i].size(), " ")
	//}
	//fmt.Println()
	//for i := 0; i < n; i++ {
	//	fmt.Println(rmq[i][:10])
	//}

	ans := Inf
	for i := 0; i < n; i++ {
		val := x - v[i].size()
		// Fix the search size
		ind1 := sort.Search(n, func(i int) bool {
			return v[i].size() >= val
		})
		if ind1 == n || v[ind1].size() != val {
			continue
		}
		ind2 := sort.Search(n, func(i int) bool {
			return v[i].size() > val
		})

		// Another binary search to find where the right end becomes bigger
		// so we need to check for a minimum in the interval [ind1; ind2)
		ind3 := ind1 - 1 + sort.Search(ind2 - ind1, func(index int) bool {
			return v[ind1 + index].r >= v[i].l
		})
		//fmt.Println(">>", i, ind1, ind2, ind3)
		if ind3 < ind1 || v[ind3].r >= v[i].l {
			continue
		}
		newPrice := v[i].price + query(ind1, ind3)
		if newPrice < ans {
			ans = newPrice
		}
	}
	if ans == Inf {
		ans = -1
	}
	fmt.Println(ans)
}

package main

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

const (
	Inf = 2000000000
	MaxN = 200005
	MaxL = 20
)

type voucher struct {
	l, r, price int
}

func (v *voucher) size() int {
	return v.r - v.l + 1
}

var n, x int
var v []voucher
var rmq [MaxN][MaxL]int

func min(args ...int) int {
	a := args[0]
	for i := 1; i < len(args); i++ {
		if a > args[i] {
			a = args[i]
		}
	}
	return a
}

// gets the minimum from the interval [l; r]
func query(l, r int) int {
	pow := int(math.Log2(float64(r - l + 1)))
	return min(rmq[l][pow], rmq[r-pow][pow])
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &x)
	v = make([]voucher, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d %d\n", &v[i].l, &v[i].r, &v[i].price)
	}
	sort.Slice(v, func(i, j int) bool {
		if v[i].size() < v[j].size() {
			return true
		}
		if v[i].size() > v[j].size() {
			return false
		}
		return v[i].r < v[j].r
	})

	for i := 0; i < n; i++ {
		for j := 0; j < MaxL; j++ {
			rmq[i][j] = Inf
		}
	}
	for i := 0; i < n; i++ {
		rmq[i][0] = v[i].price
	}

	for j := uint(1); j < MaxL; j++ {
		if 1 << j > n {
			break
		}
		for i := 0; i < n; i++ {
			if (1 << (j - 1)) + i >= n {
				break
			}
			end := min(i + (1 << j), n)
			k := end - (1 << (j - 1))
			if k < i {
				break
			}
			rmq[i][j] = min(rmq[i][j-1], rmq[k][j-1])
		}
	}

	//fmt.Println(v)
	//for i := 0; i < n; i++ {
	//	fmt.Print(v[i].size(), " ")
	//}
	//fmt.Println()
	//for i := 0; i < n; i++ {
	//	fmt.Println(rmq[i][:10])
	//}

	ans := Inf
	for i := 0; i < n; i++ {
		val := x - v[i].size()
		// Fix the search size
		ind1 := sort.Search(n, func(i int) bool {
			return v[i].size() >= val
		})
		if ind1 == n || v[ind1].size() != val {
			continue
		}
		ind2 := sort.Search(n, func(i int) bool {
			return v[i].size() > val
		})

		// Another binary search to find where the right end becomes bigger
		// so we need to check for a minimum in the interval [ind1; ind2)
		q := v[ind1:ind2]
		ind3 := sort.Search(len(q), func(index int) bool {
			return q[index].r >= v[i].l
		})
		//fmt.Println(">>", i, ind1, ind2, ind3)
		if ind3 == len(q) {
			ind3 = ind2 - 1
		} else {
			ind3 = ind1 + ind3 - 1
			if ind3 < ind1 {
				continue
			}
		}
		newPrice := v[i].price + query(ind1, ind3)
		if newPrice < ans {
			ans = newPrice
		}
	}
	if ans == Inf {
		ans = -1
	}
	fmt.Println(ans)
}

package main

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

const (
	Inf = 2000000000
	MaxN = 200005
	MaxL = 20
)

type voucher struct {
	l, r, price int
}

func (v *voucher) size() int {
	return v.r - v.l + 1
}

var n, x int
var v []voucher
var rmq [MaxN][MaxL]int

func min(args ...int) int {
	a := args[0]
	for i := 1; i < len(args); i++ {
		if a > args[i] {
			a = args[i]
		}
	}
	return a
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &x)
	v = make([]voucher, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d %d\n", &v[i].l, &v[i].r, &v[i].price)
	}
	sort.Slice(v, func(i, j int) bool {
		if v[i].size() < v[j].size() {
			return true
		}
		if v[i].size() > v[j].size() {
			return false
		}
		return v[i].r < v[j].r
	})

	for i := 0; i < n; i++ {
		for j := 0; j < MaxL; j++ {
			rmq[i][j] = Inf
		}
	}
	for i := 0; i < n; i++ {
		rmq[i][0] = v[i].price
	}

	for j := uint(1); j < MaxL; j++ {
		if 1 << j > n {
			break
		}
		for i := 0; i < n; i++ {
			end := min(i + (1 << j), n)
			k := end - (1 << j) + 1
			if k < i {
				break
			}
			rmq[i][j] = min(rmq[i][j-1], rmq[k][j-1])
		}
	}

	ans := Inf
	for i := 0; i < n; i++ {
		val := x - v[i].size()
		// Fix the search size
		ind1 := sort.Search(n, func(i int) bool {
			return v[i].size() >= val
		})
		if ind1 == n || v[ind1].size() != val {
			continue
		}
		ind2 := sort.Search(n, func(i int) bool {
			return v[i].size() > val
		})

		// Another binary search to find where the right end becomes bigger
		// so we need to check for a minimum in the interval [ind1; ind3)
		ind3 := ind1 + sort.Search(ind2 - ind1, func(i int) bool {
			return v[i].r > v[i].r
		})
		l := 0
		if ind2 != ind3 {
			l = int(math.Log2(float64(ind3) - float64(ind2)))
		}
		newPrice := v[i].price + rmq[ind1][l]
		if newPrice < ans {
			ans = newPrice
		}
	}
	if ans == Inf {
		ans = -1
	}
	fmt.Println(ans)
}

package main

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

const (
	Inf = 2000000000
	MaxN = 200005
	MaxL = 20
)

type voucher struct {
	l, r, price int
}

func (v *voucher) size() int {
	return v.r - v.l + 1
}

var n, x int
var v []voucher
var rmq [MaxN][MaxL]int

func min(args ...int) int {
	a := args[0]
	for i := 1; i < len(args); i++ {
		if a > args[i] {
			a = args[i]
		}
	}
	return a
}

// gets the minimum from the interval [l; r]
func query(l, r int) int {
	if l == r {
		return rmq[l][0]
	}
	pow := int(math.Log2(float64(r - l + 1)))
	return min(rmq[l][pow], rmq[r-pow][pow])
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &x)
	v = make([]voucher, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d %d\n", &v[i].l, &v[i].r, &v[i].price)
	}
	sort.Slice(v, func(i, j int) bool {
		if v[i].size() < v[j].size() {
			return true
		}
		if v[i].size() > v[j].size() {
			return false
		}
		return v[i].r < v[j].r
	})

	for i := 0; i < n; i++ {
		for j := 0; j < MaxL; j++ {
			rmq[i][j] = Inf
		}
	}
	for i := 0; i < n; i++ {
		rmq[i][0] = v[i].price
	}

	for j := uint(1); j < MaxL; j++ {
		if 1 << j > n {
			break
		}
		for i := 0; i < n; i++ {
			if (1 << (j - 1)) + i >= n {
				break
			}
			end := min(i + (1 << j), n)
			k := end - (1 << (j - 1))
			if k < i {
				break
			}
			rmq[i][j] = min(rmq[i][j-1], rmq[k][j-1])
		}
	}

	//fmt.Println(v)
	//for i := 0; i < n; i++ {
	//	fmt.Print(v[i].size(), " ")
	//}
	//fmt.Println()
	//for i := 0; i < n; i++ {
	//	fmt.Println(rmq[i][:10])
	//}

	ans := Inf
	for i := 0; i < n; i++ {
		val := x - v[i].size()
		// Fix the search size
		ind1 := sort.Search(n, func(i int) bool {
			return v[i].size() >= val
		})
		if ind1 == n || v[ind1].size() != val {
			continue
		}
		ind2 := sort.Search(n, func(i int) bool {
			return v[i].size() > val
		})

		// Another binary search to find where the right end becomes bigger
		// so we need to check for a minimum in the interval [ind1; ind2)
		ind3 := ind1 - 1 + sort.Search(ind2 - ind1, func(index int) bool {
			return v[ind1 + index].r >= v[i].l
		})
		//fmt.Println(">>", i, ind1, ind2, ind3)
		if ind3 < ind1 || v[ind3].r >= v[i].l {
			continue
		}
		newPrice := v[i].price + query(ind1, ind3)
		if newPrice < ans {
			ans = newPrice
		}
	}
	if ans == Inf {
		ans = -1
	}
	fmt.Println(ans)
}

package main

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

const (
	Inf = 2000000000
	MaxN = 200005
	MaxL = 20
)

type voucher struct {
	l, r, price int
}

func (v *voucher) size() int {
	return v.r - v.l + 1
}

var n, x int
var v []voucher
var rmq [MaxN][MaxL]int

func min(args ...int) int {
	a := args[0]
	for i := 1; i < len(args); i++ {
		if a > args[i] {
			a = args[i]
		}
	}
	return a
}

// gets the minimum from the interval [l; r]
func query(l, r int) int {
	pow := int(math.Log2(float64(r - l + 1)))
	return min(rmq[l][pow], rmq[r-pow][pow])
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &x)
	v = make([]voucher, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d %d\n", &v[i].l, &v[i].r, &v[i].price)
	}
	sort.Slice(v, func(i, j int) bool {
		if v[i].size() < v[j].size() {
			return true
		}
		if v[i].size() > v[j].size() {
			return false
		}
		return v[i].r < v[j].r
	})

	for i := 0; i < n; i++ {
		for j := 0; j < MaxL; j++ {
			rmq[i][j] = Inf
		}
	}
	for i := 0; i < n; i++ {
		rmq[i][0] = v[i].price
	}

	for j := uint(1); j < MaxL; j++ {
		if 1 << j > n {
			break
		}
		for i := 0; i < n; i++ {
			if (1 << (j - 1)) + i >= n {
				break
			}
			end := min(i + (1 << j), n)
			k := end - (1 << (j - 1))
			if k < i {
				break
			}
			rmq[i][j] = min(rmq[i][j-1], rmq[k][j-1])
		}
	}

	//fmt.Println(v)
	//for i := 0; i < n; i++ {
	//	fmt.Print(v[i].size(), " ")
	//}
	//fmt.Println()
	//for i := 0; i < n; i++ {
	//	fmt.Println(rmq[i][:10])
	//}

	ans := Inf
	for i := 0; i < n; i++ {
		val := x - v[i].size()
		// Fix the search size
		ind1 := sort.Search(n, func(i int) bool {
			return v[i].size() >= val
		})
		if ind1 == n || v[ind1].size() != val {
			continue
		}
		ind2 := sort.Search(n, func(i int) bool {
			return v[i].size() > val
		})

		// Another binary search to find where the right end becomes bigger
		// so we need to check for a minimum in the interval [ind1; ind3)
		ind3 := ind1 + sort.Search(ind2 - ind1, func(index int) bool {
			return v[index].r >= v[i].l
		})
		if ind1 == ind3 {
			// every right end is bigger than or equal to the searched left index
			continue
		}
		newPrice := v[i].price + query(ind1, ind3 - 1)
		if newPrice < ans {
			ans = newPrice
		}
	}
	if ans == Inf {
		ans = -1
	}
	fmt.Println(ans)
}

package main

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

const (
	Inf = 2000000000
	MaxN = 200005
	MaxL = 20
)

type voucher struct {
	l, r, price int
}

func (v *voucher) size() int {
	return v.r - v.l + 1
}

var n, x int
var v []voucher
var rmq [MaxN][MaxL]int

func min(args ...int) int {
	a := args[0]
	for i := 1; i < len(args); i++ {
		if a > args[i] {
			a = args[i]
		}
	}
	return a
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &x)
	v = make([]voucher, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d %d\n", &v[i].l, &v[i].r, &v[i].price)
	}
	sort.Slice(v, func(i, j int) bool {
		if v[i].size() < v[j].size() {
			return true
		}
		if v[i].size() > v[j].size() {
			return false
		}
		return v[i].r < v[j].r
	})

	for i := 0; i < n; i++ {
		for j := 0; j < MaxL; j++ {
			rmq[i][j] = Inf
		}
	}
	for i := 0; i < n; i++ {
		rmq[i][0] = v[i].price
	}

	for j := uint(1); j < MaxL; j++ {
		if 1 << j > n {
			break
		}
		for i := 0; i < n; i++ {
			if (1 << (j - 1)) + i >= n {
				break
			}
			end := min(i + (1 << j), n)
			k := end - (1 << (j - 1))
			if k < i {
				break
			}
			rmq[i][j] = min(rmq[i][j-1], rmq[k][j-1])
		}
	}

	//fmt.Println(v)
	//for i := 0; i < n; i++ {
	//	fmt.Println(rmq[i][:10])
	//}

	ans := Inf
	for i := 0; i < n; i++ {
		val := x - v[i].size()
		// Fix the search size
		ind1 := sort.Search(n, func(i int) bool {
			return v[i].size() >= val
		})
		if ind1 == n || v[ind1].size() != val {
			continue
		}
		ind2 := sort.Search(n, func(i int) bool {
			return v[i].size() > val
		})

		// Another binary search to find where the right end becomes bigger
		// so we need to check for a minimum in the interval [ind1; ind3)
		ind3 := ind1 + sort.Search(ind2 - ind1, func(index int) bool {
			return v[index].r >= v[i].l
		})
		if ind1 == ind3 {
			continue
		}
		l := int(math.Log2(float64(ind3) - float64(ind1)))
		//fmt.Println(i, ind1, ind2, ind3)
		newPrice := v[i].price + rmq[ind1][l]
		if newPrice < ans {
			ans = newPrice
			//fmt.Println(">>", i, ind1, ind2, ind3)
		}
	}
	if ans == Inf {
		ans = -1
	}
	fmt.Println(ans)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gi2() (int,int) { return gi(),gi() }
func gi3() (int,int,int) { return gi(),gi(),gi() }
func gi4() (int,int,int,int) { return gi(),gi(),gi(),gi() }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func gf() float64 { f,e := strconv.ParseFloat(gs(),64); if e != nil {panic(e)}; return f }
func gbs() []byte { return []byte(gs()) }
func gfs(n int) []float64  { res := make([]float64,n); for i:=0;i<n;i++ { res[i] = gf() }; return res }
func gss(n int) []string  { res := make([]string,n); for i:=0;i<n;i++ { res[i] = gs() }; return res }
func ia(m int) []int { return make([]int,m) }
func iai(m int,v int) []int { a := make([]int,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi(n int,m int,v int) [][]int {
	r := make([][]int,n); for i:=0;i<n;i++ { x := make([]int,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill2(m int) ([]int,[]int) { a,b := ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i] = gi(),gi()}; return a,b }
func fill3(m int) ([]int,[]int,[]int) { a,b,c := ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi(),gi(),gi()}; return a,b,c }
func fill4(m int) ([]int,[]int,[]int,[]int) { a,b,c,d := ia(m),ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi(),gi(),gi(),gi()}; return a,b,c,d }
func abs(a int) int { if a < 0 { return -a }; return a }
func rev(a []int) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max(a,b int) int { if a > b { return a }; return b }
func min(a,b int) int { if a > b { return b }; return a }
func tern(cond bool, a int, b int) int { if cond { return a }; return b }
func terns(cond bool, a string, b string) string { if cond { return a }; return b }
func maxarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr(a []int) int { ans := 0; for _,aa := range(a) { ans += aa }; return ans }
func zeroarr(a []int) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod(a,e,mod int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint(a,e int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd(a,b int) int { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended(a,b int) (int,int,int) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv(a,m int) (int,bool) { g,x,_ := gcdExtended(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func makefact(n int,mod int) ([]int,[]int) {
	fact,factinv := make([]int,n+1),make([]int,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * i % mod }
	factinv[n] = powmod(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * (i+1) % mod }
	return fact,factinv
}
func vecintstring(a []int) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.Itoa(a) }; return strings.Join(astr," ") }
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	gi(); // N
	M := gi()
	// First M queries, we get the value of each of the edges
	sarr := make([]byte,M); for i:=0;i<M;i++ { sarr[i] = '0' }
	type edge struct {idx,v int }
	edges := make([]edge,0,M)
	for i:=0;i<M;i++ {
		sarr[i] = '1'
		s := string(sarr)
		fmt.Fprintf(wrtr,"? %v\n",s); wrtr.Flush()
		val := gi()
		edges = append(edges,edge{i,val})
		sarr[i] = '0'
	}
	sort.Slice(edges,func(i,j int) bool { return edges[i].v < edges[j].v })
	ans := 0
	for _,e := range edges {
		sarr[e.idx] = '1'
		s := string(sarr)
		fmt.Fprintf(wrtr,"? %v\n",s); wrtr.Flush()
		val := gi()
		if ans + e.v != val { sarr[e.idx] = '0' } else { ans += e.v }
	}
	fmt.Fprintf(wrtr,"! %v\n",ans); wrtr.Flush()
}

package main

import (
	"fmt"
	"sort"
)

var (
	n int
	m int
)

type edge struct {
	w, id int
}

func query(s string) int {
	fmt.Println("? ", s)
	var x int
	fmt.Scanln(&x)
	return x
}

func main() {
	fmt.Scanln(&n, &m)
	runes := make([]rune, m)
	for i := 0; i < m; i++ {
		runes[i] = '0'
	}
	val := make([]edge, 0, m)

	for i := 0; i < m; i++ {
		runes[i] = '1'
		val = append(val, edge{query(string(runes)), i})
		runes[i] = '0'
	}
	sort.Slice(val, func(i, j int) bool {
		return val[i].w < val[j].w
	})
	mst := 0
	for _, ed := range val {
		w := ed.w
		id := ed.id
		runes[id] = '1'
		L := query(string(runes))
		if L == mst+w {
			mst += w
		} else {
			runes[id] = '0'
		}
	}
	fmt.Println("! ", mst)
}

package main

import (
	"fmt"
	"sort"
)

var (
	n int
	m int
)

type edge struct {
	w, id int
}

func query(s string) int {
	fmt.Println("? ", s)
	var x int
	fmt.Scanln(&x)
	return x
}

func main() {
	fmt.Scanln(&n, &m)
	runes := make([]rune, m)
	for i := 0; i < m; i++ {
		runes[i] = '0'
	}
	val := make([]edge, 0, m)

	for i := 0; i < m; i++ {
		runes[i] = '1'
		val = append(val, edge{query(string(runes)), i})
		runes[i] = '0'
	}
	sort.Slice(val, func(i, j int) bool {
		return val[i].w > val[j].w
	})
	mst := 0
	for _, ed := range val {
		w := ed.w
		id := ed.id
		runes[id] = '1'
		L := query(string(runes))
		if L == mst+w {
			mst += w
		} else {
			runes[id] = '0'
		}
	}
	fmt.Println("! ", mst)
}

package main

import (
	"fmt"
	"sort"
)

var (
	n int
	m int
)

type edge struct {
	w, id int
}

func query(s string) int {
	fmt.Println("? ", s)
	var x int
	fmt.Scanln(&x)
	return x
}

func main() {
	fmt.Scanln(&n, &m)
	runes := make([]rune, m)
	for i := 0; i < m; i++ {
		runes[i] = '0'
	}
	val := make([]edge, m)
	for i := 0; i < m; i++ {
		runes[i] = '1'
		val = append(val, edge{query(string(runes)), i})
		runes[i] = '0'
	}
	sort.Slice(val, func(i, j int) bool {
		return val[i].w > val[j].w
	})
	mst := 0
	for _, ed := range val {
		w := ed.w
		id := ed.id
		runes[id] = '1'
		L := query(string(runes))
		if L == mst+w {
			mst += w
		} else {
			runes[id] = '0'
		}
	}
	fmt.Println("! ", mst)
}


package main

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

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

var T int
var x, y int64

func absInt(x int64) int64 {
	if x >= 0 {
		return x
	}
	return -x
}

func minInt(x, y, z int64) int64 {
	if x <= y && x <= z {
		return x
	}
	if y <= x && y <= z {
		return y

	}
	return z
}

func main() {
	for _, _ = fmt.Fscan(_r, &T); T > 0; T-- {
		_, _ = fmt.Fscan(_r, &x, &y)
		c:=make([]int64,6)
		for i := 0; i < 6; i++ {
			_, _ = fmt.Fscan(_r, &c[i])
		}

		var len1, len2, len3 int64
		if x >= 0 {
			len1 += absInt(x) * c[0]
		} else {
			len1 += absInt(x) * c[3]
		}
		if y >= 0 {
			len2 += absInt(y) * c[0]
			len3 += absInt(y) * c[1]
		} else {
			len2 += absInt(y) * c[3]
			len3 += absInt(y) * c[4]
		}
		if (y - x) >= 0 {
			len1 += absInt(y-x) * c[1]
		} else {
			len1 += absInt(y-x) * c[4]
		}

		if (x - y) >= 0 {
			len2 += absInt(x-y) * c[5]
		} else {
			len2 += absInt(x-y) * c[2]
		}

		if x >= 0 {
			len3 += absInt(x) * c[5]
		} else {
			len3 += absInt(x) * c[2]
		}
		//fmt.Println(len1,len2,len3)

		_,_=fmt.Fprintln(_w,minInt(len1,len2,len3))
		_=_w.Flush()

	}
}

package main

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

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

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--
		dest := readNNums(reader, 2)
		C := readNNums(reader, 6)
		res := solve(dest, C)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}
	fmt.Print(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

var dx = []int64{1, 1, 0, -1, -1, 0}
var dy = []int64{1, 0, -1, -1, 0, 1}

func solve(dest []int, C []int) int64 {
	x, y := int64(dest[1]), int64(dest[0])

	var calc func(i, j int) int64
	calc = func(i, j int) int64 {
		if i == j {
			if dx[i] != 0 {
				a := x / dx[i]
				if a > 0 && a*dx[i] == x && a*dy[i] == y {
					return a * int64(C[i])
				}
				return math.MaxInt64
			}
			// dy[i] != 0
			b := y / dy[i]
			if b > 0 && b*dx[i] == x && b*dy[i] == y {
				return b * int64(C[i])
			}
			return math.MaxInt64
		}
		if i > j {
			if j+3 == i {
				return math.MaxInt64
			}
		} else {
			if i+3 == j {
				return math.MaxInt64
			}
		}
		// a, b => a * dx[i], a * dy[i] => x1, y1
		// x1 + b * dx[j], y1+ b * dy[j] => x, y
		// a * dx[i] + b * dx[j] = x
		// a * dy[i] + b * dy[j] = y
		var a, b int64
		if dx[i] == 0 {
			b = x / dx[j]
			a = (y - b*dy[j]) / dy[i]

		}
		if dx[j] == 0 {
			a = x / dx[i]
			b = (y - a*dy[i]) / dy[j]

		}
		if dy[i] == 0 {
			b = y / dy[j]
			a = (x - b*dx[j]) / dx[i]

		}
		// dy[j] == 0
		if dy[j] == 0 {
			a = y / dy[i]
			b = (x - a*dx[i]) / dx[j]

		}
		if a < 0 || b < 0 {
			return math.MaxInt64
		}
		return a*int64(C[i]) + b*int64(C[j])
	}

	var best int64 = math.MaxInt64

	for i := 0; i < 6; i++ {
		for j := 0; j < 6; j++ {
			tmp := calc(i, j)
			if tmp < best {
				best = tmp
			}
		}
	}
	return best
}

package main

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

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

var T int
var x, y int64

func absInt(x int64) int64 {
	if x >= 0 {
		return x
	}
	return -x
}

func minInt(x, y, z int64) int64 {
	if x <= y && x <= z {
		return x
	}
	if y <= x && y <= z {
		return y

	}
	return z
}

func main() {
	for _, _ = fmt.Fscan(_r, &T); T > 0; T-- {
		_, _ = fmt.Fscan(_r, &x, &y)
		c:=make([]int64,6)
		for i := 0; i < 6; i++ {
			_, _ = fmt.Fscan(_r, &c[i])
		}

		var wg sync.WaitGroup
		var len1, len2, len3 int64

		wg.Add(1)
		go func() {
			defer wg.Done()
			if x >= 0 {
				len1 += absInt(x) * c[0]
			} else {
				len1 += absInt(x) * c[3]
			}
		}()

		wg.Add(1)
		go func() {
			defer wg.Done()
			if y >= 0 {
				len2 += absInt(y) * c[0]
				len3 += absInt(y) * c[1]
			} else {
				len2 += absInt(y) * c[3]
				len3 += absInt(y) * c[4]
			}
		}()

		wg.Add(1)
		go func() {
			defer wg.Done()
			if (y - x) >= 0 {
				len1 += absInt(y-x) * c[1]
			} else {
				len1 += absInt(y-x) * c[4]
			}
		}()

		wg.Add(1)
		go func() {
			defer wg.Done()
			if (x - y) >= 0 {
				len2 += absInt(x-y) * c[5]
			} else {
				len2 += absInt(x-y) * c[2]
			}
		}()

		wg.Add(1)
		go func() {
			defer wg.Done()
			if x >= 0 {
				len3 += absInt(x) * c[5]
			} else {
				len3 += absInt(x) * c[2]
			}
		}()

		//fmt.Println(len1,len2,len3)

		wg.Wait()

		_,_=fmt.Fprintln(_w,minInt(len1,len2,len3))
		_=_w.Flush()
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1421D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}

	var T int
	var x, y, c1, c2, c3, c4, c5, c6 int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &x, &y, &c1, &c2, &c3, &c4, &c5, &c6)
		if x < 0 {
			x, y, c1, c2, c3, c4, c5, c6 = -x, -y, c4, c5, c6, c1, c2, c3
		}
		if y > x {
			c1 = min(c1, c2+c6)
			c2 = min(c2, c1+c3)
			Fprintln(out, x*c1+(y-x)*c2)
		} else if y > 0 {
			x, y, c2, c3, c5, c6 = y, x, c6, c5, c3, c2
			c1 = min(c1, c2+c6)
			c2 = min(c2, c1+c3)
			Fprintln(out, x*c1+(y-x)*c2)
		} else {
			c6 = min(c6, c1+c5)
			c5 = min(c5, c6+c4)
			Fprintln(out, x*c6-y*c5)
		}
	}
}

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

package main

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

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

var T, x, y int

func absInt(x int) int {
	if x >= 0 {
		return x
	}
	return -x
}

func minInt(x, y, z int) int {
	if x <= y && x <= z {
		return x
	}
	if y <= x && y <= z {
		return y

	}
	return z
}

func main() {
	for _, _ = fmt.Fscan(_r, &T); T > 0; T-- {
		_, _ = fmt.Fscan(_r, &x, &y)
		c:=make([]int,6)
		for i := 0; i < 6; i++ {
			_, _ = fmt.Fscan(_r, &c[i])
		}

		var len1, len2, len3 int
		if x >= 0 {
			len1 += absInt(x) * c[0]
		} else {
			len1 += absInt(x) * c[3]
		}
		if y >= 0 {
			len2 += absInt(y) * c[0]
			len3 += absInt(y) * c[1]
		} else {
			len2 += absInt(y) * c[3]
			len3 += absInt(y) * c[4]
		}
		if (y - x) >= 0 {
			len1 += absInt(y-x) * c[1]
		} else {
			len1 += absInt(y-x) * c[4]
		}

		if (x - y) >= 0 {
			len2 += absInt(x-y) * c[5]
		} else {
			len2 += absInt(x-y) * c[2]
		}

		if x >= 0 {
			len3 += absInt(x) * c[5]
		} else {
			len3 += absInt(x) * c[2]
		}
		//fmt.Println(len1,len2,len3)

		_,_=fmt.Fprintln(_w,minInt(len1,len2,len3))
		_=_w.Flush()

	}
}