A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles.In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has bi personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.Each boy can rent at most one bike, one cannot give his bike to somebody else.What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?

The first line of the input contains three integers n, m and a (1 ≤ n, m ≤ 105; 0 ≤ a ≤ 109). The second line contains the sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104), where bi is the amount of the i-th boy's personal money. The third line contains the sequence of integers p1, p2, ..., pm (1 ≤ pj ≤ 109), where pj is the price for renting the j-th bike.

Print two integers r and s, where r is the maximum number of schoolboys that can rent a bike and s is the minimum total personal money needed to rent r bikes. If the schoolchildren cannot rent any bikes, then r = s = 0.

NoteIn the first sample both schoolchildren can rent a bike. For instance, they can split the shared budget in half (5 rubles each). In this case one of them will have to pay 1 ruble from the personal money and the other one will have to pay 2 rubles from the personal money. In total, they spend 3 rubles of their personal money. This way of distribution of money minimizes the amount of spent personal money.

package main

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

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

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

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

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

func main() {
	scanner.Split(bufio.ScanWords)
	n, m, k := nextInt(), nextInt(), nextInt()
	a := make([]int, n)
	p := make([]int, m)
	for i := range a {
		a[i] = nextInt()
	}
	for i := range p {
		p[i] = nextInt()
	}
	sort.Ints(a)
	sort.Ints(p)
	ans := sort.Search(min(n, m)+1, func(nn int) bool {
		share := int64(k)
		i := n - nn
		j := 0
		for i < n {
			if a[i] < p[j] {
				share -= int64(p[j] - a[i])
			}
			i++
			j++
		}
		return share < 0
	}) - 1
	sum := 0
	for _, x := range p[:ans] {
		sum += x
	}
	buffer.WriteString(strconv.FormatInt(int64(ans), 10))
	buffer.WriteByte(' ')
	buffer.WriteString(strconv.FormatInt(int64(max(sum-k, 0)), 10))
	buffer.Flush()
}

package main

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

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

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

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

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

func main() {
	scanner.Split(bufio.ScanWords)
	n, m, k := nextInt(), nextInt(), nextInt()
	a := make([]int, n)
	p := make([]int, m)
	for i := range a {
		a[i] = nextInt()
	}
	for i := range p {
		p[i] = nextInt()
	}
	sort.Ints(a)
	sort.Ints(p)
	ans := sort.Search(min(n, m)+1, func(nn int) bool {
		share := int64(k)
		i := n - nn
		j := 0
		for i < n {
			if a[i] < p[j] {
				share -= int64(p[j] - a[i])
			}
			i++
			j++
		}
		return share < 0
	}) - 1
	sum := 0
	for _, x := range p[:ans] {
		sum += x
	}
	fmt.Println(ans, max(sum-k, 0))
}

package main

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

