You have $$$n$$$ gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The $$$i$$$-th gift consists of $$$a_i$$$ candies and $$$b_i$$$ oranges.During one move, you can choose some gift $$$1 \le i \le n$$$ and do one of the following operations:  eat exactly one candy from this gift (decrease $$$a_i$$$ by one);  eat exactly one orange from this gift (decrease $$$b_i$$$ by one);  eat exactly one candy and exactly one orange from this gift (decrease both $$$a_i$$$ and $$$b_i$$$ by one). Of course, you can not eat a candy or orange if it's not present in the gift (so neither $$$a_i$$$ nor $$$b_i$$$ can become less than zero).As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: $$$a_1 = a_2 = \dots = a_n$$$ and $$$b_1 = b_2 = \dots = b_n$$$ (and $$$a_i$$$ equals $$$b_i$$$ is not necessary).Your task is to find the minimum number of moves required to equalize all the given gifts.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of gifts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the number of candies in the $$$i$$$-th gift. The third line of the test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the number of oranges in the $$$i$$$-th gift.

NoteIn the first test case of the example, we can perform the following sequence of moves:  choose the first gift and eat one orange from it, so $$$a = [3, 5, 6]$$$ and $$$b = [2, 2, 3]$$$;  choose the second gift and eat one candy from it, so $$$a = [3, 4, 6]$$$ and $$$b = [2, 2, 3]$$$;  choose the second gift and eat one candy from it, so $$$a = [3, 3, 6]$$$ and $$$b = [2, 2, 3]$$$;  choose the third gift and eat one candy and one orange from it, so $$$a = [3, 3, 5]$$$ and $$$b = [2, 2, 2]$$$;  choose the third gift and eat one candy from it, so $$$a = [3, 3, 4]$$$ and $$$b = [2, 2, 2]$$$;  choose the third gift and eat one candy from it, so $$$a = [3, 3, 3]$$$ and $$$b = [2, 2, 2]$$$.

package main

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

func main(){
	var t,n int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		fmt.Fscan(in,&n)
		a := make([]int64, n)
		b := make([]int64, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &a[j])
		}
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &b[j])
		}
		mina := min(a)
		minb := min(b)
		count := int64(0)
		for j := 0; j < n; j++ {
			da := a[j]-mina
			db := b[j]-minb
			count += max(da,db)
		}
		fmt.Println(count)
	}

}

func min(a []int64) int64{
	x := a[0]
	for i:=1;i<len(a);i++{
		if x>a[i]{
			x = a[i]
		}
	}
	return x
}
func max(a,b int64)int64{
	if a>b{
		return a
	}
	return b
}

package main

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

const MaxN int = 50 + 5

type Gift struct {
	a int64
	b int64
}

var read = bufio.NewReader(os.Stdin)
var write = bufio.NewWriter(os.Stdout)
var gift [MaxN]Gift

func main() {
	defer write.Flush()
	var t int
	fmt.Fscan(read, &t)
	for ; t > 0; t-- {
		var n int
		fmt.Fscan(read, &n)
		var minA, minB int64 = 1e9, 1e9
		for i := 0; i < n; i++ {
			fmt.Fscan(read, &gift[i].a)
			minA = min(minA, gift[i].a)
		}
		for i := 0; i < n; i++ {
			fmt.Fscan(read, &gift[i].b)
			minB = min(minB, gift[i].b)
		}
		var ans int64 = 0
		for i := 0; i < n; i++ {
			ans += max(gift[i].a-minA, gift[i].b-minB)
		}
		fmt.Fprintln(write, ans)
	}
}

func max(x int64, y int64) int64 {
	if x < y {
		return y
	} else {
		return x
	}
}

func min(x int64, y int64) int64 {
	if x < y {
		return x
	} else {
		return y
	}
}

package main

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

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

	T:= 0
	for Fscan(in, &T); T > 0; T-- {
		var n int
		Fscan(in, &n)
		a:=make([]int,n)
		b:=make([]int,n)

		a1:=2000000000
		a2:=2000000000

		for i:=0;i<n;i++{
			Fscan(in,&a[i])
			if a1>a[i]{
				a1=a[i];
			}
		}

		for i:=0;i<n;i++{
			Fscan(in,&b[i])
			if a2>b[i]{
				a2=b[i];
			}
		}
		ans:=int64(0)

		for i:=0;i<n;i++{
			c1,c2:=a[i]-a1,b[i]-a2
			if c1<c2{
				ans+=int64(c2)
			} else {
				ans+=int64(c1)
			}
		}

		Fprintln(out,ans)
	}
}

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

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 i := 0; i < t; i++ {

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

		minA := uint64(1e9 + 1)
		a := make([]uint64, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &a[j])
			if minA > a[j] {
				minA = a[j]
			}
		}

		minB := uint64(1e9 + 1)
		b := make([]uint64, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &b[j])
			if minB > b[j] {
				minB = b[j]
			}
		}

		r := uint64(0)
		for j := 0; j < n; j++ {
			r += max(a[j]-minA, b[j]-minB)
		}

		fmt.Fprintln(out, r)

	}

}

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

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	t, err := strconv.Atoi(scanner.Text())
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		scanner.Scan()
		g, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		candies := numbers(scanner.Text())
		scanner.Scan()
		oranges := numbers(scanner.Text())
		fmt.Println(sol(g, candies, oranges))
	}
}

func numbers(s string) []int64 {
	var n []int64
	for _, f := range strings.Fields(s) {
		i, err := strconv.ParseInt(f, 10, 64)
		if err == nil {
			n = append(n, i)
		}
	}
	return n
}

func sol(n int, c, o []int64) int64 {
	mc := c[0]
	mo := o[0]
	for i := range c {
		mc = min(mc, c[i])
		mo = min(mo, o[i])
	}
	var ans int64
	for i := range c {
		dc := c[i] - mc
		do := o[i] - mo
		ans += max(dc, do)
	}
	return ans
}

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

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

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

package main

import (
    "fmt"
    "math"
)

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

func main() {
    var t int
    fmt.Scan(&t)
    for t > 0 {
        var n int
        fmt.Scan(&n)
        a := make([]int, n)
        b := make([]int, n)
        for i := 0; i < n; i++ {
            fmt.Scan(&a[i])
        }
        for i := 0; i < n; i++ {
            fmt.Scan(&b[i])
        }

        x := math.MaxInt32
        y := math.MaxInt32
        for i := 0; i < n; i++ {
            if x > a[i] {
                x = a[i]
            }
            if y > b[i] {
                y = b[i]
            }
        }
        var answer int64
        answer = 0
        for i := 0; i < n; i++ {
            dx := a[i] - x
            dy := b[i] - y
            answer += int64(max(dx, dy))
        }

        fmt.Println(answer)

        t--
    }
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		n := io.NextInt()
		a, b := io.NextInts(n), io.NextInts(n)
		ma, mb := math.MaxInt32, math.MaxInt32
		for i, x := range a {
			if x < ma {
				ma = x
			}
			y := b[i]
			if y < mb {
				mb = y
			}
		}
		var ans int64
		for i := range a {
			d := a[i] - ma
			if d < b[i]-mb {
				d = b[i] - mb
			}
			ans += int64(d)
		}
		io.Println(ans)
	}
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, f.c[0])
	}
	return string(s)
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(' ', x)
		}
	}
}

func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}

package main

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

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

	input := func() uint64 {
		scanner.Scan()
		i, _ := strconv.ParseUint(scanner.Text(), 10, 64)
		return i
	}

	for t := input(); t > 0; t-- {
		n := input()

		a := make([]uint64, n)
		b := make([]uint64, n)

		for i := range a {
			a[i] = input()
		}

		for i := range b {
			b[i] = input()
		}

		var mina, minb uint64
		mina = math.MaxUint64
		minb = math.MaxUint64

		var i uint64
		for i = 0; i < n; i++ {
			if mina > a[i] {
				mina = a[i]
			}

			if minb > b[i] {
				minb = b[i]
			}
		}

		var moves uint64
		max := func(a, b uint64) uint64 {
			if a > b {
				return a
			}

			return b
		}

		for i = 0; i < n; i++ {
			diffa := a[i] - mina
			diffb := b[i] - minb

			moves += max(diffa, diffb)
		}

		fmt.Println(moves)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int64
	fmt.Scan(&t)

	a := [50]int64{}
	b := [50]int64{}

	for ; t > 0; t-- {
		var n int
		fmt.Scan(&n)

		mina := int64(1000000000)
		minb := int64(1000000000)

		for i := 0; i < n; i++ {
			fmt.Scan(&a[i])
			if a[i] < mina {
				mina = a[i]
			}
		}
		for i := 0; i < n; i++ {
			fmt.Scan(&b[i])
			if b[i] < minb {
				minb = b[i]
			}
		}

		opt := int64(0)
		for i := 0; i < n; i++ {
			if a[i]-mina < b[i]-minb {
				opt += b[i] - minb
			} else {
				opt += a[i] - mina
			}
		}

		fmt.Println(opt)
	}
}

package main

import "fmt"

func main() {
    var t, n int64
    fmt.Scan(&t)
    for ; t > 0; t-- {
        fmt.Scan(&n)
        var a, b []int64
        var ans, i int64
        for i = 0; i < n; i++ {
            var x int64
            fmt.Scan(&x)
            a = append(a, x)
        }
        for i = 0; i < n; i++ {
            var x int64
            fmt.Scan(&x)
            b = append(b, x)
        }
        mina := a[0]
        minb := b[0]
        for i = 1; i < n; i++ {
            if a[i] < mina {
                mina = a[i]
            }
            if b[i] < minb {
                minb = b[i]
            }
        }
        for i = 0; i < n; i++ {
            if a[i] - mina > b[i] - minb {
                ans += a[i] - mina
            } else {
                ans += b[i] - minb
            }
        }
        fmt.Println(ans)
    }
}

package main

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

var t int

const mx = 1000000009

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &t)

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

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

		b := make([]int, n)
		minB := mx
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &b[i])
			if b[i] < minB {
				minB = b[i]
			}
		}

		var ans int64
		for i := 0; i < n; i++ {
			aa := a[i] - minA
			bb := b[i] - minB

			if aa > bb {
				ans += int64(aa)
			} else {
				ans += int64(bb)
			}
		}

		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
)

func nxt() int {
	var x int
	fmt.Scan(&x)
	return x
}

func ok() {
	fmt.Println("YES")
}

func no() {
	fmt.Println("NO")
}

func count(a []int) []int{
	var mn int = 1e9 + 7
	var n = len(a)
	for i := 0; i < n; i++ {
		if mn > a[i] {
			mn = a[i]
		}
	}
	buf := []int{}
	for i := 0; i < n; i++ {
		buf = append(buf, a[i] - mn)
	}
	return buf
}

func solve() {
	n := nxt()
	a := make([]int, n)
	b := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = nxt()
	}
	for i := 0; i < n; i++ {
		b[i] = nxt()
	}

	var buf1 = count(a)
	var buf2 = count(b)
	var ans int64 = 0
	for i := 0; i < n; i++ {
		mn := buf1[i]
		mx := buf2[i]
		if mn > mx {
			mn, mx = mx, mn
		}
		ans += int64(mn)
		ans += int64(mx - mn)
	}
	fmt.Println(ans)
}

func main() {
	var t int = nxt()
	for t > 0 {
		t--
		solve()
	}
	return
}

package main

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

func countActions(a []present, mo, mc int64) int64 {

	var count int64 = 0

	for i := range a {
		to := float64(a[i].orange - mo)
		tc := float64(a[i].candy - mc)

		count += int64(math.Max(to, tc))
	}

	return count
}

type present struct {
	candy int64
	orange int64
}

func main() {
	var n, t int
	var s string
	fmt.Scan(&t)

	for k:=0; k<t; k++ {
		fmt.Scan(&n)

		var r = make([]present, n)
		var max_orange int64 = 1000000000
		var max_candy int64 = 1000000000
		for i:=0; i<n; i++ {
			fmt.Scan(&s)
			m, _ := strconv.Atoi(s)
			r[i].orange = int64(m)
			if int64(m) < max_orange {
				max_orange = int64(m)
			}
		}
		for i:=0; i<n; i++ {
			fmt.Scan(&s)
			m, _ := strconv.Atoi(s)
			r[i].candy = int64(m)
			if int64(m) < max_candy {
				max_candy = int64(m)
			}
		}

		fmt.Println(countActions(r, max_orange, max_candy))
	}
}

package main

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

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

func solver(ag, bg []int64) int64 {
	aSort := make([]int64, len(ag))
	bSort := make([]int64, len(bg))
	copy(aSort, ag)
	copy(bSort, bg)
	sort.Slice(aSort, func(i, j int) bool {
		return aSort[i] < aSort[j]
	})
	sort.Slice(bSort, func(i, j int) bool {
		return bSort[i] < bSort[j]
	})
	aMin, bMin := aSort[0], bSort[0]

	counter := int64(0)
	for i := range ag {
		aNeed, bNeed := ag[i]-aMin, bg[i]-bMin
		if aNeed < bNeed {
			counter += bNeed
		} else {
			counter += aNeed
		}
	}
	return counter
}

func temp() {
	defer writer.Flush()
	ag := []int64{1, 3}
	bg := []int64{2, 5}
	fmt.Fprintln(writer, solver(ag, bg))
}

func main() {
	defer writer.Flush()
	var t, length int64
	var ag, bg []int64
	var text string
	var split []string
	fmt.Fscanf(reader, "%d\n", &t)
	for i := int64(0); i < t; i++ {
		fmt.Fscanf(reader, "%d\n", &length)
		ag, bg = make([]int64, length), make([]int64, length)
		text, _ = reader.ReadString('\n')
		split = strings.Fields(text)
		for j, v := range split {
			ag[j], _ = strconv.ParseInt(v, 10, 64)
		}
		text, _ = reader.ReadString('\n')
		split = strings.Fields(text)
		for j, v := range split {
			bg[j], _ = strconv.ParseInt(v, 10, 64)
		}
		fmt.Fprintln(writer, solver(ag, bg))
	}
}

package main

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

//Task -
type Task struct {
	Candies []int64
	Oranges []int64
}

func min(a []int64) int64 {
	m := a[0]
	for _, i := range a {
		if i < m {
			m = i
		}
	}
	return m
}

//Solve -
func (t *Task) Solve() int64 {
	actions := int64(0)
	minCandies := min(t.Candies)
	minOranges := min(t.Oranges)
	for i, c := range t.Candies {
		candydiff := c - minCandies
		orangediff := t.Oranges[i] - minOranges
		if candydiff < orangediff {
			actions = actions + orangediff
		} else {
			actions = actions + candydiff
		}
	}
	return actions
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	counter := 0
	// tasksAmount := 0
	tasks := []Task{}
	_ = scanner.Scan()
	for scanner.Scan() {

		var currentTask Task

		//Инициируем новое задание
		_ = scanner.Text()
		_ = scanner.Scan()

		//Заполняем новое задание
		currentTask = Task{
			Candies: []int64{},
		}
		text := scanner.Text()
		_ = scanner.Scan()
		for _, i := range strings.Split(text, " ") {
			a, _ := strconv.Atoi(i)
			currentTask.Candies = append(currentTask.Candies, int64(a))
		}
		// fmt.Print64ln(currentTask)
		// tasks = append(tasks, currentTask)

		// var currentTask Task
		//Заполняем новое задание
		// currentTask = Task{
		// 	Oranges: []int64{},
		// }
		currentTask.Oranges = []int64{}
		text = scanner.Text()
		// _ = scanner.Scan()
		for _, i := range strings.Split(text, " ") {
			a, _ := strconv.Atoi(i)
			currentTask.Oranges = append(currentTask.Oranges, int64(a))
		}
		tasks = append(tasks, currentTask)

		counter++
	}

	for _, t := range tasks {
		// fmt.Print64ln(t)
		fmt.Println(t.Solve())
	}
}

package main

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

var (
	w *bufio.Writer
	r *bufio.Reader
)

func readArray(a []int) {
	//fmt.Print(r);
	for i:=0; i<len(a); i++ {
		fmt.Fscanf(r, "%d", &a[i]);
	}
	fmt.Fscanf(r, "\n");
}

func getMin(a []int) int {
	var res int;
	for i, val :=  range a {
		if i == 0 || res > val {
			res = val;
		}
	}
	return res;
}

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

func main() {
//	dat,_ := os.Open("input.txt")
	r = bufio.NewReader(os.Stdin)
    w = bufio.NewWriter(os.Stdout)
    defer w.Flush()

	/*var a, b int;
	fmt.Fscanf(r, "%d %d", &a, &b);
	fmt.Fprintf(w, "%d %d", a, b);
	return;*/

	var t int;

	fmt.Fscanf(r, "%d\n", &t);
	for i:=0; i<t; i++ {
		//fmt.Print(i);
		var n int;
		fmt.Fscanf(r, "%d\n", &n);
		//fmt.Print(n);
		a := make([]int, n);
		b := make([]int, n);
		readArray(a);
		readArray(b);
		//fmt.Print(a);
		//fmt.Print(b);
		mina := getMin(a);
		minb := getMin(b);
		var res int64 = 0;
		for j:=0; j<len(a);j++{
				//var dif1 int = a[i] - mina;
				//var dif2 int = b[i] - minb;
				res += int64(Max(a[j] - mina, b[j] - minb));
		}
		fmt.Fprintf(w, "%d\n", res);
	}
}

package main

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

// https://codeforces.com/problemset/problem/1399/B
// B. Gifts Fixing
// time limit per test
// 1 second
// memory limit per test
// 256 megabytes
// input
// standard input
// output
// standard output

// You have n
// gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of ai candies and bi

// oranges.

// During one move, you can choose some gift 1≤i≤n

// and do one of the following operations:

//     eat exactly one candy from this gift (decrease ai

// by one);
// eat exactly one orange from this gift (decrease bi
// by one);
// eat exactly one candy and exactly one orange from this gift (decrease both ai
// and bi

//     by one).

// Of course, you can not eat a candy or orange if it's not present in the gift (so neither ai
// nor bi

// can become less than zero).

// As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: a1=a2=⋯=an
// and b1=b2=⋯=bn (and ai equals bi

// is not necessary).

// Your task is to find the minimum number of moves required to equalize all the given gifts.

// You have to answer t

// independent test cases.
// Input

// The first line of the input contains one integer t
// (1≤t≤1000) — the number of test cases. Then t

// test cases follow.

// The first line of the test case contains one integer n
// (1≤n≤50) — the number of gifts. The second line of the test case contains n integers a1,a2,…,an (1≤ai≤109), where ai is the number of candies in the i-th gift. The third line of the test case contains n integers b1,b2,…,bn (1≤bi≤109), where bi is the number of oranges in the i

// -th gift.
// Output

// For each test case, print one integer: the minimum number of moves required to equalize all the given gifts.

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

	var t int
	_, _ = fmt.Fscan(bufStdin, &t)

	for i := 0; i < t; i++ {
		var i uint64
		var n uint64
		_, _ = fmt.Fscan(bufStdin, &n)

		as := make([]uint64, n)
		for i = 0; i < n; i++ {
			_, _ = fmt.Fscan(bufStdin, &as[i])
		}

		bs := make([]uint64, n)
		for i = 0; i < n; i++ {
			_, _ = fmt.Fscan(bufStdin, &bs[i])
		}

		// we must reduce the values in as to the min of the values, e.g. [4, 5, 6] -> [4, 4, 4], this is 3 moves
		// same for the bs array
		candyTarget := min(as)
		orangeTarget := min(bs)

		var nSteps uint64
		for i = 0; i < n; i++ {
			nSteps += max([]uint64{as[i] - candyTarget, bs[i] - orangeTarget})
		}

		_, _ = fmt.Fprintln(bufStdout, nSteps)
	}

}

func min(vs []uint64) uint64 {
	m := vs[0]
	for i := 1; i < len(vs); i++ {
		if vs[i] < m {
			m = vs[i]
		}
	}
	return m
}

func max(vs []uint64) uint64 {
	m := vs[0]
	for i := 1; i < len(vs); i++ {
		if vs[i] > m {
			m = vs[i]
		}
	}
	return m
}

package main

import (
	"fmt"
	"strings"
)

type gifts struct {
	n int
	a []int
	b []int
}

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

// https://codeforces.com/problemset/problem/1399/B
// комментарий к решению
// Т.к. требуется арифметика с числами, то используем fmt.Scan для считывания массива.
// Для вывода воспользуемся fmt.Sprint переведя массив ответов в строку.
// Т.к. fmt.Sprint выводит данные через пробел, то задействуем strings.Replace
// для вывода ответов по одному на строку.
// Компилятор видит, что заменяется 1 однобайтовый символ unicode на 1 однобайтовый символ unicode,
// плюс мы указываем кол-во замен, поэтому будет сгенерирован оптимальный по памяти код,
// как если бы мы производили свою арифметику с []byte
func taskSolution(in []gifts) string {
	ans := make([]int64, len(in))
	for i := 0; i < len(in); i += 1 {
		n, a, b := in[i].n, in[i].a, in[i].b
		min_a, min_b := a[0], b[0]
		for j := 1; j < n; j += 1 {
			if a[j] < min_a {
				min_a = a[j]
			}
			if b[j] < min_b {
				min_b = b[j]
			}
		}
		for j := 0; j < n; j += 1 {
			ans[i] += int64(max(a[j]-min_a, b[j]-min_b))
		}
	}
	res := fmt.Sprint(ans)
	return strings.Replace(res[1:len(res)-1], " ", "\n", len(ans)-1)
}