func main() {
  bin := bufio.NewReader(os.Stdin)
	const N int = 100000
	num_child, num_bike, share := 0, 0, 0
	bike := [N]int{}
	child := [N]int{}
	fmt.Fscanf(bin, "%d %d %d", &num_child, &num_bike, &share)
	for i := 0; i < num_child; i++ {
		fmt.Fscan(bin, &child[i])
	}
	for i := 0; i < num_bike; i++ {
		fmt.Fscan(bin, &bike[i])
	}
	sort.Ints(bike[:num_bike])
	sort.Ints(child[:num_child])
	low, high, rent, cost := 0, num_bike, 0, 0
	if high > num_child {
		high = num_child
	}
	for low <= high {
		mid := (low + high) / 2
		this_share, total_cost := share, 0
		can_done := true
		for i, j := mid-1, num_child-1; i >= 0 && j >= 0; {
			if child[j]+this_share >= bike[i] {
				if bike[i] > child[j] {
					this_share -= bike[i] - child[j]
				}
			} else {
				can_done = false
				break
			}
			total_cost += bike[i]
			i--
			j--
		}
		if can_done {
			rent, cost = mid, total_cost-share
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	if cost < 0 {
		fmt.Println(rent, 0)
	} else {
		fmt.Println(rent, cost)
	}
}

package main

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

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

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

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

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

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

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

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

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

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

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

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

func min(i, j int) int {
    if i < j {
        return i
    }
    return j
}

func max(i, j int64) int64 {
    if i > j {
        return i
    }
    return j
}

func main() {
    defer w.Flush()
    n, m, a := ni32(), ni32(), ni32()
    b := make([]int, n)
    p := make([]int, m)
    tb := make([]int64, n)
    tp := make([]int64, m)
    for i := 0; i < n; i++ {
        b[i] = ni32()
    }
    for i := 0; i < m; i++ {
        p[i] = ni32()
    }
    sort.Ints(b)
    sort.Ints(p)
    tb[0], tp[0] = int64(b[0]), int64(p[0])
    for i := 1; i < n; i++ {
        tb[i] = tb[i-1] + int64(b[i])
    }
    for i := 1; i < m; i++ {
        tp[i] = tp[i-1] + int64(p[i])
    }
    //first J cannot
    J := sort.Search(n, func(j int) bool {
        if n-j > m {
            return false
        }
        rest := a
        for i := j; i < n; i++ {
            if b[i] < p[i-j] {
                rest -= p[i-j] - b[i]
            }
            if rest < 0 {
                return false
            }
        }
        return true
    })
    if J == n {
        pri64(0, 0)
    } else {
        tot, av := tb[n-1], int64(0)
        if J > 0 {
            tot -= tb[J-1]
        }
        if J < n {
            av += tp[n-1-J]
        }
        ans := av - int64(a)
        if ans < 0 {
            ans = 0
        }
        pri64(int64(n-J), ans)
    }

}

package main

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

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

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

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

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

func main() {
	scanner.Split(bufio.ScanWords)
	n, m, k := nextInt(), nextInt(), nextInt()
	a := make([]int, n)
	p := make([]int, m)
	for i := range a {
		a[i] = nextInt()
	}
	for i := range p {
		p[i] = nextInt()
	}
	sort.Ints(a)
	sort.Ints(p)
	ans := sort.Search(min(n, m)+1, func(nn int) bool {
		share := int64(k)
		i := n - nn
		j := 0
		for i < n {
			if a[i] < p[j] {
				share -= int64(p[j] - a[i])
			}
			i++
			j++
		}
		return share < 0
	}) - 1
	sum := 0
	for _, x := range p[:ans] {
		sum += x
	}
	println(ans, max(sum-k, 0))
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	const N int = 100000
	num_child, num_bike, share := 0, 0, 0
	bike := [N]int{}
	child := [N]int{}
	fmt.Scanf("%d %d %d", &num_child, &num_bike, &share)
	for i := 0; i < num_child; i++ {
		fmt.Scan(&child[i])
	}
	for i := 0; i < num_bike; i++ {
		fmt.Scan(&bike[i])
	}
	sort.Ints(bike[:num_bike])
	sort.Ints(child[:num_child])
	low, rent, cost, orignal_share := 0, 0, 0, share
	for i := 0; i < num_bike; i++ {
		value := bike[i]
		if low >= num_child {
			continue
		}
		new_low := sort.SearchInts(child[low:num_child], value) + low
		for j := low; j <= new_low && j < num_child; j++ {
			if child[j]+share >= value {
				share -= value - child[j]
				cost += value
				rent++
				new_low = j + 1
				break
			}
		}
		low = new_low
	}
	if cost-orignal_share < 0 {
		fmt.Println(rent, 0)
	} else {
		fmt.Println(rent, cost-orignal_share)
	}
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	const N int = 100000
	num_child, num_bike, share := 0, 0, 0
	bike := [N]int{}
	child := [N]int{}
	fmt.Scanf("%d %d %d", &num_child, &num_bike, &share)
	for i := 0; i < num_child; i++ {
		fmt.Scan(&child[i])
	}
	for i := 0; i < num_bike; i++ {
		fmt.Scan(&bike[i])
	}
	sort.Ints(bike[:num_bike])
	sort.Ints(child[:num_child])
	low, rent, cost, orignal_share := 0, 0, 0, share
	for i := 0; i < num_bike; i++ {
		value := bike[i]
		if low >= num_child {
			continue
		}
		new_low := sort.SearchInts(child[low:num_child], value) + low
		for j := low; j <= new_low && j < num_child; j++ {
			if child[j]+share >= value {
				share -= value - child[j]
				cost += value
				rent++
				new_low = j + 1
				break
			}
		}
		low = new_low
	}
	if cost-share < 0 {
		fmt.Println(rent, 0)
	} else {
		fmt.Println(rent, cost-orignal_share)
	}
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	const N int = 100000
	num_child, num_bike, share := 0, 0, 0
	bike := [N]int{}
	child := [N]int{}
	fmt.Scanf("%d %d %d", &num_child, &num_bike, &share)
	for i := 0; i < num_child; i++ {
		fmt.Scan(&child[i])
	}
	for i := 0; i < num_bike; i++ {
		fmt.Scan(&bike[i])
	}
	sort.Ints(bike[:num_bike])
	sort.Ints(child[:num_child])
	low, high, rent, cost := 0, num_bike, 0, 0
	if high > num_child {
		high = num_child
	}
	for low <= high {
		mid := (low + high) / 2
		this_share, total_cost := share, 0
		can_done := true
		for i, j := mid-1, num_child-1; i >= 0 && j >= 0; i, j = i-1, j-1 {
			if child[j]+this_share >= bike[i] {
				if bike[i] > child[j] {
					this_share -= bike[i] - child[j]
				}
			} else {
				can_done = false
			}
			total_cost += bike[i]
		}
		if can_done {
			rent, cost = mid, total_cost-share
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	fmt.Println(rent, cost)
}

package main

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

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

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

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

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

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

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

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

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

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

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

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

func min(i, j int) int {
    if i < j {
        return i
    }
    return j
}

func max(i, j int64) int64 {
    if i > j {
        return i
    }
    return j
}

func main() {
    defer w.Flush()
    n, m, a := ni32(), ni32(), ni32()
    b := make([]int, n)
    p := make([]int, m)
    tb, tp := make([]int64, n), make([]int64, m)
    for i := 0; i < n; i++ {
        b[i] = ni32()
    }
    for i := 0; i < m; i++ {
        p[i] = ni32()
    }
    sort.Ints(b)
    sort.Ints(p)
    tb[0], tp[0] = int64(b[0]), int64(p[0])
    for i := 1; i < n; i++ {
        tb[i] = tb[i-1] + int64(b[i])
    }
    for i := 1; i < m; i++ {
        tp[i] = tp[i-1] + int64(p[i])
    }
    //first J cannot
    ans := int64(math.MaxInt64)
    J := sort.Search(n, func(j int) bool {
        if n-j > m {
            return false
        }
        tot := tb[n-1]
        if j > 0 {
            tot -= tb[j-1]
        }
        av := int64(0)
        if n-j-1 >= 0 {
            av += tp[n-j-1]
        }
        if tot+int64(a) >= av {
            ans = av - int64(a)
            if ans < 0 {
                ans = 0
            }
        }
        return tot+int64(a) >= av
    })
    if ans == int64(math.MaxInt64) {
        ans = 0
    }
    pri64(int64(n-J), ans)
}


Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others — a group of b-s), but cccc is not since in each possible consequent partition letters in these two groups coincide.You're given a string s. Check whether it can be split into two non-empty subsequences such that the strings formed by these subsequences are adorable. Here a subsequence is an arbitrary set of indexes of the string.

The only line contains s (1 ≤ |s| ≤ 105) consisting of lowercase latin letters.

Print «Yes» if the string can be split according to the criteria above or «No» otherwise. Each letter can be printed in arbitrary case.

NoteIn sample case two zzcxx can be split into subsequences zc and zxx each of which is adorable.There's no suitable partition in sample case three.

package main

import (
	"fmt"
	"os"
)

func main() {
	var s string
	fmt.Scanf("%s\n", &s)
	var m = make(map[int32]int)
	for _, v := range s{
		m[v]++
	}
	lm := len(m) //kolvo elementov
	if lm < 2 || lm > 4{
		fmt.Println("No")
		os.Exit(0)
	}
	var allowOne, oneIsHere bool
	for _, v := range m{
		if lm == 2 && v == 1{
			fmt.Println("No")
			os.Exit(0)
		}
		if v == 1{
			oneIsHere = true
		}
		if v > 1{
			allowOne = true
		}
	}
	if allowOne == false && lm == 4{
		fmt.Println("Yes")
		os.Exit(0)
	}
	if !allowOne && oneIsHere{
		fmt.Println("No")
		os.Exit(0)
	}
	fmt.Println("Yes")
}

package main

import (
	"fmt"
	"os"
)

func main() {
	var s string
	fmt.Scanf("%s\n", &s)
	var m = make(map[int32]int)
	for _, v := range s{
		m[v]++
	}
	lm := len(m) //kolvo elementov
	if lm < 2 || lm > 4{
		fmt.Println("No")
		os.Exit(0)
	}
	var allowOne, oneIsHere bool
	for _, v := range m{
		if lm == 2 && v == 1{
			fmt.Println("No")
			os.Exit(0)
		}
		if v == 1{
			oneIsHere = true
		}
		if v > 1{
			allowOne = true
		}
	}
	if !allowOne && oneIsHere{
		fmt.Println("No")
		os.Exit(0)
	}
	fmt.Println("Yes")
}


Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date.The clock's face can display any number from 1 to d. It is guaranteed that ai ≤ d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d + 1, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1.Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1.

The first line contains the single number d — the maximum number of the day that Vasya's clock can show (1 ≤ d ≤ 106). The second line contains a single integer n — the number of months in the year (1 ≤ n ≤ 2000). The third line contains n space-separated integers: ai (1 ≤ ai ≤ d) — the number of days in each month in the order in which they follow, starting from the first one.

Print a single number — the number of times Vasya manually increased the day number by one throughout the last year.

NoteIn the first sample the situation is like this:   Day 1. Month 1. The clock shows 1. Vasya changes nothing.  Day 2. Month 1. The clock shows 2. Vasya changes nothing.  Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1.  Day 2. Month 2. The clock shows 2. Vasya changes nothing.  In total, Vasya manually changed the day number by 1 exactly 2 times.

package main

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

func main(){
	var d int
	var n int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	d, _ = strconv.Atoi(r.Text())
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	a := make([]int, n)
	for i:=0; i<n; i++ {
		r.Scan()
		a[i], _ = strconv.Atoi(r.Text())
	}
	total := 0
	for j:=0; j<n; j++ {
		if j != n-1 {
			total += d - a[j]
		}
	}
	w.WriteString(strconv.Itoa(total)+"\n")
	w.Flush()
}

package main

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

func main() {
    var n,i,k,d,ans int
    ans=0
    fmt.Scan(&d,&n)
    for i=0;i<n;i++ {
    	fmt.Scan(&k)
    	ans+=d-k
    }
    ans-=(d-k)
    fmt.Println(ans)
}

package main

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

var scanner *bufio.Scanner

func getI() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

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

  d, n := int(getI()), int(getI())
  result := 0
  for i := 0; i < n; i++ {
    x := int(getI())
    if i != n-1 {
      result += d-x
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

import "fmt"

func main() {
    var d,n,a int
    fmt.Scan(&d)
    fmt.Scan(&n)
    ans := 0
    for i := 0; i < n; i++ {
        fmt.Scan(&a)
        if i != (n-1) { ans += d-a }
    }
    fmt.Println(ans)
}

package main

import "fmt"

func main() {
    var d,n,a int // Variabel d, n, a adalah integer
    fmt.Scan(&d) // meminta input d
    fmt.Scan(&n) // meminta input n
    ans := 0 // answer adalah integer yang isinya adlah 0
    for i := 0; i < n; i++ { // lakukan selama kondisi ini
        fmt.Scan(&a) // meminta input a
        if i != (n-1) { ans += d-a } // lakukan selama kondisi ini
    }
    fmt.Println(ans) // mencetak output
}

// 182B
package main

import (
	"fmt"
)

func main() {
	var d, n, mon int
	fmt.Scan(&d, &n)
	sum := 0
	for i := 1; i <= n; i++ {
		fmt.Scan(&mon)
		if i <= n-1 {
			sum += (d - mon)
		}
	}
	fmt.Println(sum)
}

// 182B-mic
package main

import (
	"fmt"
)

func main() {
	var a, b, d int
	fmt.Scan(&a, &b)
	sum := a * (b - 1)
	for i := 0; i < b; i++ {
		fmt.Scan(&d)
		if i == b-1 {
			break
		}
		sum -= d
	}
	fmt.Println(sum)
}

// 182B
package main

import (
	"fmt"
)

func main() {
	var a, b, x, i, sum int64
	sum = 0
	fmt.Scan(&a, &b)
	for i = 0; i < b; i++ {
		fmt.Scan(&x)
		sum += a - x
	}
	fmt.Scan(&i)
	fmt.Println(sum)
}

// 182B
package main

import (
	"fmt"
)

func main() {
	var d, n, mon int
	fmt.Scan(&d, &n)
	sum := 0
	for i := 1; i <= n; i++ {
		fmt.Scan(&mon)
		if i <= n-1 {
			sum += (d - mon) / 2
		}
	}
	fmt.Println(sum)
}


Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.

The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000). The following line contains a binary string of length n representing Kevin's results on the USAICO.

Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.

NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score.

package main

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

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

  line, _ := reader.ReadString('\n')
  n, _ := strconv.Atoi(strings.TrimSpace(line))
  line, _ = reader.ReadString('\n')

  maxLength, maxCount := -1, -1
  start := 0
  for i := 1; i < n; i++ {
    if line[i - 1] != line[i] {
      length := i - start
      if length > maxLength {
        maxLength = length
        maxCount = 1
      } else if length == maxLength {
        maxCount += 1
      }
      start = i
    }
  }
  length := n - start
  if length > maxLength {
    maxLength = length
    maxCount = 1
  } else if length == maxLength {
    maxCount += 1
  }

  result := 1
  if maxLength >= 3 {
    result += 2
  } else if maxLength == 2 {
    result++
    if maxCount > 1 {
      result++
    }
  }

  for i := 1; i < n; i++ {
    if line[i - 1] != line[i] {
      result++
    }
  }

  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

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

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

var s string
var n int

func main()  {
	defer writer.Flush()
	fmt.Fscanf(reader, "%d\n", &n)
	fmt.Fscanf(reader, "%s", &s)
	var a, b int

	b = 1
	for i := 0; i < n - 1; i++ {
		if s[i] == s[i + 1] {
			a++
		} else {
			b++
		}
	}

	if a >= 2 {
		a = 2
	}

	fmt.Fprintf(writer, "%d\n", a + b)
}

package main

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

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

const N = 100010
var dp[N][2][3] int

var s string
var n int

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

func main()  {
	defer writer.Flush()
	fmt.Fscanf(reader, "%d\n", &n)
	fmt.Fscanf(reader, "%s", &s)

	for i := 1; i <= n; i++ {
		var val = int(s[i - 1] - '0')
		for j := 0; j < 2; j++ {
			for c := 0; c < 3; c++ {
				// init
				dp[i][j][c] = dp[i - 1][j][c]

				if c > 0 {
					dp[i][j][c] = max(dp[i][j][c], dp[i - 1][1 - j][c - 1])
				}

				// others
				if (c == 0 || c == 2) && j == val {
					dp[i][j][c] = max(dp[i][j][c], dp[i - 1][1 - j][c] + 1)
					if c > 0 {
						dp[i][j][c] = max(dp[i][j][c], dp[i - 1][1 - j][c - 1] + 1)
					}
				}

				if c == 1 && j == 1 - val {
					dp[i][j][c] = max(dp[i][j][c], dp[i - 1][1 - j][c] + 1)
					dp[i][j][c] = max(dp[i][j][c], dp[i - 1][1 - j][c - 1] + 1)
				}
			}
		}
	}

	var ret = 0
	for i := 0; i < 2; i++ {
		for j := 0; j < 3; j++ {
			ret = max(ret, dp[n][i][j])
		}
	}

	fmt.Fprintf(writer, "%d\n", ret)
}

package main

import (
    "fmt"
)

func main() {
    var s []byte
    var n int
    fmt.Scanf("%d\r\n%s", &n, &s)
    for i := 0; i < n; i++ {
        if i+2 < n {
            if s[i] == '0' && s[i+1] == '0' && s[i+2] == '0' {
                s[i+1] = '1'
                break
            }
        }
    }
    l := 0
    var b byte
    for i := 0; i < n; i++ {
        if i == 0 {
            b = s[i]
            l++
            continue
        }
        if s[i] == b {
            continue
        }
        b = s[i]
        l++
    }
    fmt.Println(l)
}

package main

import (
    "fmt"
)

func inv(s []byte, a, b int) {
    for i := a; i < b; i++ {
        if s[i] == '0' {
            s[i] = '1'
        } else {
            s[i] = '0'
        }
    }
}

func main() {
    var s []byte
    var n int
    fmt.Scanf("%d\r\n%s\r\n", &n, &s)
    var zero, one bool
    zeroPos := -1
    onePos := -1
    for i := 0; i+1 < n; {
        if s[i] == '0' && s[i+1] == '0' {
            if zero {
                inv(s, zeroPos, i+1)
                goto Count
            }
            zero = true
            zeroPos = i + 1
            i += 2
        } else if s[i] == '1' && s[i+1] == '1' {
            if one {
                inv(s, onePos, i+1)
                goto Count
            }
            one = true
            onePos = i + 1
            i += 2
        } else {
            i++
        }
    }
    if zero {
        inv(s, zeroPos, n)
        goto Count
    }
    if one {
        inv(s, onePos, n)
        goto Count
    }
    for i := 0; i+2 < n; i++ {
        if s[i] == '0' && s[i+1] == '0' && s[i+2] == '0' {
            s[i+1] = '1'
            break
        }
        if s[i] == '1' && s[i+1] == '1' && s[i+2] == '1' {
            s[i+1] = '0'
            break
        }
    }
Count:
    l := 0
    var b byte
    for i := 0; i < n; i++ {
        if i == 0 {
            b = s[i]
            l++
            continue
        }
        if s[i] == b {
            continue
        }
        b = s[i]
        l++
    }
    fmt.Println(l)
}

package main

import (
    "fmt"
)

func inv(s []byte, a, b int) {
    for i := a; i < b; i++ {
        if s[i] == '0' {
            s[i] = '1'
        } else {
            s[i] = '0'
        }
    }
}

func main() {
    var s []byte
    var n int
    fmt.Scanf("%d\r\n%s\r\n", &n, &s)
    fmt.Println(n, len(s))
    var zero, one bool
    zeroPos := -1
    onePos := -1
    for i := 0; i < n && (i+1) < n; {
        if s[i] == '0' && s[i+1] == '0' {
            if zero {
                inv(s, zeroPos, i+1)
                goto Count
            }
            zero = true
            zeroPos = i + 1
            i += 2
        } else if s[i] == '1' && s[i+1] == '1' {
            if one {
                inv(s, onePos, i+1)
                goto Count
            }
            one = true
            onePos = i + 1
            i += 2
        } else {
            i++
        }
    }
    for i := 0; i < n; i++ {
        if i+2 < n {
            if s[i] == '0' && s[i+1] == '0' && s[i+2] == '0' {
                s[i+1] = '1'
                break
            }
            if s[i] == '1' && s[i+1] == '1' && s[i+2] == '1' {
                s[i+1] = '0'
                break
            }
        }
    }
Count:
    l := 0
    var b byte
    for i := 0; i < n; i++ {
        if i == 0 {
            b = s[i]
            l++
            continue
        }
        if s[i] == b {
            continue
        }
        b = s[i]
        l++
    }
    fmt.Println(l)
}

package main

import (
    "fmt"
)

func inv(s []byte, a, b int) {
    for i := a; i < b; i++ {
        if s[i] == '0' {
            s[i] = '1'
        } else {
            s[i] = '0'
        }
    }
}

func main() {
    var s []byte
    var n int
    fmt.Scanf("%d\r\n%s\r\n", &n, &s)
    var zero, one bool
    zeroPos := -1
    onePos := -1
    for i := 0; i < n && (i+1) < n; {
        if s[i] == '0' && s[i+1] == '0' {
            if zero {
                inv(s, zeroPos, i+1)
                goto Count
            }
            zero = true
            zeroPos = i + 1
            i += 2
        } else if s[i] == '1' && s[i+1] == '1' {
            if one {
                inv(s, onePos, i+1)
                goto Count
            }
            one = true
            onePos = i + 1
            i += 2
        } else {
            i++
        }
    }
    for i := 0; i < n; i++ {
        if i+2 < n {
            if s[i] == '0' && s[i+1] == '0' && s[i+2] == '0' {
                s[i+1] = '1'
                break
            }
            if s[i] == '1' && s[i+1] == '1' && s[i+2] == '1' {
                s[i+1] = '0'
                break
            }
        }
    }
Count:
    l := 0
    var b byte
    for i := 0; i < n; i++ {
        if i == 0 {
            b = s[i]
            l++
            continue
        }
        if s[i] == b {
            continue
        }
        b = s[i]
        l++
    }
    fmt.Println(l)
}

package main

import (
    "fmt"
)

func main() {
    var s []byte
    var n int
    fmt.Scanf("%d\r\n%s", &n, &s)
    a := -1
    for i := 0; i < n; {
        if i+1 >= n {
            break
        }
        if s[i] == '0' && s[i+1] == '0' {
            if a >= 0 {
                for j := a; j <= i; j++ {
                    if s[j] == '0' {
                        s[j] = '1'
                    } else {
                        s[j] = '0'
                    }
                }
                goto L
            }
            a = i + 1
            i += 2
        } else {
            i++
        }
    }
    for i := 0; i < n; i++ {
        if i+2 < n {
            if s[i] == '0' && s[i+1] == '0' && s[i+2] == '0' {
                s[i+1] = '1'
                break
            }
        }
    }
L:
    l := 0
    var b byte
    for i := 0; i < n; i++ {
        if i == 0 {
            b = s[i]
            l++
            continue
        }
        if s[i] == b {
            continue
        }
        b = s[i]
        l++
    }
    fmt.Println(l)
}

package main

import (
    "fmt"
)

func inv(s []byte, a, b int) {
    for i := a; i < b; i++ {
        if s[i] == '0' {
            s[i] = '1'
        } else {
            s[i] = '0'
        }
    }
}

func main() {
    var s []byte
    var n int
    fmt.Scanf("%d\r\n%s", &n, &s)
    var zero, one bool
    zeroPos := -1
    onePos := -1
    for i := 0; i < n && (i+1) < n; {
        if s[i] == '0' && s[i+1] == '0' {
            if zero {
                inv(s, zeroPos, i+1)
                goto Count
            }
            zero = true
            zeroPos = i + 1
            i += 2
        } else if s[i] == '1' && s[i+1] == '1' {
            if one {
                inv(s, onePos, i+1)
                goto Count
            }
            one = true
            onePos = i + 1
            i += 2
        } else {
            i++
        }
    }
    for i := 0; i < n; i++ {
        if i+2 < n {
            if s[i] == '0' && s[i+1] == '0' && s[i+2] == '0' {
                s[i+1] = '1'
                break
            }
            if s[i] == '1' && s[i+1] == '1' && s[i+2] == '1' {
                s[i+1] = '0'
                break
            }
        }
    }
Count:
    l := 0
    var b byte
    for i := 0; i < n; i++ {
        if i == 0 {
            b = s[i]
            l++
            continue
        }
        if s[i] == b {
            continue
        }
        b = s[i]
        l++
    }
    fmt.Println(l)
}

package main

import (
    "fmt"
)

func inv(s []byte, a, b int) {
    for i := a; i < b; i++ {
        if s[i] == '0' {
            s[i] = '1'
        } else {
            s[i] = '0'
        }
    }
}

func main() {
    var s []byte
    var n int
    fmt.Scanf("%d\r\n%s\r\n", &n, &s)
    var zero, one bool
    zeroPos := -1
    onePos := -1
    for i := 0; i+1 < n; {
        if s[i] == '0' && s[i+1] == '0' {
            if zero {
                inv(s, zeroPos, i+1)
                goto Count
            }
            zero = true
            zeroPos = i + 1
            i += 2
        } else if s[i] == '1' && s[i+1] == '1' {
            if one {
                inv(s, onePos, i+1)
                goto Count
            }
            one = true
            onePos = i + 1
            i += 2
        } else {
            i++
        }
    }
    for i := 0; i+2 < n; i++ {
        if s[i] == '0' && s[i+1] == '0' && s[i+2] == '0' {
            s[i+1] = '1'
            break
        }
        if s[i] == '1' && s[i+1] == '1' && s[i+2] == '1' {
            s[i+1] = '0'
            break
        }
    }
Count:
    l := 0
    var b byte
    for i := 0; i < n; i++ {
        if i == 0 {
            b = s[i]
            l++
            continue
        }
        if s[i] == b {
            continue
        }
        b = s[i]
        l++
    }
    fmt.Println(l)
}

package main

import (
    "fmt"
)

func inv(s []byte, a, b int) {
    for i := a; i < b; i++ {
        if s[i] == '0' {
            s[i] = '1'
        } else {
            s[i] = '0'
        }
    }
}

func main() {
    var s []byte
    var n int
    fmt.Scanf("%d\r\n%s\r\n", &n, &s)
    pos := -1
    for i := 0; i+1 < n; {
        if (s[i] == '0' && s[i+1] == '0') || (s[i] == '1' && s[i+1] == '1') {
            if pos >= 0 {
                inv(s, pos, i+1)
                goto Count
            }
            pos = i + 1
            i += 2
        } else {
            i++
        }
    }
    if pos >= 0 {
        inv(s, pos, n)
    }
Count:
    l := 0
    var b byte
    for i := 0; i < n; i++ {
        if i == 0 {
            b = s[i]
            l++
            continue
        }
        if s[i] == b {
            continue
        }
        b = s[i]
        l++
    }
    fmt.Println(l)
}

package main

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

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

  line, _ := reader.ReadString('\n')
  n, _ := strconv.Atoi(strings.TrimSpace(line))
  line, _ = reader.ReadString('\n')

  maxZero, maxOne := -1, -1
  start := 0
  for i := 1; i < n; i++ {
    if line[i - 1] != line[i] {
      length := i - start
      if line[i - 1] == '0' {
        if length > maxZero {
          maxZero = length
        }
      } else {
        if length > maxOne {
          maxOne = length
        }
      }
      start = i
    }
  }
  length := n - start
  if line[n - 1] == '0' {
    if length > maxZero {
      maxZero = length
    }
  } else {
    if length > maxOne {
      maxOne = length
    }
  }

  result := 1
  if maxZero >= 3 || maxOne >= 3 {
    result += 2
  } else if maxZero == 2 && maxOne == 2 {
    result += 2
  } else if maxZero == 2 || maxOne == 2 {
    result++
  }

  for i := 1; i < n; i++ {
    if line[i - 1] != line[i] {
      result++
    }
  }

  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

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

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

  line, _ := reader.ReadString('\n')
  n, _ := strconv.Atoi(strings.TrimSpace(line))
  line, _ = reader.ReadString('\n')

  bestLength, bestStart, bestEnd := -1, -1, -1
  start := 0
  for i := 1; i < n; i++ {
    if line[i - 1] != line[i] {
      length := i - start
      //fmt.Printf("start = %d, i = %d, length = %d\n", start, i, length)
      if length > bestLength {
        bestEnd = i
        bestStart = start
        bestLength = length
      }
      start = i
    }
  }
  length := n - start
  //fmt.Printf("start = %d, end = %d, length = %d\n", start, n, length)
  if length >= bestLength {
    bestEnd = n
    bestStart = start
    bestLength = length
  }
  result := 1
  if bestLength == 2 && (bestStart == 0 || bestEnd == n) {
    result++
  }
  if bestLength >= 3 {
    result += 2
  }

  for i := 1; i < n; i++ {
    if line[i - 1] != line[i] {
      result++
    }
  }

  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

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

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

  line, _ := reader.ReadString('\n')
  n, _ := strconv.Atoi(strings.TrimSpace(line))
  line, _ = reader.ReadString('\n')

  bestLength := -1
  start := 0
  for i := 1; i < n; i++ {
    if line[i - 1] != line[i] {
      length := i - start
      //fmt.Printf("start = %d, i = %d, length = %d\n", start, i, length)
      if length > bestLength {
        bestLength = length
      }
      start = i
    }
  }
  length := n - start
  //fmt.Printf("start = %d, end = %d, length = %d\n", start, n, length)
  if length >= bestLength {
    bestLength = length
  }
  result := 1
  if bestLength == 2 {
    result++
  }
  if bestLength >= 3 {
    result += 2
  }

  for i := 1; i < n; i++ {
    if line[i - 1] != line[i] {
      result++
    }
  }

  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

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

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

var s string
var n int

func main()  {
	defer writer.Flush()
	fmt.Fscanf(reader, "%d\n", &n)
	fmt.Fscanf(reader, "%s", &s)
	var a, b int

	b = 1
	for i := 0; i < n - 1; i++ {
		if s[i] == s[i + 1] {
			a++
		} else {
			b++
		}
	}

	if a >= 2 {
		b += 2
	}

	fmt.Fprintf(writer, "%d\n", b)
}


Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:  the number of different users online did not exceed M at any moment,  at some second the number of distinct users online reached value M,  the total number of users (the number of distinct identifiers) was as much as possible. Help Polycarpus cope with the test.

The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).

In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).

NoteConsider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56.In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)

package main

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

func isDelim(b byte) bool {
	return b == ' ' || b == '\n' || b == ':' || b == '\r'
}

func getString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getInt(scanner *bufio.Scanner) int {
	x, _ := strconv.ParseInt(getString(scanner), 10, 32)
	return int(x)
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	split := func(data []byte, atEOF bool) (int, []byte, error) {
		l := len(data)
		if atEOF {
			if l == 0 {
				return 0, nil, nil
			}
			return l, data, nil
		}
		var i int
		for i = 0; i < l; i++ {
			if !isDelim(data[i]) {
				break
			}
		}
		for j := i; j < l; j++ {
			if isDelim(data[j]) {
				return j + 1, data[i:j], nil
			}
		}
		return i, nil, nil
	}
	scanner.Split(split)
	n := getInt(scanner)
	m := getInt(scanner)
	t := getInt(scanner)
	tm := []int{}
	for i := 0; i < n; i++ {
		h := getInt(scanner)
		m := getInt(scanner)
		s := getInt(scanner)
		tm = append(tm, h * 3600 + m * 60 + s)
	}
	ans := make([]int, n)
	left := 0
	uniq := 0
	streakEnd := make(map[int]bool, n)
	sol := false
	for i, ct := range tm {
		for ct - tm[left] >= t {
			if end, ok := streakEnd[left]; ok && end {
				uniq--
			}
			left++
		}
		nextVal := func(i int) int {
			if i > 0 {
				return ans[i - 1] + 1
			}
			return 1
		}
		if uniq == m {
			ans[i] = nextVal(i) - 1
		} else {
			ans[i] = nextVal(i)
			uniq++
		}
		streakEnd[i] = true
		if i > 0 && ans[i - 1] == ans[i] {
			streakEnd[i - 1] = false
		}
		if uniq == m {
			sol = true
		}
	}
	if sol {
		fmt.Printf("%d\n", ans[n - 1])
		for _, a := range ans {
			fmt.Printf("%d\n", a)
		}
	} else {
		fmt.Printf("No solution\n")
	}
	return
}

package main

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

func isDelim(b byte) bool {
	return b == ' ' || b == '\n' || b == ':' || b == '\r'
}

func getString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getInt(scanner *bufio.Scanner) int {
	x, _ := strconv.ParseInt(getString(scanner), 10, 32)
	return int(x)
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	split := func(data []byte, atEOF bool) (int, []byte, error) {
		l := len(data)
		if atEOF {
			if l == 0 {
				return 0, nil, nil
			}
			return l, data, nil
		}
		var i int
		for i = 0; i < l; i++ {
			if !isDelim(data[i]) {
				break
			}
		}
		for j := i; j < l; j++ {
			if isDelim(data[j]) {
				return j + 1, data[i:j], nil
			}
		}
		return i, nil, nil
	}
	scanner.Split(split)
	n := getInt(scanner)
	m := getInt(scanner)
	t := getInt(scanner)
	tm := []int{}
	for i := 0; i < n; i++ {
		h := getInt(scanner)
		m := getInt(scanner)
		s := getInt(scanner)
		tm = append(tm, h * 3600 + m * 60 + s)
	}
	ans := make([]int, n)
	left := 0
	uniq := 0
	streakEnd := make(map[int]bool, n)
	sol := false
	for i, ct := range tm {
		for ct - tm[left] >= t {
			if end, ok := streakEnd[left]; ok && end {
				uniq--
			}
			left++
		}
		nextVal := func(i int) int {
			if i > 0 {
				return ans[i - 1] + 1
			}
			return 1
		}
		if uniq == m {
			ans[i] = nextVal(i) - 1
		} else {
			ans[i] = nextVal(i)
			uniq++
		}
		streakEnd[i] = true
		if i > 0 && ans[i - 1] == ans[i] {
			streakEnd[i - 1] = false
		}
		sol = true
	}
	if sol {
		fmt.Printf("%d\n", ans[n - 1])
		for _, a := range ans {
			fmt.Printf("%d\n", a)
		}
	} else {
		fmt.Printf("No solution\n")
	}
	return
}

package main

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

func isDelim(b byte) bool {
	return b == ' ' || b == '\n' || b == ':' || b == '\r'
}

func getString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getInt(scanner *bufio.Scanner) int {
	x, _ := strconv.ParseInt(getString(scanner), 10, 32)
	return int(x)
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	split := func(data []byte, atEOF bool) (int, []byte, error) {
		l := len(data)
		if atEOF {
			if l == 0 {
				return 0, nil, nil
			}
			return l, data, nil
		}
		var i int
		for i = 0; i < l; i++ {
			if !isDelim(data[i]) {
				break
			}
		}
		for j := i; j < l; j++ {
			if isDelim(data[j]) {
				return j + 1, data[i:j], nil
			}
		}
		return i, nil, nil
	}
	scanner.Split(split)
	n := getInt(scanner)
	m := getInt(scanner)
	t := getInt(scanner)
	tm := []int{}
	for i := 0; i < n; i++ {
		h := getInt(scanner)
		m := getInt(scanner)
		s := getInt(scanner)
		tm = append(tm, h * 3600 + m * 60 + s)
		fmt.Printf("%d %d %d\n", h, m, s)
	}
	ans := make([]int, n)
	left := 0
	uniq := 0
	streakEnd := make(map[int]bool, n)
	sol := false
	for i, ct := range tm {
		fmt.Printf("%d\n", ct)
		for ct - tm[left] >= t {
			if end, ok := streakEnd[left]; ok && end {
				uniq--
			}
			left++
		}
		nextVal := func(i int) int {
			if i > 0 {
				return ans[i - 1] + 1
			}
			return 1
		}
		if uniq == m {
			ans[i] = nextVal(i) - 1
			sol = true
		} else {
			ans[i] = nextVal(i)
			uniq++
		}
		streakEnd[i] = true
		if i > 0 && ans[i - 1] == ans[i] {
			streakEnd[i - 1] = false
		}
	}
	if sol {
		fmt.Printf("%d\n", ans[n - 1])
		for _, a := range ans {
			fmt.Printf("%d\n", a)
		}
	} else {
		fmt.Printf("No solution\n")
	}
	return
}

package main

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

func isDelim(b byte) bool {
	return b == ' ' || b == '\n' || b == ':'
}

func getString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getInt(scanner *bufio.Scanner) int {
	x, _ := strconv.ParseInt(getString(scanner), 10, 32)
	return int(x)
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	split := func(data []byte, atEOF bool) (int, []byte, error) {
		l := len(data)
		if atEOF {
			if l == 0 {
				return 0, data, nil
			}
			return l, data, nil
		}
		var i int
		for i = 0; i < l; i++ {
			if !isDelim(data[i]) {
				break
			}
		}
		for j := i; j < l; j++ {
			if isDelim(data[j]) {
				return j + 1, data[i:j], nil
			}
		}
		return 0, nil, nil
	}
	scanner.Split(split)
	n := getInt(scanner)
	m := getInt(scanner)
	t := getInt(scanner)
	tm := []int{}
	for i := 0; i < n; i++ {
		h := getInt(scanner)
		m := getInt(scanner)
		s := getInt(scanner)
		tm = append(tm, h * 3600 + m * 60 + s)
	}
	fmt.Printf("0\n")
	return
	ans := []int{}
	var left, uniq int
	streakEnd := make(map[int]bool)
	sol := false
	for i, ct := range tm {
		for ct - tm[left] >= t {
			if streakEnd[left] {
				uniq--
			}
			left++
		}
		nextVal := func(i int) int {
			if i > 0 {
				return ans[i - 1] + 1
			}
			return 1
		}
		if uniq == m {
			ans = append(ans, nextVal(i) - 1)
			sol = true
		} else {
			ans = append(ans, nextVal(i))
			uniq++
		}
		streakEnd[i] = true
		if i > 0 && ans[i - 1] == ans[i] {
			streakEnd[i - 1] = false
		}
	}
	if sol {
		fmt.Printf("%d\n", ans[n - 1])
		for _, a := range ans {
			fmt.Printf("%d\n", a)
		}
	} else {
		fmt.Printf("No solution\n")
	}
}

package main

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

func isDelim(b byte) bool {
	return b == ' ' || b == '\n' || b == ':' || b == '\r'
}

func getString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getInt(scanner *bufio.Scanner) int {
	x, _ := strconv.ParseInt(getString(scanner), 10, 32)
	return int(x)
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	split := func(data []byte, atEOF bool) (int, []byte, error) {
		l := len(data)
		if atEOF {
			if l == 0 {
				return 0, nil, nil
			}
			return l, data, nil
		}
		var i int
		for i = 0; i < l; i++ {
			if !isDelim(data[i]) {
				break
			}
		}
		for j := i; j < l; j++ {
			if isDelim(data[j]) {
				return j + 1, data[i:j], nil
			}
		}
		return i, nil, nil
	}
	scanner.Split(split)
	n := getInt(scanner)
	m := getInt(scanner)
	t := getInt(scanner)
	tm := []int{}
	for i := 0; i < n; i++ {
		h := getInt(scanner)
		m := getInt(scanner)
		s := getInt(scanner)
		tm = append(tm, h * 3600 + m * 60 + s)
	}
	ans := make([]int, n)
	left := 0
	uniq := 0
	streakEnd := make(map[int]bool, n)
	sol := false
	for i, ct := range tm {
		for ct - tm[left] >= t {
			if end, ok := streakEnd[left]; ok && end {
				uniq--
			}
			left++
		}
		nextVal := func(i int) int {
			if i > 0 {
				return ans[i - 1] + 1
			}
			return 1
		}
		if uniq == m {
			ans[i] = nextVal(i) - 1
			sol = true
		} else {
			ans[i] = nextVal(i)
			uniq++
		}
		streakEnd[i] = true
		if i > 0 && ans[i - 1] == ans[i] {
			streakEnd[i - 1] = false
		}
	}
	if sol {
		fmt.Printf("%d\n", ans[n - 1])
		for _, a := range ans {
			fmt.Printf("%d\n", a)
		}
	} else {
		fmt.Printf("No solution\n")
	}
	return
}


You have received data from a Bubble bot. You know your task is to make factory facilities, but before you even start, you need to know how big the factory is and how many rooms it has. When you look at the data you see that you have the dimensions of the construction, which is in rectangle shape: N x M. Then in the next N lines you have M numbers. These numbers represent factory tiles and they can go from 0 to 15. Each of these numbers should be looked in its binary form. Because from each number you know on which side the tile has walls. For example number 10 in it's binary form is 1010, which means that it has a wall from the North side, it doesn't have a wall from the East, it has a wall on the South side and it doesn't have a wall on the West side. So it goes North, East, South, West. It is guaranteed that the construction always has walls on it's edges. The input will be correct. Your task is to print the size of the rooms from biggest to smallest.

The first line has two numbers which are N and M, the size of the construction. Both are integers:  $$$n$$$ ($$$1 \leq n \leq 10^3$$$) $$$m$$$ ($$$1 \leq m \leq 10^3$$$) Next N x M numbers represent each tile of construction.

Once you finish processing the data your output consists of one line sorted from biggest to smallest room sizes.

package main

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

var (
	n, m int
	t    [][]int
	r    []int
	cnt  int
	dx   = []int{0, 1, 0, -1}
	dy   = []int{-1, 0, 1, 0}
)

func input() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	scanner.Scan()
	n, _ = strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ = strconv.Atoi(scanner.Text())

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

func dfs(x int, y int) {
	if x < 0 || x >= n || y < 0 || y >= m || t[x][y] < 0 {
		return
	}

	r[cnt]++
	txy := t[x][y]
	t[x][y] = -1
	for i := 0; i < 4; i++ {
		m := txy % 2
		txy /= 2
		if m == 0 {
			dfs(x+dx[i], y+dy[i])
		}
	}
}

func solve() {
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if t[i][j] >= 0 {
				r = append(r, 0)
				dfs(i, j)
				cnt++
			}
		}
	}
	sort.Ints(r)
}