func main() {
	var t int
	if _, err := fmt.Scan(&t); err != nil {
		panic(err)
	}

	in := make([]gifts, 0, t)
	var n, elem int
	for i := 0; i < t; i += 1 {
		if _, err := fmt.Scan(&n); err != nil {
			panic(err)
		}
		a := make([]int, 0, n)
		for j := 0; j < n; j += 1 {
			if _, err := fmt.Scan(&elem); err != nil {
				panic(err)
			}
			a = append(a, elem)
		}
		b := make([]int, 0, n)
		for j := 0; j < n; j += 1 {
			if _, err := fmt.Scan(&elem); err != nil {
				panic(err)
			}
			b = append(b, elem)
		}
		in = append(in, gifts{n: n, a: a, b: b})
	}

	fmt.Println(taskSolution(in))
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

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

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

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

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

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

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

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

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

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

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

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

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n := sint64()
		a := make([]int64, n)
		for i := range a {
			a[i] = sint64()
		}
		b := make([]int64, n)
		for i := range b {
			b[i] = sint64()
		}
		printf("%d\n", sol(n, a, b))
	}
}

func sol(n int64, a, b []int64) int64 {
	minA := min(a[0], a[1:]...)
	minB := min(b[0], b[1:]...)
	ret := int64(0)
	for i := int64(0); i < n; i++ {
		ret += max(a[i]-minA, b[i]-minB)
	}
	return ret
}

package main

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

func main(){
	var t,n int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		fmt.Fscan(in,&n)
		a := make([]int, n)
		b := make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &a[j])
		}
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &b[j])
		}
		mina := min(a)
		minb := min(b)
		count :=0
		for j := 0; j < n; j++ {
			da := a[j]-mina
			db := b[j]-minb
			count += max(da,db)
		}
		fmt.Println(count)
	}

}

func min(a []int) int{
	x := a[0]
	for i:=1;i<len(a);i++{
		if x>a[i]{
			x = a[i]
		}
	}
	return x
}
func max(a,b int)int{
	if a>b{
		return a
	}
	return b
}

package main

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

const MaxN int = 50 + 5

type Gift struct {
	a int
	b int
}

var read = bufio.NewReader(os.Stdin)
var write = bufio.NewWriter(os.Stdout)
var gift [MaxN]Gift

func main() {
	defer write.Flush()
	var t int
	fmt.Fscan(read, &t)
	for ; t > 0; t-- {
		var n int
		fmt.Fscan(read, &n)
		var minA, minB int = 1e9, 1e9
		for i := 0; i < n; i++ {
			fmt.Fscan(read, &gift[i].a)
			minA = min(minA, gift[i].a)
		}
		for i := 0; i < n; i++ {
			fmt.Fscan(read, &gift[i].b)
			minB = min(minB, gift[i].b)
		}
		var ans int = 0
		for i := 0; i < n; i++ {
			ans += max(gift[i].a-minA, gift[i].b-minB)
		}
		fmt.Fprintln(write, ans)
	}
}

func max(x int, y int) int {
	if x < y {
		return y
	} else {
		return x
	}
}

func min(x int, y int) int {
	if x < y {
		return x
	} else {
		return y
	}
}

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 i := 0; i < t; i++ {

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

		minA := uint(1e9 + 1)
		a := make([]uint, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &a[j])
			if minA > a[j] {
				minA = a[j]
			}
		}

		minB := uint(1e9 + 1)
		b := make([]uint, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &b[j])
			if minB > b[j] {
				minB = b[j]
			}
		}

		r := uint(0)
		for j := 0; j < n; j++ {
			r += max(a[j]-minA, b[j]-minB)
		}

		fmt.Fprintln(out, r)

	}

}

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

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 i := 0; i < t; i++ {

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

		minA := int(1e9 + 1)
		a := make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &a[j])
			if minA > a[j] {
				minA = a[j]
			}
		}

		minB := int(1e9 + 1)
		b := make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &b[j])
			if minB > b[j] {
				minB = b[j]
			}
		}

		r := 0
		for j := 0; j < n; j++ {
			r += max(a[j]-minA, b[j]-minB)
		}

		fmt.Fprintln(out, r)

	}

}

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

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	t, err := strconv.Atoi(scanner.Text())
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		scanner.Scan()
		g, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		candies := numbers(scanner.Text())
		scanner.Scan()
		oranges := numbers(scanner.Text())
		fmt.Println(sol(g, candies, oranges))
	}
}

func numbers(s string) []int {
	var n []int
	for _, f := range strings.Fields(s) {
		i, err := strconv.Atoi(f)
		if err == nil {
			n = append(n, i)
		}
	}
	return n
}

func sol(n int, c, o []int) int {
	mc := c[0]
	mo := o[0]
	for i := range c {
		mc = min(mc, c[i])
		mo = min(mo, o[i])
	}
	ans := 0
	for i := range c {
		dc := c[i] - mc
		do := o[i] - mo
		ans += max(dc, do)
	}
	return ans
}

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

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

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

package main

import (
    "fmt"
    "math"
)

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

func main() {
    var t int
    fmt.Scan(&t)
    for t > 0 {
        var n int
        fmt.Scan(&n)
        a := make([]int, n)
        b := make([]int, n)
        for i := 0; i < n; i++ {
            fmt.Scan(&a[i])
        }
        for i := 0; i < n; i++ {
            fmt.Scan(&b[i])
        }

        x := math.MaxInt32
        y := math.MaxInt32
        for i := 0; i < n; i++ {
            if x > a[i] {
                x = a[i]
            }
            if y > b[i] {
                y = b[i]
            }
        }
        answer := 0
        for i := 0; i < n; i++ {
            dx := a[i] - x
            dy := b[i] - y
            answer += max(dx, dy)
        }

        fmt.Println(answer)

        t--
    }
}

package main

import (
    "fmt"
)

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

func main() {
    var t int
    fmt.Scan(&t)
    for t > 0 {
        var n int
        fmt.Scan(&n)
        a := make([]int, n)
        b := make([]int, n)
        for i := 0; i < n; i++ {
            fmt.Scan(&a[i])
        }
        for i := 0; i < n; i++ {
            fmt.Scan(&b[i])
        }

        x := 1000000001
        y := 1000000001
        for i := 0; i < n; i++ {
            if x > a[i] {
                x = a[i]
            }
            if y > b[i] {
                y = b[i]
            }
        }
        answer := 0
        for i := 0; i < n; i++ {
            dx := a[i] - x
            dy := b[i] - y
            answer += max(dx, dy)
        }

        fmt.Println(answer)

        t--
    }
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		n := io.NextInt()
		a, b := io.NextInts(n), io.NextInts(n)
		ma, mb := math.MaxInt32, math.MaxInt32
		for i, x := range a {
			if x < ma {
				ma = x
			}
			y := b[i]
			if y < mb {
				mb = y
			}
		}
		ans := 0
		for i := range a {
			d := a[i] - ma
			if d < b[i]-mb {
				d = b[i] - mb
			}
			ans += d
		}
		io.Println(ans)
	}
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, f.c[0])
	}
	return string(s)
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(' ', x)
		}
	}
}

func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}

package main

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

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

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

	for t := input(); t > 0; t-- {
		n := input()

		a := make([]int, n)
		b := make([]int, n)

		for i := range a {
			a[i] = input()
		}

		for i := range b {
			b[i] = input()
		}

		mina := 100000000 + 1
		minb := 100000000 + 1

		for i := 0; i < n; i++ {
			if mina > a[i] {
				mina = a[i]
			}

			if minb > b[i] {
				minb = b[i]
			}
		}

		moves := 0
		max := func(a, b int) int {
			if a > b {
				return a
			}

			return b
		}

		for i := 0; i < n; i++ {
			diffa := a[i] - mina
			diffb := b[i] - minb

			moves += max(diffa, diffb)
		}

		fmt.Println(moves)
	}
}

package main

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

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

	input := func() uint64 {
		scanner.Scan()
		i, _ := strconv.ParseUint(scanner.Text(), 10, 64)
		return i
	}

	for t := input(); t > 0; t-- {
		n := input()

		a := make([]uint64, n)
		b := make([]uint64, n)

		for i := range a {
			a[i] = input()
		}

		for i := range b {
			b[i] = input()
		}

		var mina, minb uint64
		mina = 100000000 + 1
		minb = 100000000 + 1

		var i uint64
		for i = 0; i < n; i++ {
			if mina > a[i] {
				mina = a[i]
			}

			if minb > b[i] {
				minb = b[i]
			}
		}

		var moves uint64
		max := func(a, b uint64) uint64 {
			if a > b {
				return a
			}

			return b
		}

		for i = 0; i < n; i++ {
			diffa := a[i] - mina
			diffb := b[i] - minb

			moves += max(diffa, diffb)
		}

		fmt.Println(moves)
	}
}

package main

import (
	"fmt"
	"math"
)

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

	a := [50]int{}
	b := [50]int{}

	for ; t > 0; t-- {
		var n int
		fmt.Scan(&n)

		mina := math.MaxInt32
		minb := math.MaxInt32

		for i := 0; i < n; i++ {
			fmt.Scan(&a[i])
			if a[i] < mina {
				mina = a[i]
			}
		}
		for i := 0; i < n; i++ {
			fmt.Scan(&b[i])
			if b[i] < minb {
				minb = b[i]
			}
		}

		opt := 0
		for i := 0; i < n; i++ {
			if a[i]-mina < b[i]-minb {
				opt += b[i] - minb
			} else {
				opt += a[i] - mina
			}
		}

		fmt.Println(opt)
	}
}

package main

import "fmt"

func main() {
    var t int64
    var n int64
    fmt.Scan(&t)
    for ; t > 0; t-- {
        fmt.Scan(&n)
        var a []int64
        var b []int64
        var ans int64
        var i int64
        for i = 0; i < n; i++ {
            var x int64
            fmt.Scan(x)
            a = append(a, x)
        }
        for i = 0; i < n; i++ {
            var x int64
            fmt.Scan(x)
            b = append(b, x)
        }
        mina := a[0]
        minb := b[0]
        for i = 1; i < n; i++ {
            if a[i] < mina {
                mina = a[i]
            }
            if b[i] < minb {
                minb = b[i]
            }
        }
        for i = 0; i < n; i++ {
            if a[i] - mina > b[i] - minb {
                ans += a[i] - mina
            } else {
                ans += b[i] - minb
            }
        }
        fmt.Println(ans)
    }
}

package main

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

var t int

const mx = 1000000009

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &t)

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

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

		b := make([]int, n)
		minB := mx
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &b[i])
			if b[i] < minB {
				minB = b[i]
			}
		}

		ans := 0
		for i := 0; i < n; i++ {
			aa := a[i] - minA
			bb := b[i] - minB

			if aa > bb {
				ans += aa
			} else {
				ans += bb
			}
		}

		fmt.Println(ans)
	}
}

package main

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

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

func solver(ag, bg []int64) int64 {
	aSort := make([]int64, len(ag))
	bSort := make([]int64, len(bg))
	copy(aSort, ag)
	copy(bSort, bg)
	sort.Slice(aSort, func(i, j int) bool {
		return aSort[i] < aSort[j]
	})
	sort.Slice(bSort, func(i, j int) bool {
		return bSort[i] < bSort[j]
	})
	aMin, bMin := aSort[0], bSort[0]

	counter := int64(0)
	for i := range ag {
		aNeed, bNeed := ag[i]-aMin, bg[i]-bMin
		if aNeed < bNeed {
			counter += bNeed
		} else {
			counter += aNeed
		}
	}
	return counter
}

func main() {
	defer writer.Flush()
	ag := []int64{1, 3}
	bg := []int64{2, 5}
	fmt.Fprintln(writer, solver(ag, bg))
}

func temp() {
	defer writer.Flush()
	var t, length int64
	var ag, bg []int64
	var text string
	var split []string
	fmt.Fscanf(reader, "%d\n", &t)
	for i := int64(0); i < t; i++ {
		fmt.Fscanf(reader, "%d\n", &length)
		ag, bg = make([]int64, length), make([]int64, length)
		text, _ = reader.ReadString('\n')
		split = strings.Fields(text)
		for j, v := range split {
			ag[j], _ = strconv.ParseInt(v, 10, 64)
		}
		text, _ = reader.ReadString('\n')
		split = strings.Fields(text)
		for j, v := range split {
			bg[j], _ = strconv.ParseInt(v, 10, 64)
		}
		fmt.Fprintln(writer, solver(ag, bg))
	}
}

package main

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

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

func solver(ag, bg []int) int {
	aSort := make([]int, len(ag))
	bSort := make([]int, len(bg))
	copy(aSort, ag)
	copy(bSort, bg)
	sort.Slice(aSort, func(i, j int) bool {
		return aSort[i] < aSort[j]
	})
	sort.Slice(bSort, func(i, j int) bool {
		return bSort[i] < bSort[j]
	})
	aMin, bMin := aSort[0], bSort[0]

	counter := 0
	for i := range ag {
		aNeed, bNeed := ag[i]-aMin, bg[i]-bMin
		if aNeed < bNeed {
			counter += bNeed
		} else {
			counter += aNeed
		}
	}
	return counter
}

func test() {
	defer writer.Flush()
	ag := []int{1, 2, 3, 4, 5}
	bg := []int{5, 4, 3, 2, 1}
	fmt.Fprintln(writer, solver(ag, bg))
}

func main() {
	defer writer.Flush()
	var t, length int
	var ag, bg []int
	var text string
	var split []string
	fmt.Fscanf(reader, "%d\n", &t)
	for i := 0; i < t; i++ {
		fmt.Fscanf(reader, "%d\n", &length)
		ag, bg = make([]int, length), make([]int, length)
		text, _ = reader.ReadString('\n')
		split = strings.Fields(text)
		for j, v := range split {
			ag[j], _ = strconv.Atoi(v)
		}
		text, _ = reader.ReadString('\n')
		split = strings.Fields(text)
		for j, v := range split {
			bg[j], _ = strconv.Atoi(v)
		}
		fmt.Fprintln(writer, solver(ag, bg))
	}
}

package main

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

//Task -
type Task struct {
	Candies []int
	Oranges []int
}

func min(a []int) int {
	m := a[0]
	for _, i := range a {
		if i < m {
			m = i
		}
	}
	return m
}

//Solve -
func (t *Task) Solve() int {
	actions := 0
	minCandies := min(t.Candies)
	minOranges := min(t.Oranges)
	for i, c := range t.Candies {
		candydiff := c - minCandies
		orangediff := t.Oranges[i] - minOranges
		if candydiff < orangediff {
			actions = actions + orangediff
		} else {
			actions = actions + candydiff
		}
	}
	return actions
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	counter := 0
	// tasksAmount := 0
	tasks := []Task{}
	_ = scanner.Scan()
	for scanner.Scan() {

		var currentTask Task

		//Инициируем новое задание
		_ = scanner.Text()
		_ = scanner.Scan()

		//Заполняем новое задание
		currentTask = Task{
			Candies: []int{},
		}
		text := scanner.Text()
		_ = scanner.Scan()
		for _, i := range strings.Split(text, " ") {
			a, _ := strconv.Atoi(i)
			currentTask.Candies = append(currentTask.Candies, a)
		}
		// fmt.Println(currentTask)
		// tasks = append(tasks, currentTask)

		// var currentTask Task
		//Заполняем новое задание
		// currentTask = Task{
		// 	Oranges: []int{},
		// }
		currentTask.Oranges = []int{}
		text = scanner.Text()
		// _ = scanner.Scan()
		for _, i := range strings.Split(text, " ") {
			a, _ := strconv.Atoi(i)
			currentTask.Oranges = append(currentTask.Oranges, a)
		}
		tasks = append(tasks, currentTask)

		counter++
	}

	for _, t := range tasks {
		// fmt.Println(t)
		fmt.Println(t.Solve())
	}
}

package main

import (
	"fmt"
	)

func readArray(a []int) {
	for i:=0; i<len(a); i++ {
		fmt.Scanf("%d", &a[i]);
	}
}

func getMin(a []int) int {
	var res int;
	for i, val :=  range a {
		if i == 0 || res > val {
			res = val;
		}
	}
	return res;
}

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

func main() {
	var t int;

	fmt.Scanf("%d", &t);
	for i:=0; i<t; i++ {
		//fmt.Print(i);
		var n int;
		fmt.Scanf("%d", &n);
		//fmt.Print(n);
		a := make([]int, n);
		b := make([]int, n);
		readArray(a);
		readArray(b);
		//fmt.Print(a);
		//fmt.Print(b);
		mina := getMin(a);
		minb := getMin(b);
		var res int64 = 0;
		for j:=0; j<len(a);j++{
				//var dif1 int = a[i] - mina;
				//var dif2 int = b[i] - minb;
				res += int64(Max(a[j] - mina, b[j] - minb));
		}
		fmt.Printf("%d\n", res);
	}
}

package main

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

var (
	w *bufio.Writer
	r *bufio.Reader
)

func readArray(a []int) {
	//fmt.Print(r);
	for i:=0; i<len(a); i++ {
		fmt.Fscanf(r, "%d", &a[i]);
	}
}

func getMin(a []int) int {
	var res int;
	for i, val :=  range a {
		if i == 0 || res > val {
			res = val;
		}
	}
	return res;
}

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

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

	var t int;

	fmt.Fscanf(r, "%d", &t);
	for i:=0; i<t; i++ {
		//fmt.Print(i);
		var n int;
		fmt.Fscanf(r, "%d", &n);
		//fmt.Print(n);
		a := make([]int, n);
		b := make([]int, n);
		readArray(a);
		readArray(b);
		//fmt.Print(a);
		//fmt.Print(b);
		mina := getMin(a);
		minb := getMin(b);
		var res int64 = 0;
		for j:=0; j<len(a);j++{
				//var dif1 int = a[i] - mina;
				//var dif2 int = b[i] - minb;
				res += int64(Max(a[j] - mina, b[j] - minb));
		}
		fmt.Fprintf(w, "%d\n", res);
	}
}

package main

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

var (
	w *bufio.Writer
	r *bufio.Reader
)

func readArray(a []int) {
	//fmt.Print(r);
	for i:=0; i<len(a); i++ {
		fmt.Fscanf(r, "%d", &a[i]);
	}
}

func getMin(a []int) int {
	var res int;
	for i, val :=  range a {
		if i == 0 || res > val {
			res = val;
		}
	}
	return res;
}

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

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

	var t int;

	fmt.Fscanf(r, "%d", &t);
	for i:=0; i<t; i++ {
		//fmt.Print(i);
		var n int;
		fmt.Fscanf(r, "%d", &n);
		//fmt.Print(n);
		a := make([]int, n);
		b := make([]int, n);
		readArray(a);
		readArray(b);
		//fmt.Print(a);
		//fmt.Print(b);
		mina := getMin(a);
		minb := getMin(b);
		var res int64 = 0;
		for j:=0; j<len(a);j++{
				//var dif1 int = a[i] - mina;
				//var dif2 int = b[i] - minb;
				res += int64(Max(a[j] - mina, b[j] - minb));
		}
		fmt.Fprint(w, res, "\n");
	}
}

package main

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

// https://codeforces.com/problemset/problem/1399/B
// B. Gifts Fixing
// time limit per test
// 1 second
// memory limit per test
// 256 megabytes
// input
// standard input
// output
// standard output

// You have n
// gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of ai candies and bi

// oranges.

// During one move, you can choose some gift 1≤i≤n

// and do one of the following operations:

//     eat exactly one candy from this gift (decrease ai

// by one);
// eat exactly one orange from this gift (decrease bi
// by one);
// eat exactly one candy and exactly one orange from this gift (decrease both ai
// and bi

//     by one).

// Of course, you can not eat a candy or orange if it's not present in the gift (so neither ai
// nor bi

// can become less than zero).

// As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: a1=a2=⋯=an
// and b1=b2=⋯=bn (and ai equals bi

// is not necessary).

// Your task is to find the minimum number of moves required to equalize all the given gifts.

// You have to answer t

// independent test cases.
// Input

// The first line of the input contains one integer t
// (1≤t≤1000) — the number of test cases. Then t

// test cases follow.

// The first line of the test case contains one integer n
// (1≤n≤50) — the number of gifts. The second line of the test case contains n integers a1,a2,…,an (1≤ai≤109), where ai is the number of candies in the i-th gift. The third line of the test case contains n integers b1,b2,…,bn (1≤bi≤109), where bi is the number of oranges in the i

// -th gift.
// Output

// For each test case, print one integer: the minimum number of moves required to equalize all the given gifts.

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

	var t int
	_, _ = fmt.Fscan(bufStdin, &t)

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

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

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

		// we must reduce the values in as to the min of the values, e.g. [4, 5, 6] -> [4, 4, 4], this is 3 moves
		// same for the bs array
		candyTarget := min(as)
		orangeTarget := min(bs)

		var nSteps int
		for i := 0; i < n; i++ {
			nSteps += max([]int{as[i] - candyTarget, bs[i] - orangeTarget})
		}

		_, _ = fmt.Fprintln(bufStdout, nSteps)
	}

}