func output() {
	writer := bufio.NewWriter(os.Stdout)
	for i := cnt - 1; i >= 0; i-- {
		writer.WriteString(strconv.Itoa(r[i]) + " ")
	}
	writer.Flush()
}

func main() {
	input()
	solve()
	output()
}

package main

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

func start() {
	n, m := sint(), sint()
	mat := make([][]int8, n)
	vised := make([][]bool, n)
	for i := 0; i < n; i++ {
		mat[i] = make([]int8, m)
		vised[i] = make([]bool, m)
		for j := 0; j < m; j++ {
			mat[i][j] = int8(sint())
		}
	}
	// dfs
	dfs_blocks := func(i, j int) int {
		type vec2 struct {
			x, y int
		}
		vised[i][j] = true
		st := make([]vec2, 1)
		st[0] = vec2{i, j}
		blockCnt := 0
		for len(st) > 0 {
			top := st[len(st)-1]
			st = st[:len(st)-1]
			i, j := top.x, top.y
			if i+1 < n && !(2&mat[i][j] != 0) && !vised[i+1][j] {
				st = append(st, vec2{i + 1, j})
				vised[i+1][j] = true
			}
			if j+1 < m && !(4&mat[i][j] != 0) && !vised[i][j+1] {
				st = append(st, vec2{i, j + 1})
				vised[i][j+1] = true
			}
			if i > 0 && !(8&mat[i][j] != 0) && !vised[i-1][j] {
				st = append(st, vec2{i - 1, j})
				vised[i-1][j] = true
			}
			if j > 0 && !(1&mat[i][j] != 0) && !vised[i][j-1] {
				st = append(st, vec2{i, j - 1})
				vised[i][j-1] = true
			}
			blockCnt++
		}
		return blockCnt
	}
	// algo
	vec := make([]int, 0)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if vised[i][j] == false {
				bCnt := dfs_blocks(i, j)
				vec = append(vec, bCnt)
			}
		}
	}
	sort.Slice(vec, func(i, j int) bool {
		return vec[i] > vec[j]
	})
	printls(vec)
}