func min(vs []int) int {
	m := vs[0]
	for i := 1; i < len(vs); i++ {
		if vs[i] < m {
			m = vs[i]
		}
	}
	return m
}

func max(vs []int) int {
	m := vs[0]
	for i := 1; i < len(vs); i++ {
		if vs[i] > m {
			m = vs[i]
		}
	}
	return m
}

package main

import (
	"fmt"
	"strings"
)

type gifts struct {
	n int
	a []int
	b []int
}

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

// https://codeforces.com/problemset/problem/1399/B
// комментарий к решению
// Т.к. требуется арифметика с числами, то используем fmt.Scan для считывания массива.
// Для вывода воспользуемся fmt.Sprint переведя массив ответов в строку.
// Т.к. fmt.Sprint выводит данные через пробел, то задействуем strings.Replace
// для вывода ответов по одному на строку.
// Компилятор видит, что заменяется 1 однобайтовый символ unicode на 1 однобайтовый символ unicode,
// плюс мы указываем кол-во замен, поэтому будет сгенерирован оптимальный по памяти код,
// как если бы мы производили свою арифметику с []byte
func taskSolution(in []gifts) string {
	ans := make([]int, len(in))
	for i := 0; i < len(in); i += 1 {
		n, a, b := in[i].n, in[i].a, in[i].b
		min_a, min_b := a[0], b[0]
		for j := 1; j < n; j += 1 {
			if a[j] < min_a {
				min_a = a[j]
			}
			if b[j] < min_b {
				min_b = b[j]
			}
		}
		for j := 0; j < n; j += 1 {
			ans[i] += max(a[j]-min_a, b[j]-min_b)
		}
	}
	res := fmt.Sprint(ans)
	return strings.Replace(res[1:len(res)-1], " ", "\n", len(ans)-1)
}

func main() {
	var t int
	if _, err := fmt.Scan(&t); err != nil {
		panic(err)
	}

	in := make([]gifts, 0, t)
	var n, elem int
	for i := 0; i < t; i += 1 {
		if _, err := fmt.Scan(&n); err != nil {
			panic(err)
		}
		a := make([]int, 0, n)
		for j := 0; j < n; j += 1 {
			if _, err := fmt.Scan(&elem); err != nil {
				panic(err)
			}
			a = append(a, elem)
		}
		b := make([]int, 0, n)
		for j := 0; j < n; j += 1 {
			if _, err := fmt.Scan(&elem); err != nil {
				panic(err)
			}
			b = append(b, elem)
		}
		in = append(in, gifts{n: n, a: a, b: b})
	}

	fmt.Println(taskSolution(in))
}


You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:   inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;  rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively). Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.Write program to process given sequence of operations.

The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.

For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).

package main

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

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	defer w.Flush()
	for I(&n) == nil {
		solve(n)
	}
}

var n int
var inf int
var tree []stree

func solve(n int) {
	inf = 1e9 * 2
	var a int
	tree = make([]stree, n*4)
	for i := 0; i < n; i++ {
		I(&a)
		update(i, i, 0, n-1, 1, a)
	}
	var m int
	I(&m)
	r.ReadLine()
	for i := 0; i < m; i++ {
		oo, _, _ := r.ReadLine()
		o := strings.Split(string(oo), " ")
		l, _ := strconv.Atoi(o[0])
		r, _ := strconv.Atoi(o[1])
		if len(o) == 2 {
			if l <= r {
				O(query(l, r, 0, n-1, 1), "\n")
			} else {
				O(min(query(l, n-1, 0, n-1, 1), query(0, r, 0, n-1, 1)), "\n")
			}
		} else if len(o) == 3 {
			value, _ := strconv.Atoi(o[2])
			if l <= r {
				update(l, r, 0, n-1, 1, value)
			} else {
				update(l, n-1, 0, n-1, 1, value)
				update(0, r, 0, n-1, 1, value)
			}
		}
	}
}

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

type stree struct {
	value, lazy int
}

func query(l, r, ll, rr, pos int) int {
	push(ll, rr, pos)
	if ll > r || rr < l {
		return inf
	}
	if l <= ll && rr <= r {
		return tree[pos].value
	}
	mid := (ll + rr) / 2
	return min(query(l, r, ll, mid, pos*2), query(l, r, mid+1, rr, pos*2+1))
}

func update(l, r, ll, rr, pos, value int) {
	push(ll, rr, pos)
	if ll > r || rr < l {
		return
	}
	if l <= ll && rr <= r {
		tree[pos].lazy += value
		push(ll, rr, pos)
		return
	}
	mid := (ll + rr) / 2
	update(l, r, ll, mid, pos*2, value)
	update(l, r, mid+1, rr, pos*2+1, value)
	tree[pos].value = min(tree[pos*2].value, tree[pos*2+1].value)
}

func push(l, r, pos int) {
	if tree[pos].lazy == 0 {
		return
	}
	if l != r {
		tree[pos*2].lazy += tree[pos].lazy
		tree[pos*2+1].lazy += tree[pos].lazy
	}
	tree[pos].value += tree[pos].lazy
	tree[pos].lazy = 0
}

package main

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

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	defer w.Flush()
	for I(&n) == nil {
		solve(n)
	}
}

var n int
var inf int
var a []int
var tree []stree

func solve(n int) {
	inf = 1e9 * 2
	a = make([]int, n)
	tree = make([]stree, n*4)
	for i := 0; i < n; i++ {
		I(&a[i])
		update(i, i, 0, n-1, 1, a[i])
	}
	var m int
	I(&m)
	r.ReadLine()
	for i := 0; i < m; i++ {
		oo, _, _ := r.ReadLine()
		o := strings.Split(string(oo), " ")
		l, _ := strconv.Atoi(o[0])
		r, _ := strconv.Atoi(o[1])
		if len(o) == 2 {
			if l <= r {
				O(query(l, r, 0, n-1, 1), "\n")
			} else {
				O(min(query(l, n-1, 0, n-1, 1), query(0, r, 0, n-1, 1)), "\n")
			}
		} else if len(o) == 3 {
			value, _ := strconv.Atoi(o[2])
			if l <= r {
				update(l, r, 0, n-1, 1, value)
			} else {
				update(l, n-1, 0, n-1, 1, value)
				update(0, r, 0, n-1, 1, value)
			}
		}
	}
}

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

type stree struct {
	value, lazy int
}

func query(l, r, ll, rr, pos int) int {
	work(ll, rr, pos)
	if ll > r || rr < l {
		return inf
	}
	if l <= ll && rr <= r {
		return tree[pos].value
	}
	mid := (ll + rr) / 2
	return min(query(l, r, ll, mid, pos*2), query(l, r, mid+1, rr, pos*2+1))
}

func update(l, r, ll, rr, pos, value int) {
	work(ll, rr, pos)
	if ll > r || rr < l {
		return
	}
	if l <= ll && rr <= r {
		tree[pos].lazy += value
		work(ll, rr, pos)
		return
	}
	mid := (ll + rr) / 2
	update(l, r, ll, mid, pos*2, value)
	update(l, r, mid+1, rr, pos*2+1, value)
	tree[pos].value = min(tree[pos*2].value, tree[pos*2+1].value)
}

func work(l, r, pos int) {
	if tree[pos].lazy == 0 {
		return
	}
	if l != r {
		tree[pos*2].lazy += tree[pos].lazy
		tree[pos*2+1].lazy += tree[pos].lazy
	}
	tree[pos].value += tree[pos].lazy
	tree[pos].lazy = 0
}

package main

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

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	defer w.Flush()
	for I(&n) == nil {
		solve(n)
	}
}

var n int
var a, b, tree []int

func solve(n int) {
	a = make([]int, n+1)
	b = make([]int, n+1)
	tree = make([]int, n*2+2)
	for i := 0; i < n; i++ {
		I(&a[i])
	}
	var m int
	I(&m)
	r.ReadLine()
	up := true
	for i := 0; i < m; i++ {
		oo, _, _ := r.ReadLine()
		o := strings.Split(string(oo), " ")
		l, _ := strconv.Atoi(o[0])
		r, _ := strconv.Atoi(o[1])
		if len(o) == 2 {
			if up {
				c := make([]int, n+1)
				c[0] = b[0]
				for i := 1; i <= n; i++ {
					c[i] = b[i] + c[i-1]
				}
				for i := 0; i < n; i++ {
					update(i+1, a[i]+c[i])
				}
			}
			if l <= r {
				O(query(l+1, r+1), "\n")
			} else {
				ans := query(l+1, n)
				qq := query(1, r+1)
				if ans > qq {
					ans = qq
				}
				O(ans, "\n")
			}
			up = false
		} else if len(o) == 3 {
			up = true
			val, _ := strconv.Atoi(o[2])
			if l <= r {
				b[l] += val
				b[r+1] -= val
			} else {
				b[l] += val
				b[0] += val
				b[r+1] -= val
			}
		}
	}
}

func update(x, y int) {
	x += n
	tree[x] = y
	for x > 0 {
		x /= 2
		tree[x] = tree[2*x]
		if tree[x] > tree[2*x+1] {
			tree[x] = tree[2*x+1]
		}
	}
}

func query(l, r int) int {
	var min int = 1e9
	l += n
	r += n
	if r == l {
		return tree[r]
	}
	for l != r {
		if l%2 == 1 {
			if tree[l] < min {
				min = tree[l]
			}
			l++
		}
		if r%2 == 1 {
			if tree[r] < min {
				min = tree[r]
			}
			r--
		}
		l /= 2
		r /= 2
	}
	return min
}

package main

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

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	defer w.Flush()
	for I(&n) == nil {
		solve(n)
	}
}

var n int
var inf int
var a []int
var tree []stree

func solve(n int) {
	inf = 1e9 * 2
	a = make([]int, n)
	for i := 0; i < n; i++ {
		I(&a[i])
	}
	build()
	var m int
	I(&m)
	r.ReadLine()
	for i := 0; i < m; i++ {
		oo, _, _ := r.ReadLine()
		o := strings.Split(string(oo), " ")
		l, _ := strconv.Atoi(o[0])
		r, _ := strconv.Atoi(o[1])
		if len(o) == 2 {
			if l <= r {
				O(query(l, r, 0, n-1, 1), "\n")
			} else {
				O(min(query(l, n-1, 0, n-1, 1), query(0, r, 0, n-1, 1)), "\n")
			}
		} else if len(o) == 3 {
			value, _ := strconv.Atoi(o[2])
			if l <= r {
				update(l, r, 0, n-1, 1, value)
			} else {
				update(l, n-1, 0, n-1, 1, value)
				update(0, r, 0, n-1, 1, value)
			}
		}
	}
}

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

type stree struct {
	value, lazy int
}

func build() {
	tree = make([]stree, n*2)
	for i := 0; i < n; i++ {
		tree[i+n].value = a[i]
	}
	for i := n - 1; i > 0; i-- {
		tree[i].value = min(tree[i*2].value, tree[i*2+1].value)
	}
}

func query(l, r, ll, rr, pos int) int {
	work(ll, rr, pos)
	if ll > r || rr < l {
		return inf
	}
	if l <= ll && rr <= r {
		return tree[pos].value
	}
	mid := (ll + rr) / 2
	return min(query(l, r, ll, mid, pos*2), query(l, r, mid+1, rr, pos*2+1))
}

func update(l, r, ll, rr, pos, value int) {
	if ll > r || rr < l {
		return
	}
	if l <= ll && rr <= r {
		tree[pos].lazy += value
		work(ll, rr, pos)
		return
	}
	mid := (ll + rr) / 2
	update(l, r, ll, mid, pos*2, value)
	update(l, r, mid+1, rr, pos*2+1, value)
	tree[pos].value = min(tree[pos*2].value, tree[pos*2+1].value)
}

func work(l, r, pos int) {
	if tree[pos].lazy == 0 {
		return
	}
	if l != r {
		tree[pos*2].lazy += tree[pos].lazy
		tree[pos*2+1].lazy += tree[pos].lazy
	}
	tree[pos].value += tree[pos].lazy
	tree[pos].lazy = 0
}

package main

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

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	defer w.Flush()
	for I(&n) == nil {
		solve(n)
	}
}

var n int
var a, b, tree []int

func solve(n int) {
	a = make([]int, n+2)
	b = make([]int, n+2)
	tree = make([]int, n*2+2)
	for i := 1; i <= n; i++ {
		I(&a[i])
	}
	var m int
	I(&m)
	r.ReadLine()
	up := true
	for i := 0; i < m; i++ {
		oo, _, _ := r.ReadLine()
		o := strings.Split(string(oo), " ")
		l, _ := strconv.Atoi(o[0])
		r, _ := strconv.Atoi(o[1])
		l++
		r++
		if len(o) == 2 {
			if up {
				c := make([]int, n+1)
				c[1] = b[1]
				for i := 1; i <= n; i++ {
					c[i] = b[i] + c[i-1]
				}
				for i := 1; i <= n; i++ {
					tree[n+i] = a[i] + c[i]
				}
				for i := n - 1; i > 0; i-- {
					tree[i] = tree[i*2]
					if tree[i] > tree[i*2+1] {
						tree[i] = tree[i*2+1]
					}
				}
			}
			if l <= r {
				O(query(l, r), "\n")
			} else {
				ans := query(l, n)
				qq := query(1, r)
				if ans > qq {
					ans = qq
				}
				O(ans, "\n")
			}
			up = false
		} else if len(o) == 3 {
			up = true
			val, _ := strconv.Atoi(o[2])
			if l <= r {
				b[l] += val
				b[r+1] -= val
			} else {
				b[l] += val
				b[1] += val
				b[r+1] -= val
			}
		}
	}
}

func query(l, r int) int {
	var min int = 1e9
	l += n
	r += n
	if r == l {
		return tree[r]
	}
	for l != r {
		if l%2 == 0 {
			if tree[l] < min {
				min = tree[l]
			}
			l++
		}
		if r%2 == 1 {
			if tree[r] < min {
				min = tree[r]
			}
			r--
		}
		l /= 2
		r /= 2
	}
	return min
}


You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.The verse patterns for the given text is a sequence of n integers p1, p2, ..., pn. Text matches the given verse pattern if for each i from 1 to n one can divide words of the i-th line in syllables in such a way that the total number of syllables is equal to pi.You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.

The first line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of lines in the text. The second line contains integers p1, ..., pn (0 ≤ pi ≤ 100) — the verse pattern. Next n lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters.

If the given text matches the given verse pattern, then print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).

4
13 11 15 15
to be or not to be that is the question
whether tis nobler in the mind to suffer
the slings and arrows of outrageous fortune
or to take arms against a sea of troubles

NoteIn the first sample, one can split words into syllables in the following way: in-telco-dech al-len-geSince the word "ch" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one.

package main

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

func main() {
        var n int
        fmt.Scanln(&n)
        m := n
        var as, oo []int
        var a int
        for m > 0 {
                fmt.Scan(&a)
                as = append(as, a)
                m--
        }
        re := regexp.MustCompile("[aeiouy]")
        reader := bufio.NewReader(os.Stdin)
        c, _ := reader.ReadString('\n')
        for n > 0 {
                c, _ = reader.ReadString('\n')
                c = re.ReplaceAllString(c, ",")
                cs := strings.Split(c, ",")
                oo = append(oo, len(cs)-1)
                n--
        }
        if len(oo) != len(as) {
                fmt.Println("NO")
        } else {
                for i, v := range as {
                        if v != oo[i] {
                                fmt.Println("NO")
                                os.Exit(0)
                        }
                }
                fmt.Println("YES")
        }
}

package main

import "bufio"
import "os"
import "io/ioutil"

func vowel(c byte) bool {
	return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u') || (c == 'y')
}

func syllable(s string) int {
	cnt := 0
	n := len(s)
	for i := 0; i < n; i++ {
		if vowel(s[i]) {
			cnt++
		}
	}
	return cnt
}

func main() {
	defer out.Flush()

	var n int
	var a []int
	var s string

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

	res := "YES"
	for i := 0; i < n; i++ {
		readln(&s)
		if syllable(s) != a[i] {
			res = "NO"
		}
	}

	out.WriteString(res)
	out.WriteByte('\n')
}

var out *bufio.Writer
var iPointer int
var nPointer int
var iBuffer []byte

func init() {
	out = bufio.NewWriter(os.Stdout)
	iPointer = 0
	iBuffer, _ = ioutil.ReadAll(os.Stdin)
	nPointer = len(iBuffer)
}

func isLine(c byte) bool {
	return (c == '\n') || (c == '\r')
}

func isSpace(c byte) bool {
	return (c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')
}

func isDigit(c byte) bool {
	return (c >= '0') && (c <= '9')
}

func readInt(v *int) bool {
	neg := false
	for (iPointer < nPointer) && !isDigit(iBuffer[iPointer]) {
		neg = (iBuffer[iPointer] == '-')
		iPointer++
	}
	if iPointer >= nPointer {
		return false
	}
	var a int
	for (iPointer < nPointer) && isDigit(iBuffer[iPointer]) {
		a = a*10 + int(iBuffer[iPointer]-'0')
		iPointer++
	}
	if neg {
		*v = -a
	} else {
		*v = a
	}
	return true
}

func readln(v *string) bool {
	for (iPointer < nPointer) && isLine(iBuffer[iPointer]) {
		iPointer++
	}
	if iPointer >= nPointer {
		return false
	}
	var a []byte
	for (iPointer < nPointer) && !isLine(iBuffer[iPointer]) {
		a = append(a, iBuffer[iPointer])
		iPointer++
	}
	*v = string(a)
	for (iPointer < nPointer) && isLine(iBuffer[iPointer]) {
		iPointer++
	}
	return true
}

// http://acm.timus.ru/problem.aspx?space=1&num=1741
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

const (
	MOD = 1e9 + 7
)

type (

)

func main () {
	var (
		N int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)

	fmt.Fscanln(input, &N)
	m := make([]int, N)

	for i := 0; i < N; i++ {
		if i != N - 1 {
			fmt.Fscan(input, &m[i])
		} else {
			fmt.Fscanln(input, &m[i])
		}
	}

	for i := 0; i < N; i++ {
		var r rune

		fmt.Fscanf(input, "%c", &r)
		tmp := ""
		for r != '\n' {
			tmp += string(r)
			fmt.Fscanf(input, "%c", &r)
		}

		cnt := 0
		for j := 0; j < len(tmp); j++ {
			if strings.ContainsAny(string(tmp[j]), "aeiouy") {
				cnt++
			}
		}

		if cnt != m[i] {
			fmt.Println("NO")
			return
		}
	}

	fmt.Println("YES")
}

package main

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

func main() {
        var n int
        fmt.Scanln(&n)
        m := n
        var as, oo []int
        var a int
        for m > 0 {
                fmt.Scan(&a)
                as = append(as, a)
                m--
        }
        re := regexp.MustCompile("[aeiouy]")
        reader := bufio.NewReader(os.Stdin)
        for n > 0 {
                c, _ := reader.ReadString('\n')
                c = re.ReplaceAllString(c, ",")
                cs := strings.Split(c, ",")
                oo = append(oo, len(cs)-1)
                n--
        }
        if len(oo) != len(as) {
                fmt.Println("NO")
        } else {
                for i, v := range as {
                        if v != oo[i] {
                                fmt.Println("NO")
                                os.Exit(0)
                        }
                }
                fmt.Println("YES")
        }
}


Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card.The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.Suppose Ciel and Jiro play optimally, what is the score of the game?

The first line contain an integer n (1 ≤ n ≤ 100). Each of the next n lines contains a description of the pile: the first integer in the line is si (1 ≤ si ≤ 100) — the number of cards in the i-th pile; then follow si positive integers c1, c2, ..., ck, ..., csi (1 ≤ ck ≤ 1000) — the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile.

Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally.

NoteIn the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10.In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF388C(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	a := []int{}
	var n, m, v, x, y int
	for Fscan(in, &n); n > 0; n-- {
		Fscan(in, &m)
		for i := 0; i < m/2; i++ {
			Fscan(in, &v)
			x += v
		}
		if m&1 > 0 {
			Fscan(in, &v)
			a = append(a, v)
			m--
		}
		for i := m / 2; i < m; i++ {
			Fscan(in, &v)
			y += v
		}
	}
	sort.Ints(a)
	for i := len(a) - 1; i >= 0; i -= 2 {
		x += a[i]
	}
	for i := len(a) - 2; i >= 0; i -= 2 {
		y += a[i]
	}
	Fprint(out, x, y)
}

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


Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex $$$1$$$ is the root of this tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is $$$0$$$.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by $$$2$$$ rounding down. More formally, during one move, you choose some edge $$$i$$$ and divide its weight by $$$2$$$ rounding down ($$$w_i := \left\lfloor\frac{w_i}{2}\right\rfloor$$$).Your task is to find the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most $$$S$$$. In other words, if $$$w(i, j)$$$ is the weight of the path from the vertex $$$i$$$ to the vertex $$$j$$$, then you have to make $$$\sum\limits_{v \in leaves} w(root, v) \le S$$$, where $$$leaves$$$ is the list of all leaves.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$S$$$ ($$$2 \le n \le 10^5; 1 \le S \le 10^{16}$$$) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next $$$n-1$$$ lines describe edges of the tree. The edge $$$i$$$ is described as three integers $$$v_i$$$, $$$u_i$$$ and $$$w_i$$$ ($$$1 \le v_i, u_i \le n; 1 \le w_i \le 10^6$$$), where $$$v_i$$$ and $$$u_i$$$ are vertices the edge $$$i$$$ connects and $$$w_i$$$ is the weight of this edge. It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^5$$$ ($$$\sum n \le 10^5$$$).

For each test case, print the answer: the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most $$$S$$$.

package main

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

type pair struct {
	to int
	val int64
}

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

	T:= 0
	for Fscan(in, &T); T > 0; T-- {
		var n int
		var s int64
		Fscan(in,&n,&s)
		s=-s
		e:=make([][]pair,n+1)
		for i:=0;i<n-1;i++{
			var u,v int
			var val int64
			Fscan(in,&u,&v,&val)
			// Fprintln(out,u,v,n)
			e[u]=append(e[u],pair{v,val})
			e[v]=append(e[v],pair{u,val})
		}

		e[0]=append(e[0],pair{1,0})
		e[1]=append(e[1],pair{0,0})
		ans:=make([]int64,0)
		add:=func(pe int64,cur int64){
			if cur==int64(0){
				return
			}
			// Fprintln(out,pe,cur)
			for pe>0{
				ans=append(ans,((pe+1)/2)*cur)
				pe/=2
			}
		}
		var dfs func(int,int,int64,int64) int64
		dfs=func(u int,p int,cst int64,pe int64) int64 {
			if len(e[u])==1{
				s+=cst
				// Fprintln(out,1,pe)
				add(pe,int64(1))
				return int64(1)
			}
			cur:=int64(0)
			for _,ed := range(e[u]){
				if ed.to==p{
					continue
				}
				cur+=dfs(ed.to,u,cst+ed.val,ed.val)
			}
			// Fprintln(out,cur,pe)
			add(pe,cur)
			return cur
		}

		dfs(1,0,int64(0),int64(0))
		// Fprintln(out,s,ans)
		cnt:=0
		sort.SliceStable(ans, func(i, j int) bool {
			return ans[i] > ans[j]
		})

		for _,x := range(ans){
			if s<=0{
				break
			}
			cnt++
			s-=x
		}

		Fprintln(out,cnt)
	}
}

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