func main() {
	start()
	// flush
	writer.Flush()
}

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

// io utils

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

func wstring(s string) {
	writer.WriteString(s)
}
func wrune(r rune) {
	writer.WriteRune(r)
}
func wint(i int) {
	wstring(strconv.Itoa(i))
}
func wlstring(s string) {
	writer.WriteString(s)
	wrune('\n')
}
func wlrune(r rune) {
	writer.WriteRune(r)
	wrune('\n')
}
func wlint(i int) {
	wstring(strconv.Itoa(i))
	wrune('\n')
}

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

func printls(in []int) {
	for _, v := range in {
		wint(v)
		wrune(' ')
	}
	wlstring("")
}

func sint() int {
	i, err := strconv.Atoi(sstring())
	if err != nil {
		panic("sint: Error")
	}
	return i
}

func sints(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = sint()
	}
	return a
}

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

package main

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

func start() {
	n, m := sint(), sint()
	mat := make([][]int8, n)
	vised := make([][]bool, n)
	for i := 0; i < n; i++ {
		mat[i] = make([]int8, m)
		vised[i] = make([]bool, m)
		for j := 0; j < m; j++ {
			mat[i][j] = int8(sint())
		}
	}
	// dfs
	dfs_blocks := func(i, j int) int {
		type vec2 struct {
			x, y int
		}
		if vised[i][j] {
			return 0
		}
		vised[i][j] = true
		st := make([]vec2, 1)
		st[0] = vec2{i, j}
		blockCnt := 0
		for len(st) > 0 {
			top := st[len(st)-1]
			st = st[:len(st)-1]
			i, j := top.x, top.y
			if i+1 < n && !(2&mat[i][j] != 0) && !vised[i+1][j] {
				st = append(st, vec2{i + 1, j})
				vised[i+1][j] = true
			}
			if j+1 < m && !(4&mat[i][j] != 0) && !vised[i][j+1] {
				st = append(st, vec2{i, j + 1})
				vised[i][j+1] = true
			}
			if i > 0 && !(8&mat[i][j] != 0) && !vised[i-1][j] {
				st = append(st, vec2{i - 1, j})
				vised[i-1][j] = true
			}
			if j > 0 && !(1&mat[i][j] != 0) && !vised[i][j-1] {
				st = append(st, vec2{i, j - 1})
				vised[i][j-1] = true
			}
			blockCnt++
		}
		return blockCnt
	}
	// algo
	vec := make([]int, 0)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			bCnt := dfs_blocks(i, j)
			if bCnt > 0 {
				vec = append(vec, bCnt)
			}
		}
	}
	sort.Slice(vec, func(i, j int) bool {
		return vec[i] > vec[j]
	})
	printls(vec)
}

func main() {
	start()
	// flush
	writer.Flush()
}

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

// io utils

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

func wstring(s string) {
	writer.WriteString(s)
}
func wrune(r rune) {
	writer.WriteRune(r)
}
func wint(i int) {
	wstring(strconv.Itoa(i))
}
func wlstring(s string) {
	writer.WriteString(s)
	wrune('\n')
}
func wlrune(r rune) {
	writer.WriteRune(r)
	wrune('\n')
}
func wlint(i int) {
	wstring(strconv.Itoa(i))
	wrune('\n')
}

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

func printls(in []int) {
	for _, v := range in {
		wint(v)
		wrune(' ')
	}
	wlstring("")
}

func sint() int {
	i, err := strconv.Atoi(sstring())
	if err != nil {
		panic("sint: Error")
	}
	return i
}

func sints(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = sint()
	}
	return a
}

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

package main

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

var reader *bufio.Reader
var writer *bufio.Writer

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func print(a ...interface{})            { fmt.Fprint(writer, a...) }
func scan(a ...interface{})             { fmt.Fscan(reader, a...) }

func solve() {
	var n, m int
	scan(&n, &m)

	mat := make([][]int, n)
	visited := make([][]bool, n)
	for i := range mat {
		mat[i] = make([]int, m)
		visited[i] = make([]bool, m)
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			var x int
			scan(&x)
			mat[i][j] = x
		}
	}

	var res []int
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if !visited[i][j] {
				res = append(res, bfs(visited, mat, i, j))
			}
		}
	}

	sort.Slice(res, func(a, b int) bool {
		return res[b] < res[a]
	})
	for i := 0; i < len(res); i++ {
		printf("%d ", res[i])
	}
}