package main

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

type pair struct {
	to int
	val int64
	c int
}

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

	T:= 0
	for Fscan(in, &T); T > 0; T-- {
		var n int
		var s int64
		Fscan(in,&n,&s)
		s=-s
		e:=make([][]pair,n+1)
		for i:=0;i<n-1;i++{
			var u,v,c int
			var val int64
			Fscan(in,&u,&v,&val)
			c=1
			// Fprintln(out,u,v,n)
			e[u]=append(e[u],pair{v,val,c})
			e[v]=append(e[v],pair{u,val,c})
		}

		e[0]=append(e[0],pair{1,0,1})
		e[1]=append(e[1],pair{0,0,1})

		ans:=make([][]int64,2)
		add:=func(pe int64,cur int64,c int){
			if cur==int64(0){
				return
			}
			// Fprintln(out,pe,cur)
			c--
			for pe>0{
				ans[c]=append(ans[c],((pe+1)/2)*cur)
				pe/=2
			}
		}
		var dfs func(int,int,int64,int64,int) int64
		dfs=func(u int,p int,cst int64,pe int64, c int) int64 {
			if len(e[u])==1{
				s+=cst
				// Fprintln(out,1,pe)
				add(pe,int64(1),c)
				return int64(1)
			}
			cur:=int64(0)
			for _,ed := range(e[u]){
				if ed.to==p{
					continue
				}
				cur+=dfs(ed.to,u,cst+ed.val,ed.val,ed.c)
			}
			// Fprintln(out,cur,pe)
			add(pe,cur,c)
			return cur
		}

		dfs(1,0,int64(0),int64(0),0)
		// Fprintln(out,s,ans)
		cnt:=100000000

		for kk:=0;kk<2;kk++{
			ans[kk]=append(ans[kk],int64(1e16))

			sort.SliceStable(ans[kk], func(i, j int) bool {
				return ans[kk][i] > ans[kk][j]
			})

			ans[kk][0]=0
			for i:=1;i<len(ans[kk]);i++{
				ans[kk][i]+=ans[kk][i-1]
			}

		}

		bs:=func(s int64,a []int64) int {
			l,r:=-1,len(a)
			if a[r-1]<s{
				return 1000000000
			}
			for r-l>1{
				m:=(l+r)/2
				if a[m]<s{
					l=m
				} else{
					r=m
				}
			}
			return r
		}

		for i,x:=range(ans[0]){
			val:=i+2*bs(s-x,ans[1])
			if val<cnt{
				cnt=val
			}
		}

		Fprintln(out,cnt)
	}
}

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

package main

import (
	"bufio"
	"bytes"
	"container/heap"
	"fmt"
	"os"
)

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

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--
		var n int
		var S uint64
		s, _ := reader.ReadBytes('\n')
		pos := readInt(s, 0, &n)
		readUint64(s, pos+1, &S)
		E := make([][]int, n-1)
		for i := 0; i < n-1; i++ {
			E[i] = readNNums(reader, 3)
		}
		res := solve(n, int64(S), E)
		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
}

func solve(n int, S int64, E [][]int) int {
	adj := make([][]int, n)
	for i := 0; i < n; i++ {
		adj[i] = make([]int, 0, 3)
	}

	for i := 0; i < len(E); i++ {
		u, v := E[i][0], E[i][1]
		u--
		v--
		adj[u] = append(adj[u], i)
		adj[v] = append(adj[v], i)
	}

	pq := make(PriorityQueue, 0, n)

	var tot int64

	var dfs func(p, u int) int

	dfs = func(p, u int) int {
		if len(adj[u]) == 1 && p >= 0 {
			return 1
		}

		var cnt int
		for _, i := range adj[u] {
			e := E[i]
			v, w := e[0]^e[1]^(u+1), e[2]
			v--
			if p == v {
				continue
			}
			c := dfs(u, v)
			cnt += c
			edge := NewEdge(w, c)

			tot += edge.priority()

			heap.Push(&pq, edge)
		}
		return cnt
	}

	dfs(-1, 0)

	var ans int
	for tot > S && pq.Len() > 0 {
		cur := heap.Pop(&pq).(*Edge)
		tot -= cur.diff()
		cur.w /= 2
		ans++
		if cur.w > 0 {
			heap.Push(&pq, cur)
		}
	}
	return ans
}

type Edge struct {
	w     int
	c     int
	index int
}

func NewEdge(w, c int) *Edge {
	edge := new(Edge)
	edge.w = w
	edge.c = c
	return edge
}

func (edge Edge) priority() int64 {
	return int64(edge.w) * int64(edge.c)
}

func (edge Edge) diff() int64 {
	tot := edge.priority()
	return tot - int64(edge.w/2)*int64(edge.c)
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Edge

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

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].diff() > pq[j].diff()
}

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

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

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

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"io"
	"os"
)

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	type Edge struct {
		v, w int
	}

	for t := io.NextInt(); t > 0; t-- {
		n := io.NextInt()
		var s int64
		fmt.Fscan(io, &s)
		g := make([][]Edge, n+1)
		for i := 0; i < n-1; i++ {
			u, v, w := io.NextInt(), io.NextInt(), io.NextInt()
			g[u] = append(g[u], Edge{v, w})
			g[v] = append(g[v], Edge{u, w})
		}

		var total int64
		pq := new(EHeap)
		var dfs func(u, p int) int
		dfs = func(u, p int) (s int) {
			if u != p && len(g[u]) == 1 {
				return 1
			}
			for _, e := range g[u] {
				if e.v != p {
					c := dfs(e.v, u)
					e := E{e.w, c}
					heap.Push(pq, e)
					total += e.cost()
					s += c
				}
			}
			return
		}
		dfs(1, 1)

		ans := 0
		for total > s {
			e := heap.Pop(pq).(E)
			ans++
			total -= e.remove()
			e.w /= 2
			heap.Push(pq, e)
		}

		io.Println(ans)
	}
}

type E struct {
	w, mul int
}

func (e E) cost() int64 {
	return int64(e.w) * int64(e.mul)
}

func (e E) remove() int64 {
	return int64(e.w+1) / 2 * int64(e.mul)
}

type EHeap []E

func (h EHeap) Len() int           { return len(h) }
func (h EHeap) Less(i, j int) bool { return h[i].remove() > h[j].remove() }
func (h EHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *EHeap) Push(x interface{}) {
	*h = append(*h, x.(E))
}

func (h *EHeap) Pop() interface{} {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, f.c[0])
	}
	return string(s)
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}

func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"math"
	"os"
)

const (
	SCANNER_BUF_SIZE = 2 << 20

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

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

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

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

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

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

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

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

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

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

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

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n := sint64()
		S := sint64()
		nodes := map[int64]map[int64]int64{}
		for i := int64(1); i < n; i++ {
			vi := sint64()
			ui := sint64()
			wi := sint64()
			if nodes[vi] == nil {
				nodes[vi] = map[int64]int64{}
			}
			if nodes[ui] == nil {
				nodes[ui] = map[int64]int64{}
			}
			nodes[vi][ui] = wi
			nodes[ui][vi] = wi
		}
		printf("%d\n", sol(n, S, nodes))
	}
}

type weight struct {
	val    int64
	leaves int64
}

func (w weight) diff() int64 {
	return w.val - (w.val / 2)
}

func (w weight) sum() int64 {
	return w.val * w.leaves
}

func (w weight) less(w2 weight) bool {
	return w.diff()*w.leaves < w2.diff()*w2.leaves
}

type MaxHeap []weight

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

func (s MaxHeap) Less(a, b int) bool {
	return s[b].less(s[a])
}

func (s MaxHeap) Swap(a, b int) {
	s[a], s[b] = s[b], s[a]
}

func (h *MaxHeap) Push(x interface{}) {
	*h = append(*h, x.(weight))
}

func (h *MaxHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func sol(n, S int64, nodes map[int64]map[int64]int64) int64 {
	weights := []weight{}
	explored := map[int64]bool{}
	var dfs func(int64) int64
	dfs = func(i int64) int64 {
		explored[i] = true
		ret := int64(0)
		isLeaf := true
		for nxt := range nodes[i] {
			if !explored[nxt] {
				nxtLeaves := dfs(nxt)
				weights = append(weights, weight{nodes[i][nxt], nxtLeaves})
				ret += nxtLeaves
				isLeaf = false
			}
		}
		if isLeaf {
			return 1
		}
		return ret
	}
	dfs(1)
	h := MaxHeap(weights)
	heap.Init(&h)
	// printf("%v\n", weights)
	totalSum := sum(weights)
	ret := int64(0)
	for totalSum > S {
		ret++
		w := heap.Pop(&h).(weight)
		totalSum -= w.diff() * w.leaves
		w.val /= 2
		heap.Push(&h, w)
		// printf("%v\n", weights)
	}
	return ret
}

func sum(sl []weight) int64 {
	ret := int64(0)
	for _, w := range sl {
		ret += w.sum()
	}
	return ret
}

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"math"
	"os"
)