type pair struct {
	x, y int
}

// north, east, south, west
var dx = []int{-1, 0, 1, 0}
var dy = []int{0, 1, 0, -1}
var mask = []int{8, 4, 2, 1}

func bfs(visited [][]bool, mat [][]int, x, y int) int {
	p := pair{x, y}
	visited[x][y] = true
	queue := []pair{p}

	rooms := 1
	for len(queue) != 0 {
		top := queue[0]
		queue = queue[1:]

		for i := 0; i < 4; i++ {
			if (mat[top.x][top.y] & mask[i]) == mask[i] {
				continue
			}
			//			fmt.Println(mat[top.x][top.y], mask[i], (mat[top.x][top.y]&mask[i]) == mask[i])
			newX, newY := top.x+dx[i], top.y+dy[i]
			if newX >= 0 && newX < len(mat) && newY >= 0 && newY < len(mat[0]) && !visited[newX][newY] && (mat[newX][newY]&mask[(i+2)%4]) == 0 {
				//				fmt.Println(mask[i], mat[newX][newY], mat[top.x][top.y], mat[top.x][top.y]&mask[i])
				rooms += 1
				visited[newX][newY] = true
				queue = append(queue, pair{newX, newY})
			}
		}
	}
	return rooms
}

func main() {
	//	os.Stdin, _ = os.OpenFile("input.txt", os.O_RDONLY|os.O_CREATE, 0666)
	//	os.Stdout, _ = os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	reader = bufio.NewReader(os.Stdin)
	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	solve()
}

package main

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

var (
	n, m int
	t    [][]int
	r    []int
	cnt  int
	dx   = []int{0, 1, 0, -1}
	dy   = []int{-1, 0, 1, 0}
)

func input() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	scanner.Scan()
	n, _ = strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ = strconv.Atoi(scanner.Text())

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

func dfs(x int, y int) {
	if x < 0 || x >= n || y < 0 || y >= m || t[x][y] < 0 {
		return
	}

	r[cnt]++
	txy := t[x][y]
	t[x][y] = -1
	for i := 0; i < 4; i++ {
		m := txy % 2
		txy /= 2
		if m == 0 {
			dfs(x+dx[i], y+dy[i])
		}
	}
}

func solve() {
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if t[i][j] >= 0 {
				r = append(r, 0)
				dfs(i, j)
				cnt++
			}
		}
	}
	sort.Ints(r)
}

func output() {
	writer := bufio.NewWriter(os.Stdout)
	for i := cnt - 1; i >= 0; i-- {
		writer.WriteString(strconv.Itoa(r[i]) + " ")
	}
}

func main() {
	input()
	solve()
	output()
}

package main

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

var (
	n, m int
	t    [][]int
	r    []int
	cnt  int
	dx   = []int{0, 1, 0, -1}
	dy   = []int{-1, 0, 1, 0}
)

func input() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	scanner.Scan()
	n, _ = strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ = strconv.Atoi(scanner.Text())

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

func dfs(x int, y int) {
	if x < 0 || x >= n || y < 0 || y >= m || t[x][y] < 0 {
		return
	}

	r[cnt]++
	txy := t[x][y]
	t[x][y] = -1
	for i := 0; i < 4; i++ {
		m := txy % 2
		txy /= 2
		if m == 0 {
			dfs(x+dx[i], y+dy[i])
		}
	}
}

func solve() {
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if t[i][j] >= 0 {
				r = append(r, 0)
				dfs(i, j)
				cnt++
			}
		}
	}
	fmt.Println("here")
	sort.Ints(r)
	fmt.Println("dfdf")
}

func output() {
	writer := bufio.NewWriter(os.Stdout)
	for i := cnt - 1; i >= 0; i-- {
		writer.WriteString(strconv.Itoa(r[i]) + " ")
	}
}

func main() {
	input()
	solve()
	output()
}

package main

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

var (
	n, m int
	t    [][]int
	r    []int
	cnt  int
	dx   = []int{0, 1, 0, -1}
	dy   = []int{-1, 0, 1, 0}
)

func input() {
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscanln(reader, &n, &m)
	t = make([][]int, n)
	for i := 0; i < n; i++ {
		t[i] = make([]int, m)
		for j := 0; j < m; j++ {
			fmt.Fscan(reader, &t[i][j])
		}
	}
	fmt.Println("readed")
}

func dfs(x int, y int) {
	if x < 0 || x >= n || y < 0 || y >= m || t[x][y] < 0 {
		return
	}

	r[cnt]++
	txy := t[x][y]
	t[x][y] = -1
	for i := 0; i < 4; i++ {
		m := txy % 2
		txy /= 2
		if m == 0 {
			dfs(x+dx[i], y+dy[i])
		}
	}
}

func solve() {
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if t[i][j] >= 0 {
				r = append(r, 0)
				dfs(i, j)
				cnt++
			}
		}
	}
	sort.Ints(r)
}

func output() {
	for i := cnt - 1; i >= 0; i-- {
		fmt.Print(r[i], " ")
	}
}

func main() {
	input()
	solve()
	output()
}

package main

import (
	"fmt"
	"sort"
)

var (
	n, m int
	t    [][]int
	r    []int
	cnt  int
	dx   = []int{0, 1, 0, -1}
	dy   = []int{-1, 0, 1, 0}
)

func input() {
	fmt.Scanln(&n, &m)
	t = make([][]int, n)
	for i := 0; i < n; i++ {
		t[i] = make([]int, m)
		for j := 0; j < m; j++ {
			fmt.Scan(&t[i][j])
		}
	}
}

func dfs(x int, y int) {
	if x < 0 || x >= n || y < 0 || y >= m || t[x][y] < 0 {
		return
	}

	r[cnt]++
	txy := t[x][y]
	t[x][y] = -1
	for i := 0; i < 4; i++ {
		m := txy % 2
		txy /= 2
		if m == 0 {
			dfs(x+dx[i], y+dy[i])
		}
	}
}

func solve() {
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if t[i][j] >= 0 {
				r = append(r, 0)
				dfs(i, j)
				cnt++
			}
		}
	}
	sort.Ints(r)
}

func output() {
	for i := cnt - 1; i >= 0; i-- {
		fmt.Print(r[i])
		if i > 0 {
			fmt.Print(" ")
		} else {
			fmt.Println()
		}
	}
}

func main() {
	input()
	solve()
	output()
}

package main

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

var reader *bufio.Reader
var writer *bufio.Writer

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func print(a ...interface{})            { fmt.Fprint(writer, a...) }
func scan(a ...interface{})             { fmt.Fscan(reader, a...) }

func solve() {
	var n, m int
	scan(&n, &m)

	mat := make([][]int, n)
	visited := make([][]bool, n)
	for i := range mat {
		mat[i] = make([]int, m)
		visited[i] = make([]bool, m)
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			var x int
			scan(&x)
			mat[i][j] = x
		}
	}

	var res []int
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if !visited[i][j] {
				res = append(res, bfs(visited, mat, i, j))
			}
		}
	}

	sort.Slice(res, func(a, b int) bool {
		return res[b] < res[a]
	})
	for i := 0; i < len(res); i++ {
		printf("%d", res[i])
		if i != len(res)-1 {
			printf(" ")
		}
	}
}

type pair struct {
	x, y int
}

// north, east, south, west
var dx = []int{-1, 0, 1, 0}
var dy = []int{0, 1, 0, -1}
var mask = []int{8, 4, 2, 1}

func bfs(visited [][]bool, mat [][]int, x, y int) int {
	p := pair{x, y}
	visited[x][y] = true
	queue := []pair{p}

	rooms := 1
	for len(queue) != 0 {
		top := queue[0]
		queue = queue[1:]

		for i := 0; i < 4; i++ {
			if (mat[top.x][top.y] & mask[i]) == mask[i] {
				continue
			}
			//			fmt.Println(mat[top.x][top.y], mask[i], (mat[top.x][top.y]&mask[i]) == mask[i])
			newX, newY := top.x+dx[i], top.y+dy[i]
			if newX >= 0 && newX < len(mat) && newY >= 0 && newY < len(mat[0]) && !visited[newX][newY] && (mat[newX][newY]&mask[(i+2)%4]) == 0 {
				//				fmt.Println(mask[i], mat[newX][newY], mat[top.x][top.y], mat[top.x][top.y]&mask[i])
				rooms += 1
				visited[newX][newY] = true
				queue = append(queue, pair{newX, newY})
			}
		}
	}
	return rooms
}