const (
	SCANNER_BUF_SIZE = 2 << 20

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

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

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

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

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

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

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

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

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

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

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

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n := sint64()
		S := sint64()
		nodes := map[int64]map[int64]int64{}
		for i := int64(1); i < n; i++ {
			vi := sint64()
			ui := sint64()
			wi := sint64()
			if nodes[vi] == nil {
				nodes[vi] = map[int64]int64{}
			}
			if nodes[ui] == nil {
				nodes[ui] = map[int64]int64{}
			}
			nodes[vi][ui] = wi
			nodes[ui][vi] = wi
		}
		printf("%d\n", sol(n, S, nodes))
	}
}

type weight struct {
	val    int64
	leaves int64
}

func (w weight) diff() int64 {
	return w.val - (w.val / 2)
}

func (w weight) sum() int64 {
	return w.val * w.leaves
}

func (w weight) less(w2 weight) bool {
	return w.diff()*w.leaves < w2.diff()*w2.leaves
}

type Heap []weight

func (h Heap) Len() int {
	return len(h)
}

func (h Heap) Less(a, b int) bool {
	return h[b].less(h[a])
}

func (h Heap) Swap(a, b int) {
	h[a], h[b] = h[b], h[a]
}

func (h *Heap) Push(x interface{}) {
	*h = append(*h, x.(weight))
}

func (h *Heap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func sol(n, S int64, nodes map[int64]map[int64]int64) int64 {
	h := Heap{}
	explored := map[int64]bool{}
	var dfs func(int64) int64
	dfs = func(i int64) int64 {
		explored[i] = true
		ret := int64(0)
		isLeaf := true
		for nxt := range nodes[i] {
			if !explored[nxt] {
				nxtLeaves := dfs(nxt)
				heap.Push(&h, weight{nodes[i][nxt], nxtLeaves})
				ret += nxtLeaves
				isLeaf = false
			}
		}
		if isLeaf {
			return 1
		}
		return ret
	}
	dfs(1)
	// printf("%v\n", weights)
	totalSum := sum(h)
	ret := int64(0)
	for totalSum > S {
		ret++
		w := heap.Pop(&h).(weight)
		totalSum -= w.diff() * w.leaves
		w.val /= 2
		heap.Push(&h, w)
		// printf("%v\n", weights)
	}
	return ret
}

func sum(sl []weight) int64 {
	ret := int64(0)
	for _, w := range sl {
		ret += w.sum()
	}
	return ret
}

package main

import (
	"bufio"
	"bytes"
	"container/heap"
	"fmt"
	"os"
)

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

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--
		var n int
		var S uint64
		s, _ := reader.ReadBytes('\n')
		pos := readInt(s, 0, &n)
		readUint64(s, pos+1, &S)
		E := make([][]int, n-1)
		for i := 0; i < n-1; i++ {
			E[i] = readNNums(reader, 3)
		}
		res := solve(n, int64(S), E)
		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
}

func solve(n int, S int64, E [][]int) int {
	adj := make([][]int, n)
	for i := 0; i < n; i++ {
		adj[i] = make([]int, 0, 3)
	}

	for i := 0; i < len(E); i++ {
		u, v := E[i][0], E[i][1]
		u--
		v--
		adj[u] = append(adj[u], i)
		adj[v] = append(adj[v], i)
	}

	pq := make(PriorityQueue, 0, n)

	var tot int64

	var dfs func(p, u int) int

	dfs = func(p, u int) int {
		if len(adj[u]) == 1 && p >= 0 {
			return 1
		}

		var cnt int
		for _, i := range adj[u] {
			e := E[i]
			v, w := e[0]^e[1]^(u+1), e[2]
			v--
			if p == v {
				continue
			}
			c := dfs(u, v)
			cnt += c
			edge := NewEdge(w, c)

			tot += edge.priority()

			heap.Push(&pq, edge)
		}
		return cnt
	}

	dfs(-1, 0)

	var ans int
	for tot > S && pq.Len() > 0 {
		cur := heap.Pop(&pq).(*Edge)
		tot -= cur.priority()
		cur.w /= 2
		ans++
		if cur.w > 0 {
			tot += cur.priority()
			heap.Push(&pq, cur)
		}
	}
	return ans
}

type Edge struct {
	w     int
	c     int
	index int
}

func NewEdge(w, c int) *Edge {
	edge := new(Edge)
	edge.w = w
	edge.c = c
	return edge
}

func (edge Edge) priority() int64 {
	return int64(edge.w) * int64(edge.c)
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Edge

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

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return (pq[i].priority()+1)/2 > (pq[j].priority()+1)/2 ||
		(pq[i].priority()+1)/2 == (pq[j].priority()+1)/2 && pq[i].w > pq[j].w
}

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

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

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

package main

import (
	"bufio"
	"bytes"
	"container/heap"
	"fmt"
	"os"
)

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

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--
		var n int
		var S uint64
		s, _ := reader.ReadBytes('\n')
		pos := readInt(s, 0, &n)
		readUint64(s, pos+1, &S)
		E := make([][]int, n-1)
		for i := 0; i < n-1; i++ {
			E[i] = readNNums(reader, 3)
		}
		res := solve(n, int64(S), E)
		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
}

func solve(n int, S int64, E [][]int) int {
	adj := make([][]int, n)
	for i := 0; i < n; i++ {
		adj[i] = make([]int, 0, 3)
	}

	for i := 0; i < len(E); i++ {
		u, v := E[i][0], E[i][1]
		u--
		v--
		adj[u] = append(adj[u], i)
		adj[v] = append(adj[v], i)
	}

	pq := make(PriorityQueue, 0, n)

	var tot int64

	var dfs func(p, u int) int

	dfs = func(p, u int) int {
		if len(adj[u]) == 1 && p >= 0 {
			return 1
		}

		var cnt int
		for _, i := range adj[u] {
			e := E[i]
			v, w := e[0]^e[1]^(u+1), e[2]
			v--
			if p == v {
				continue
			}
			c := dfs(u, v)
			cnt += c
			edge := NewEdge(w, c)

			tot += edge.priority()

			heap.Push(&pq, edge)
		}
		return cnt
	}

	dfs(-1, 0)

	var ans int
	for tot > S && pq.Len() > 0 {
		cur := heap.Pop(&pq).(*Edge)
		tot -= cur.priority()
		cur.w /= 2
		ans++
		if cur.w > 0 {
			tot += cur.priority()
			heap.Push(&pq, cur)
		}
	}
	return ans
}

type Edge struct {
	w     int
	c     int
	index int
}

func NewEdge(w, c int) *Edge {
	edge := new(Edge)
	edge.w = w
	edge.c = c
	return edge
}

func (edge Edge) priority() int64 {
	return int64(edge.w) * int64(edge.c)
}

func (edge Edge) diff() int64 {
	tot := edge.priority()
	return tot - tot/2
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Edge

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

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].diff() > pq[j].diff()
}

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

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

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

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"io"
	"os"
)

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	type Edge struct {
		v, w int
	}

	for t := io.NextInt(); t > 0; t-- {
		n := io.NextInt()
		var s int64
		fmt.Fscan(io, &s)
		g := make([][]Edge, n+1)
		for i := 0; i < n-1; i++ {
			u, v, w := io.NextInt(), io.NextInt(), io.NextInt()
			g[u] = append(g[u], Edge{v, w})
			g[v] = append(g[v], Edge{u, w})
		}

		var total int64
		pq := new(EHeap)
		var dfs func(u, p int) int
		dfs = func(u, p int) (s int) {
			if u != p && len(g[u]) == 1 {
				return 1
			}
			for _, e := range g[u] {
				if e.v != p {
					c := dfs(e.v, u)
					e := E{e.w, c}
					heap.Push(pq, e)
					total += e.cost()
					s += c
				}
			}
			return
		}
		dfs(1, 1)

		ans := 0

		for total > s {
			e := heap.Pop(pq).(E)
			ans += 1
			total -= e.cost()
			e.w /= 2
			total += e.cost()
			heap.Push(pq, e)
		}

		io.Println(ans)
	}
}

type E struct {
	w, mul int
}

func (e E) cost() int64 {
	return int64(e.w) * int64(e.mul)
}

type EHeap []E

func (h EHeap) Len() int           { return len(h) }
func (h EHeap) Less(i, j int) bool { return h[i].cost() > h[j].cost() }
func (h EHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *EHeap) Push(x interface{}) {
	*h = append(*h, x.(E))
}

func (h *EHeap) Pop() interface{} {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, f.c[0])
	}
	return string(s)
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}

func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

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

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

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

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

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

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

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

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

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

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

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

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n := sint64()
		S := sint64()
		nodes := map[int64]map[int64]int64{}
		for i := int64(1); i < n; i++ {
			vi := sint64()
			ui := sint64()
			wi := sint64()
			if nodes[vi] == nil {
				nodes[vi] = map[int64]int64{}
			}
			if nodes[ui] == nil {
				nodes[ui] = map[int64]int64{}
			}
			nodes[vi][ui] = wi
			nodes[ui][vi] = wi
		}
		printf("%d\n", sol(n, S, nodes))
	}
}

func sol(n, S int64, nodes map[int64]map[int64]int64) int64 {
	weights := []int64{}
	explored := map[int64]bool{}
	var dfs func(int64) int64
	dfs = func(i int64) int64 {
		explored[i] = true
		ret := int64(0)
		isLeaf := true
		for nxt := range nodes[i] {
			if !explored[nxt] {
				nxtLeaves := dfs(nxt)
				weights = append(weights, nodes[i][nxt]*nxtLeaves)
				ret += nxtLeaves
				isLeaf = false
			}
		}
		if isLeaf {
			return 1
		}
		return ret
	}
	dfs(1)
	sort.Slice(weights, func(a, b int) bool {
		return weights[a] < weights[b]
	})
	// printf("%v\n", weights)
	totalSum := sum(weights)
	ret := int64(0)
	for totalSum > S {
		ret++
		p := len(weights)-1
		target := weights[p] / 2
		totalSum -= weights[p] - target
		weights[p] = target
		for p > 0 && weights[p-1] > weights[p] {
			weights[p-1], weights[p] = weights[p], weights[p-1]
			p--
		}
		// printf("%v\n", weights)
	}
	return ret
}

func sum(sl []int64) int64 {
	ret := int64(0)
	for _, i := range sl {
		ret += i
	}
	return ret
}