func main() {
	//	os.Stdin, _ = os.OpenFile("input.txt", os.O_RDONLY|os.O_CREATE, 0666)
	//	os.Stdout, _ = os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	reader = bufio.NewReader(os.Stdin)
	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	solve()
}


You are playing a computer game. To pass the current level, you have to kill a big horde of monsters. In this horde, there are $$$n$$$ monsters standing in the row, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th monster has $$$a_i$$$ health and a special "Death's Blessing" spell of strength $$$b_i$$$ attached to it.You are going to kill all of them one by one. It takes exactly $$$h$$$ seconds to kill a monster with health $$$h$$$.When the $$$i$$$-th monster dies, it casts its spell that increases the health of its neighbors by $$$b_i$$$ (the neighbors of the $$$j$$$-th monster in the row are the monsters on places $$$j - 1$$$ and $$$j + 1$$$. The first and the last monsters have only one neighbor each).After each monster is killed, the row shrinks, so its former neighbors become adjacent to each other (so if one of them dies, the other one is affected by its spell). For example, imagine a situation with $$$4$$$ monsters with health $$$a = [2, 6, 7, 3]$$$ and spells $$$b = [3, 6, 0, 5]$$$. One of the ways to get rid of the monsters is shown below:  $$$2$$$$$$6$$$$$$7$$$$$$3$$$$$$\xrightarrow{6\ s}$$$$$$8$$$$$$13$$$$$$3$$$$$$\xrightarrow{13\ s}$$$$$$8$$$$$$3$$$$$$\xrightarrow{8\ s}$$$$$$6$$$$$$\xrightarrow{6\ s}$$$$$$\{\}$$$$$$3$$$$$$6$$$$$$0$$$$$$5$$$$$$3$$$$$$0$$$$$$5$$$$$$3$$$$$$5$$$$$$5$$$ The first row represents the health of each monster, the second one — the power of the spells. As a result, we can kill all monsters in $$$6 + 13 + 8 + 6$$$ $$$=$$$ $$$33$$$ seconds. Note that it's only an example and may not be the fastest way to get rid of the monsters.What is the minimum time required to kill all monsters in the row?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of monsters in the row. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial health of corresponding monsters. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i \le 10^9$$$), where $$$b_i$$$ is the strength of the spell for the $$$i$$$-th monster. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the minimum possible total time to kill all monsters.

NoteIn the first test case, there is only one monster that will be killed in $$$10$$$ seconds.In the second test case, it's optimal to kill the first monster, the last monster and then the middle one. It will take $$$100 + 100 + (1 + 1 + 1)$$$ $$$=$$$ $$$203$$$ seconds.In the third test case, it's optimal to kill the first monster, then the third one, then the fourth one and finally the second one. It will take $$$2 + 7 + (3 + 0) + (3 + 6 + 5)$$$ $$$=$$$ $$$26$$$ seconds.

package main

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

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

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

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

		aa := make([]int64, n)
		var tot int64
		for _ = range aa {
			var v int64
			fmt.Fscan(in, &v)
			tot += v
		}

		for i := range aa {
			fmt.Fscan(in, &aa[i])
		}

		z := aa[0]
		for i := range aa {
			tot += aa[i]
			if aa[i] > z {
				z = aa[i]
			}
		}
		fmt.Fprintln(out, tot-z)
	}
}

package main

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

var (
	t, n, m  int
	x, y     int64
	row, col []int64
	a        []node
)

type node struct {
	x, y int64
	f    bool
}

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n)
		a = make([]node, n)
		for i := 0; i < n; i++ {
			if i == 0 || i == n-1 {
				a[i].f = true
			} else {
				a[i].f = false
			}
			scan(&a[i].x)
		}
		for i := 0; i < n; i++ {
			scan(&a[i].y)
		}
		sort.Slice(a, func(i, j int) bool {
			return a[i].y <= a[j].y
		})
		var ans int64 = 0
		var dt int64 = 0
		for i := 0; i < n; i++ {
			ans += a[i].x
			if i != n-1 {
				dt += a[i].y
			}
		}
		println(ans + dt)
	}
}

//

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

func init() {
	r = bufio.NewReader(os.Stdin)
	w = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(r, a...)
}

func println(a ...any) {
	fmt.Fprintln(w, a...)
}

func flush() {
	w.Flush()
}

package main

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

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

// source: https://codeforces.com/contest/1749/problem/B?locale=en
func solve() {
	n, a := _readArr()
	_, b := _readArr(n)
	_print(_sum(a...) + _sum(b...) - _max(b...))
}

func solve_() {
	n := _readInt()
	_, a := _readArr(n)
	_, b := _readArr(n)
	res := 0

	cast := func(x int) {
		d := b[x]
		if x > 0 {
			a[x-1] += d
		}
		if x < len(a)-1 {
			a[x+1] += d
		}
		a = append(a[:x], a[x+1:]...)
		b = append(b[:x], b[x+1:]...)
	}

	next := func() int {
		mi, mv := 0, b[0]
		for i := 1; i < len(b)-1; i++ {
			if b[i]*2 < mv {
				mi = i
				mv = b[i] * 2
			}
		}
		if i := len(b) - 1; b[i] < mv {
			mi = i
		}
		return mi
	}

	for len(a) > 0 {
		i := next()
		res += a[i]
		cast(i)
	}

	_print(res)
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscanln(in, &t); t > 0; t-- {
		solve()
	}
}

// ====
func _readInt() int {
	var x int
	fmt.Fscan(in, &x)
	return x
}
func _readStr() string {
	var x string
	fmt.Fscan(in, &x)
	return x
}
func _readArr(x ...int) (int, []int) {
	var n int
	if len(x) == 0 {
		fmt.Fscan(in, &n)
	} else {
		n = x[0]
	}
	var v = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	return n, v
}
func _print(x ...any) {
	fmt.Fprintln(out, x...)
}
func _max(x ...int) int {
	mi := 0
	for i := 1; i < len(x); i++ {
		if x[i] > x[mi] {
			mi = i
		}
	}
	return x[mi]
}
func _min(x ...int) int {
	mi := 0
	for i := 1; i < len(x); i++ {
		if x[i] < x[mi] {
			mi = i
		}
	}
	return x[mi]
}
func _sum(x ...int) int {
	res := 0
	for _, i := range x {
		res += i
	}
	return res
}
func _abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func _sortStr(x string) string {
	r := []rune(x)
	sort.Slice(r, func(i, j int) bool {
		return r[i] < r[j]
	})
	return string(r)
}
func _reverseInts(x []int) {
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
}
func _reverseStr(s string) string {
	x := []rune(s)
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
	return string(x)
}
func _makeMatrix(n, m int) [][]int {
	x := make([][]int, n)
	for i := range x {
		x[i] = make([]int, m)
	}
	return x
}

package main

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

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

type Monster struct {
	health   int
	strength int
}

func minimunKill(monsters []Monster) int {
	if len(monsters) < 2 {
		return monsters[0].health
	}

	sort.Slice(monsters, func(i, j int) bool {
		return monsters[i].strength < monsters[j].strength
	})

	rs := 0
	for i := 0; i < len(monsters); i++ {
		rs += monsters[i].health + monsters[i].strength
	}

	return rs - monsters[len(monsters)-1].strength
}

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

		brr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(reader, "%d", &brr[i])
		}
		fmt.Fscanf(reader, "\n")
		monsters := make([]Monster, len(arr))
		for i := 0; i < len(arr); i++ {
			monsters[i].health = arr[i]
			monsters[i].strength = brr[i]
		}

		fmt.Println(minimunKill(monsters))
		test--
	}
}

package main

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

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

type Monster struct {
	health   int
	strength int
}

func minimun(arr []int, brr []int) int {
	if len(arr) < 2 {
		return arr[0]
	}

	monsters := make([]Monster, len(arr))
	for i := 0; i < len(arr); i++ {
		monsters[i].health = arr[i]
		monsters[i].strength = brr[i]
	}

	sort.Slice(monsters, func(i, j int) bool {
		return monsters[i].strength < monsters[j].strength
	})

	rs := 0
	for i := 0; i < len(arr); i++ {
		rs += monsters[i].health + monsters[i].strength
	}

	return rs - monsters[len(monsters) -1].strength
}

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

		brr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(reader, "%d", &brr[i])
		}
		fmt.Fscanf(reader, "\n")
		fmt.Println(minimun(arr, brr))
		test--
	}
}

package main

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

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	var t, n int
	Fscan(r, &t)
	for t > 0{
		s := 0
		t--
		Fscan(r, &n)
		a := make([]int, n)
		b := make([]int, n)
		for i := range a{
			Fscan(r, &a[i])
			s += a[i]
		}
		for i := range b{
			Fscan(r, &b[i])
			s += b[i]
		}
		sort.Ints(b)
		s -= b[n-1]
		Fprintln(w, s)
	}
}

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

func debug(a ...interface{}) {
	for _, e := range a {
		printf("%v ", e)
	}
	printf("\n")
	writer.Flush()
}

func solve() {
	var n int
	scanf("%d\n", &n)
	var res int64 = 0
	a := make([]int64, n)
	for i:=0; i<n; i++ {
		scanf("%d ", &a[i])
		res += a[i]
	}
	scanf("\n")

	b := make([]int64, n)
	var mx int64 = -1
	for i:=0; i<n; i++ {
		scanf("%d ", &b[i])
		if b[i] > mx {
			mx = b[i]
		}
		res += b[i]
	}
	scanf("\n")

	res -= mx
	printf("%v\n", res)
}

func main() {
	defer writer.Flush()

	var T int
	scanf("%d\n", &T)
	for tt:=1; tt<=T; tt++ {
		solve()
	}
}

package main

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

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

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

		var sum, max, temp int
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &temp)
			sum += temp
		}
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &temp)
			sum += temp
			if temp > max { max = temp }
		}

		fmt.Fprintln(w, sum-max)

	}

}

package main

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

const cf = true

func solve() {
	var n int
	fmt.Fscan(in, &n)
	a, b := make([]int, n), make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}
	for i := range b {
		fmt.Fscan(in, &b[i])
	}
	i1, i2 := 0, n-1
	ans := 0
	for i1 <= i2 {
		if b[i1] < b[i2] {
			ans += a[i1]
			if i1 < n-1 {
				a[i1+1] += b[i1]
			}
			i1++
		} else {
			ans += a[i2]
			if i2 > 0 {
				a[i2-1] += b[i2]
			}
			i2--
		}
	}
	fmt.Fprintln(out, ans)
}

func main() {
	defer out.Flush()
	t := 1
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		solve()
	}
}

func reverse[T any](arr []T) {
	n := len(arr)
	for i := 0; i < n/2; i++ {
		arr[i], arr[n-i-1] = arr[n-i-1], arr[i]
	}
}

func reversed[T any](arr []T) (res []T) {
	res = make([]T, len(arr))
	copy(res, arr)
	reverse(res)
	return res
}

func GCD(a, b int) int {
	for a != b {
		if a > b {
			a -= b
		} else {
			b -= a
		}
	}

	return a
}

func ConvertInt(val string, base, toBase int) (string, error) {
	i, err := strconv.ParseInt(val, base, 64)
	if err != nil {
		return "", err
	}
	return strconv.FormatInt(i, toBase), nil
}

type set[T Ordered] struct {
	itms map[T]struct{}
}

func (s *set[T]) init() {
	if s.itms == nil {
		s.itms = make(map[T]struct{})
	}
}

func (s *set[T]) add(item T) *set[T] {
	s.init()
	s.itms[item] = exists
	return s
}

func (s *set[T]) remove(item T) *set[T] {
	s.init()
	delete(s.itms, item)
	return s
}

func (s *set[T]) has(item T) bool {
	s.init()
	_, c := s.itms[item]
	return c
}

func (s *set[T]) sortedItems() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	sort.Slice(items, func(i, j int) bool {
		return items[i] < items[j]
	})
	return items
}

func (s *set[T]) items() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	return items
}

func (s *set[T]) size() int {
	s.init()
	return len(s.itms)
}

var exists = struct{}{}

const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1

func reverseStr(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Ordered interface {
	Integer | Float | ~string
}

func abs[T Signed](x T) T {
	if x < 0 {
		return -x
	}
	return x
}

func min[T Ordered](x, y T) T {
	if x < y {
		return x
	}
	return y
}

func max[T Ordered](x, y T) T {
	if x > y {
		return x
	}
	return y
}

var (
	in  = getReader()
	out = getWriter()
)

func getReader() *bufio.Reader {
	if cf {
		return bufio.NewReader(os.Stdin)
	} else {
		in, _ := os.Open("input.txt")
		return bufio.NewReader(in)
	}
}

func getWriter() *bufio.Writer {
	if cf {
		return bufio.NewWriter(os.Stdout)
	} else {
		out, _ := os.Create("output.txt")
		return bufio.NewWriter(out)
	}
}

package main

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

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

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

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

		aa := make([]int64, n)
		var tot int64
		for _ = range aa {
			var v int64
			fmt.Fscan(in, &v)
			tot += v
		}

		for i := range aa {
			fmt.Fscan(in, &aa[i])
		}

		mm := make([]bool, n)
		l, r := 0, n-1
		for l != r {
			v := aa[l]
			pos := l
			if aa[l] > aa[r] {
				v = aa[r]
				pos = r
			}
			for i := l + 1; i < r; i++ {
				if !mm[i] && aa[i]*2 <= v {
					v = aa[i] * 2
					pos = i
				}
			}
			mm[pos] = true
			tot += v
			for l < n && mm[l] {
				l++
			}
			for r > 0 && mm[r] {
				r--
			}
		}
		fmt.Fprintln(out, tot)
	}
}

package main

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

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

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

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

		aa := make([][2]int64, n)
		for i := range aa {
			fmt.Fscan(in, &aa[i][0])
		}
		for i := range aa {
			var v int64
			fmt.Fscan(in, &v)
			aa[i][1] = v
		}

		var tot int64
		for len(aa) > 1 {
			mn := aa[0][1]
			var mIdx int
			if aa[0][1] > aa[len(aa)-1][1] {
				mn = aa[len(aa)-1][1]
				mIdx = len(aa) - 1
			}

			for i := 1; i < len(aa)-1; i++ {
				if aa[i][1]*2 < mn {
					mn = aa[i][1]
					mIdx = i
				}
			}

			// cut
			if mIdx == 0 {
				aa[1][0] += aa[0][1]
			} else if mIdx == len(aa)-1 {
				aa[len(aa)-2][0] += aa[len(aa)-1][1]
			} else {
				aa[mIdx-1][0] += aa[mIdx][1]
				aa[mIdx+1][0] += aa[mIdx][1]
			}
			tot += aa[mIdx][0]
			aa = append(aa[:mIdx], aa[mIdx+1:]...)
		}
		fmt.Fprintln(out, tot+aa[0][0])
	}
}

package main

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

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

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

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

		aa := make([][2]int64, n)
		for i := range aa {
			fmt.Fscan(in, &aa[i][0])
		}
		for i := range aa {
			var v int64
			fmt.Fscan(in, &v)
			aa[i][1] = v
		}

		var tot int64
		for len(aa) > 1 {
			mn := aa[0][1]
			var mIdx int
			if aa[0][1] > aa[len(aa)-1][1] {
				mn = aa[len(aa)-1][1]
				mIdx = len(aa) - 1
			}

			for i := 1; i < len(aa)-1; i++ {
				if aa[i][1] < mn {
					mn = aa[i][1]
					mIdx = i
				}
			}

			// cut
			if mIdx == 0 {
				aa[1][0] += aa[0][1]
			} else if mIdx == len(aa)-1 {
				aa[len(aa)-2][0] += aa[len(aa)-1][1]
			} else {
				aa[mIdx-1][0] += aa[mIdx][1]
				aa[mIdx+1][0] += aa[mIdx][1]
			}
			tot += aa[mIdx][0]
			aa = append(aa[:mIdx], aa[mIdx+1:]...)
		}
		fmt.Fprintln(out, tot+aa[0][0])
	}
}

package main

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

var (
	t, n, m  int
	x, y     int64
	row, col []int64
	a        []node
)

type node struct {
	x, y int64
	f    bool
}

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n)
		a = make([]node, n)
		for i := 0; i < n; i++ {
			if i == 0 || i == n-1 {
				a[i].f = true
			} else {
				a[i].f = false
			}
			scan(&a[i].x)
		}
		for i := 0; i < n; i++ {
			scan(&a[i].y)
		}
		sort.Slice(a, func(i, j int) bool {
			return a[i].y <= a[j].y
		})
		var ans int64 = 0
		var dt int64 = 0
		for i := 0; i < n; i++ {
			ans += a[i].x
			if i != n-1 {
				if a[i].f {
					dt += a[i].y
				} else {
					dt += a[i].y * 2
				}
			}
		}
		println(ans + dt)
	}
}

//

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

func init() {
	r = bufio.NewReader(os.Stdin)
	w = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(r, a...)
}

func println(a ...any) {
	fmt.Fprintln(w, a...)
}

func flush() {
	w.Flush()
}

package main

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

var (
	t, n, m, x, y int
	row, col      []int
	a             []node
)

type node struct {
	x, y int
	f    bool
}

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n)
		a = make([]node, n)
		for i := 0; i < n; i++ {
			if i == 0 || i == n-1 {
				a[i].f = true
			} else {
				a[i].f = false
			}
			scan(&a[i].x)
		}
		for i := 0; i < n; i++ {
			scan(&a[i].y)
		}
		sort.Slice(a, func(i, j int) bool {
			return a[i].y <= a[j].y
		})
		ans := 0
		dt := 0
		for i := 0; i < n; i++ {
			ans += a[i].x
			if i != n-1 {
				if a[i].f {
					dt += a[i].y
				} else {
					dt += a[i].y * 2
				}
			}
		}
		println(ans + dt)
	}
}

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

func init() {
	r = bufio.NewReader(os.Stdin)
	w = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(r, a...)
}

func println(a ...any) {
	fmt.Fprintln(w, a...)
}

func flush() {
	w.Flush()
}

package main

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

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

// source: https://codeforces.com/contest/1749/problem/B?locale=en
func solve() {
	n := _readInt()
	_, a := _readArr(n)
	_, b := _readArr(n)
	res := 0

	cast := func(x int) {
		d := b[x]
		if x > 0 {
			a[x-1] += d
		}
		if x < len(a)-1 {
			a[x+1] += d
		}
		a = append(a[:x], a[x+1:]...)
		b = append(b[:x], b[x+1:]...)
	}

	next := func() int {
		mi, mv := 0, b[0]
		for i := 1; i < len(b)-1; i++ {
			if b[i]*2 < mv {
				mi = i
				mv = b[i] * 2
			}
		}
		if i := len(b) - 1; b[i] < mv {
			mi = i
		}
		return mi
	}

	for len(a) > 0 {
		i := next()
		res += a[i]
		cast(i)
	}

	_print(res)
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscanln(in, &t); t > 0; t-- {
		solve()
	}
}

// ====
func _readInt() int {
	var x int
	fmt.Fscan(in, &x)
	return x
}
func _readStr() string {
	var x string
	fmt.Fscan(in, &x)
	return x
}
func _readArr(x ...int) (int, []int) {
	var n int
	if len(x) == 0 {
		fmt.Fscan(in, &n)
	} else {
		n = x[0]
	}
	var v = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	return n, v
}
func _print(x ...any) {
	fmt.Fprintln(out, x...)
}
func _max(x, y int) int {
	if x > y {
		return x
	}
	return y
}
func _min(x, y int) int {
	if x < y {
		return x
	}
	return y
}
func _abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func _sortStr(x string) string {
	r := []rune(x)
	sort.Slice(r, func(i, j int) bool {
		return r[i] < r[j]
	})
	return string(r)
}
func _reverseInts(x []int) {
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
}
func _reverseStr(s string) string {
	x := []rune(s)
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
	return string(x)
}
func _makeMatrix(n, m int) [][]int {
	x := make([][]int, n)
	for i := range x {
		x[i] = make([]int, m)
	}
	return x
}