You are given an integer $$$k$$$ and an undirected tree, consisting of $$$n$$$ vertices.The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of this tree.You are about to remove a set of edges from the tree. The tree splits into multiple smaller trees when the edges are removed. The set of edges is valid if all the resulting trees have diameter less than or equal to $$$k$$$.Two sets of edges are different if there is an edge such that it appears in only one of the sets.Count the number of valid sets of edges modulo $$$998\,244\,353$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 5000$$$, $$$0 \le k \le n - 1$$$) — the number of vertices of the tree and the maximum allowed diameter, respectively. Each of the next $$$n-1$$$ lines contains a description of an edge: two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$, $$$v \neq u$$$). The given edges form a tree.

Print a single integer — the number of valid sets of edges modulo $$$998\,244\,353$$$.

NoteIn the first example the diameter of the given tree is already less than or equal to $$$k$$$. Thus, you can choose any set of edges to remove and the resulting trees will have diameter less than or equal to $$$k$$$. There are $$$2^3$$$ sets, including the empty one.In the second example you have to remove the only edge. Otherwise, the diameter will be $$$1$$$, which is greater than $$$0$$$.Here are the trees for the third and the fourth examples:

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1499F(_r io.Reader, out io.Writer) {
	const mod = 998244353
	in := bufio.NewReader(_r)
	var n, k, v, w int
	Fscan(in, &n, &k)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	var f func(v, fa int) []int64
	f = func(v, fa int) []int64 {
		res := []int64{1}
		for _, w := range g[v] {
			if w == fa {
				continue
			}
			r := f(w, v)
			s := int64(0)
			for _, v := range r {
				s += v
			}
			s %= mod
			a := make([]int64, max(len(res), len(r)+1))
			for i, v := range res {
				a[i] = v * s
			}
			for i, v := range res {
				for j, w := range r {
					if i+j >= k {
						break
					}
					a[max(i, j+1)] += v * w % mod
				}
			}
			for i, v := range a {
				a[i] = v % mod
			}
			res = a
		}
		return res
	}
	res := f(0, -1)
	ans := int64(0)
	for _, v := range res {
		ans += v
	}
	Fprint(out, ans%mod)
}

func main() { CF1499F(os.Stdin, os.Stdout) }
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

package main

import . "fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	const P = 998244353
	var n, k, v, w int
	Scan(&n, &k)
	g := make([][]int, n+1)
	for i := 1; i < n; i++ {
		Scan(&v, &w)
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}
	var f func(v, p int) []int64
	f = func(v, p int) []int64 {
		res := []int64{1}
		for _, w := range g[v] {
			if w == p {
				continue
			}
			r := f(w, v)
			s := int64(0)
			for _, v := range r {
				s += v
			}
			s %= P
			a := make([]int64, max(len(res), len(r)+1))
			for i, v := range res {
				a[i] = v * s
			}
			for i, v := range res {
				for j, w := range r {
					if i+j >= k {
						break
					}
					a[max(i, j+1)] += v * w % P
				}
			}
			for i, v := range a {
				a[i] = v % P
			}
			res = a
		}
		return res
	}
	s := int64(0)
	for _, v := range f(1, 0) {
		s += v
	}
	Print(s % P)
}

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

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"runtime/debug"
)

// github.com/EndlessCheng/codeforces-go
func init() { debug.SetGCPercent(-1) }

func CF1499F(_r io.Reader, out io.Writer) {
	const mod = 998244353
	in := bufio.NewReader(_r)
	var n, k, v, w int
	Fscan(in, &n, &k)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	var f func(v, fa int) []int64
	f = func(v, fa int) []int64 {
		res := []int64{1}
		for _, w := range g[v] {
			if w == fa {
				continue
			}
			r := f(w, v)
			s := int64(0)
			for _, v := range r {
				s += v
			}
			s %= mod
			a := make([]int64, max(len(res), len(r)+1))
			for i, v := range res {
				a[i] = v * s
			}
			for i, v := range res {
				for j, w := range r {
					if i+j >= k {
						break
					}
					a[max(i, j+1)] += v * w % mod
				}
			}
			for i, v := range a {
				a[i] = v % mod
			}
			res = a
		}
		return res
	}
	res := f(0, -1)
	ans := int64(0)
	for _, v := range res {
		ans += v
	}
	Fprint(out, ans%mod)
}

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

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

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n, k := readTwoNums(reader)
	E := make([][]int, n-1)
	for i := 0; i < n-1; i++ {
		E[i] = readNNums(reader, 2)
	}
	res := solve(n, k, E)
	fmt.Println(res)
}

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
}

const MOD = 998244353

func modAdd(a, b int64) int64 {
	a += b
	a %= MOD
	return a
}

func modMul(a, b int64) int64 {
	a *= b
	a %= MOD
	return a
}

func solve(n, k int, E [][]int) int {
	g := NewGraph(n, len(E)*2)
	for _, e := range E {
		u, v := e[0], e[1]
		g.AddEdge(u-1, v-1)
		g.AddEdge(v-1, u-1)
	}

	dp := make([][]int64, n)
	for i := 0; i < n; i++ {
		dp[i] = make([]int64, n+1)
	}

	var dfs func(p, u int) int

	aux := make([]int64, n+1)

	dfs = func(p, u int) int {
		dp[u][0] = 1
		h := 1
		for i := g.nodes[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p == v {
				continue
			}
			vh := dfs(u, v)
			uh := max(h, vh+1)

			for a := 0; a < uh; a++ {
				aux[a] = 0
			}

			for a := 0; a < h; a++ {
				for b := 0; b < vh; b++ {
					if a+b+1 <= k {
						aux[max(a, b+1)] = modAdd(aux[max(a, b+1)], modMul(dp[u][a], dp[v][b]))
					}
					if a <= k && b <= k {
						aux[a] = modAdd(aux[a], modMul(dp[u][a], dp[v][b]))
					}
				}
			}
			h = uh
			for a := 0; a < h; a++ {
				dp[u][a] = aux[a]
			}
		}
		return h
	}
	dfs(-1, 0)

	var res int64
	for i := 0; i <= k; i++ {
		res = modAdd(res, dp[0][i])
	}

	return int(res)
}

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

type Graph struct {
	nodes []int
	next  []int
	to    []int
	cur   int
}

func NewGraph(n int, e int) Graph {
	nodes := make([]int, n)
	next := make([]int, e+3)
	to := make([]int, e+3)
	var cur int
	return Graph{nodes, next, to, cur}
}

func (g *Graph) AddEdge(u, v int) {
	g.cur++
	g.next[g.cur] = g.nodes[u]
	g.nodes[u] = g.cur
	g.to[g.cur] = v
}

package main
import . "fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	const P = 998244353
	var n, k, v, w int
	Scan(&n, &k)
	g := make([][]int, n+1)
	for i := 1; i < n; i++ {
		Scan(&v, &w)
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	var f func(v, p int) []int64
	f = func(v, p int) []int64 {
		dp := []int64{1}
		for _, w := range g[v] {
			if w == p {
				continue
			}
			r := f(w, v)
			s := int64(0)
			for _, v := range r {
				s += v
			}
			s %= P
			d := make([]int64, max(len(dp), len(r)+1))
			for i, v := range dp {
				d[i] = v * s
			}
			for i, v := range dp {
				for j, w := range r {
					if i+j >= k {
						break
					}
					i = max(i, j+1)
					d[i] = (d[i] + v*w) % P
				}
			}
			dp = d
		}
		return dp
	}
	s := int64(0)
	for _, v := range f(1, 0) {
		s += v
	}
	Print(s % P)
}

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

package main
import . "fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	const P = 998244353
	var n, k, v, w int
	Scan(&n, &k)
	g := make([][]int, n+1)
	for i := 1; i < n; i++ {
		Scan(&v, &w)
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	var f func(v, p int) []int64
	f = func(v, p int) []int64 {
		dp := []int64{1}
		for _, w = range g[v] {
			if w == p {
				continue
			}
			r := f(w, v)
			s := int64(0)
			for _, v := range r {
				s += v
			}
			s %= P
			d := make([]int64, max(len(dp), len(r)+1))
			for i, v := range dp {
				d[i] = v * s
			}
			for i, v := range dp {
				for j, w := range r {
					if i+j >= k {
						break
					}
					i = max(i, j+1)
					d[i] = (d[i] + v*w) % P
				}
			}
			dp = d
		}
		return dp
	}
	s := int64(0)
	for _, v := range f(1, 0) {
		s += v
	}
	Print(s % P)
}

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


Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought $$$n$$$ integers, now it's time to distribute them between his friends rationally...Lee has $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ in his backpack and he has $$$k$$$ friends. Lee would like to distribute all integers in his backpack between his friends, such that the $$$i$$$-th friend will get exactly $$$w_i$$$ integers and each integer will be handed over to exactly one friend.Let's define the happiness of a friend as the sum of the maximum and the minimum integer he'll get.Lee would like to make his friends as happy as possible, in other words, he'd like to maximize the sum of friends' happiness. Now he asks you to calculate the maximum sum of friends' happiness.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$3t$$$ lines contain test cases — one per three lines. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le n$$$) — the number of integers Lee has and the number of Lee's friends. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the integers Lee has. The third line contains $$$k$$$ integers $$$w_1, w_2, \ldots, w_k$$$ ($$$1 \le w_i \le n$$$; $$$w_1 + w_2 + \ldots + w_k = n$$$) — the number of integers Lee wants to give to each friend.  It's guaranteed that the sum of $$$n$$$ over test cases is less than or equal to $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the maximum sum of happiness Lee can achieve.

NoteIn the first test case, Lee should give the greatest integer to the first friend (his happiness will be $$$17 + 17$$$) and remaining integers to the second friend (his happiness will be $$$13 + 1$$$).In the second test case, Lee should give $$$\{10, 10, 11\}$$$ to the first friend and to the second friend, so the total happiness will be equal to $$$(11 + 10) + (11 + 10)$$$In the third test case, Lee has four friends and four integers, it doesn't matter how he distributes the integers between his friends.

package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var T int
	con.Scan(&T)
	for testcase := 0; testcase < T; testcase++ {
		var n, k int
		con.Scan(&n, &k)
		a := make([]int64, n)
		for i := 0; i < n; i++ {
			con.Scan(&a[i])
		}
		sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })
		w := make([]int, k)
		for i := 0; i < k; i++ {
			con.Scan(&w[i])
		}
		sort.Slice(w, func(i, j int) bool { return w[i] > w[j] })
		var sum int64
		for i := n - k; i < n; i++ {
			sum += a[i]
		}
		j := 0
		for i, l := range w {
			if l == 1 {
				sum += a[n-k+i]
				continue
			}
			sum += a[j]
			j += l - 1
		}
		con.Println(sum)
	}
	return nil
}

package main

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

var reader *bufio.Reader

func parseInt(s string) int {
	return int(parseInt64(s))
}

func parseInt64(s string) int64 {
	x, _ := strconv.ParseInt(s, 10, 64)
	return x
}

func readLine() string {
	if reader == nil {
		reader = bufio.NewReader(os.Stdin)
	}
	s, _ := reader.ReadString('\n')
	return strings.TrimSuffix(s, "\n")
}

func readFields() []string {
	return strings.Fields(readLine())
}

var t int

func main() {
	Scan(&t)
    readFields()
	for tc := 0; tc < t; tc++ {
	    nk := readFields()
		n, k := parseInt(nk[0]), parseInt(nk[1])
		af := readFields()
		ff := readFields()
		as := make([]int64, n)
		fs := make([]int, k)
		for i := range as {
			as[i] = parseInt64(af[i])
		}
		for i := range fs {
			fs[i] = parseInt(ff[i]) - 1
		}

		sort.Slice(as, func(i, j int) bool {
			return as[i] < as[j]
		})
		sort.Ints(fs)

		var ans int64 = 0
		for i := n - 1; n-k-1 < i; i-- {
			ans += int64(as[i])
		}

		j := 0
		for i := k - 1; 0 <= i; i-- {
			if fs[i] != 0 {
				ans += int64(as[j])
				j += fs[i]
			} else {
				ans += int64(as[n-i-1])
			}
		}

		Println(ans)
	}
}

package main

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

var reader *bufio.Reader

func parseInt(s string) int {
	return int(parseInt64(s))
}

func parseInt64(s string) int64 {
	x, _ := strconv.ParseInt(s, 10, 64)
	return x
}

func readLine() string {
	if reader == nil {
		reader = bufio.NewReader(os.Stdin)
	}
	s, _ := reader.ReadString('\n')
	return strings.TrimSuffix(s, "\n")
}

func readFields() []string {
	return strings.Fields(readLine())
}

var t int

func main() {
    t := parseInt(readFields()[0])
	for tc := 0; tc < t; tc++ {
	    nk := readFields()
		n, k := parseInt(nk[0]), parseInt(nk[1])
		af := readFields()
		ff := readFields()
		as := make([]int64, n)
		fs := make([]int, k)
		for i := range as {
			as[i] = parseInt64(af[i])
		}
		for i := range fs {
			fs[i] = parseInt(ff[i]) - 1
		}

		sort.Slice(as, func(i, j int) bool {
			return as[i] < as[j]
		})
		sort.Ints(fs)

		var ans int64 = 0
		for i := n - 1; n-k-1 < i; i-- {
			ans += int64(as[i])
		}

		j := 0
		for i := k - 1; 0 <= i; i-- {
			if fs[i] != 0 {
				ans += int64(as[j])
				j += fs[i]
			} else {
				ans += int64(as[n-i-1])
			}
		}

		Println(ans)
	}
}

package main

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

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, k := readTwoNums(reader)
		A := readNNums(reader, n)
		W := readNNums(reader, k)
		fmt.Println(solve(n, k, A, W))
	}
}

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, k int, A []int, W []int) int64 {
	sort.Ints(A)
	reverse(A)
	sort.Ints(W)

	var res int64
	var i, j = 0, n - 1

	var u int

	for u < k && W[u] == 1 {
		res += 2 * int64(A[i])
		i++
		u++
	}

	reverse(W[u:])

	for u < k {
		res += int64(A[i])
		res += int64(A[j])
		j -= W[u] - 1
		i++
		u++
	}

	return res
}

func reverse(arr []int) {
	for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
		arr[i], arr[j] = arr[j], arr[i]
	}
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < cases; i++ {
		nkss := readLine(reader)
		ans := readLine(reader)
		wks := readLine(reader)
		nks := strings.Split(string(nkss), " ")
		n, _ := strconv.ParseInt(nks[0], 10, 64)
		k, _ := strconv.ParseInt(nks[1], 10, 64)
		anarr := strings.Split(string(ans), " ")
		an := make([]int64, n)
		for i:=int64(0);i<n;i++ {
			an[i],_ = strconv.ParseInt(anarr[i], 10, 64)
		}
		wkarr := strings.Split(string(wks), " ")
		wk := make([]int64, k)
		for i:=int64(0);i<k;i++ {
			wk[i], _ = strconv.ParseInt(wkarr[i], 10, 64)
		}
		sort.Slice(an, func(i, j int) bool {
			return an[i] < an[j]
		})
		sort.Slice(wk, func(i, j int) bool {
			return wk[i] < wk[j]
		})
		sum := int64(0)
		highw := make([]int64, k)
		for i:=int64(0);i<k;i++ {
			h := an[n-i-1]
			highw[i] = h
			sum += h // 加上头
			// fmt.Println(sum)
		}
		// fmt.Println(highw)
		start := n - k
		for i:=int64(0);i<k;i++ {
			if wk[i] == 1 {
				sum += highw[i]
			} else {
				low := start - (wk[i] - 1)
				sum += an[low]
				start = low
			}
			// fmt.Println(sum)
		}
		fmt.Println(sum)
	}
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

/*
URL:
https://codeforces.com/contest/1369/problem/C
*/

package main

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

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

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

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

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

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

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

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

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

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

var (
	t int

	n, k int
	A    []int64
	W    []int64
)

func main() {
	t = ReadInt()

	for i := 0; i < t; i++ {
		n, k = ReadInt2()
		A = ReadInt64Slice(n)
		W = ReadInt64Slice(k)

		solve()
	}
}

func solve() {
	ans := int64(0)
	I := make([][]int64, k)

	sort.Slice(A, func(i, j int) bool { return A[i] > A[j] })
	sort.Slice(W, func(i, j int) bool { return W[i] < W[j] })
	for i := 0; i < k; i++ {
		W[i]--
	}

	for i := 0; i < k; i++ {
		// ans += A[i]
		I[i] = append(I[i], A[i])
	}

	cur := k
	for i := 0; i < k; i++ {
		for j := 0; j < int(W[i]); j++ {
			if j == int(W[i])-1 {
				// ans += A[cur]
				I[i] = append(I[i], A[cur])
			}
			cur++
		}
	}

	for i := 0; i < k; i++ {
		ans += Min(I[i]...)
		ans += Max(I[i]...)
	}

	fmt.Println(ans)
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

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

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

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

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

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

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

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

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

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

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

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

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

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

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

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

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

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

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

package main

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

func main() {
	var nTest, n, k int
	var a [200000]int64
	var w [200000]int

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

	fmt.Fscan(in, &nTest)
	for t := 0; t < nTest; t++ {
		fmt.Fscan(in, &n, &k)

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

		for i := 0; i < k; i++ {
			fmt.Fscan(in, &w[i])
		}

		sort.Slice(a[:n], func(i, j int) bool {
			return a[i] > a[j]
		})

		sort.Slice(w[:k], func(i, j int) bool {
			return w[i] < w[j]
		})

		res := int64(0)
		j := k - 1
		for i := 0; i < k; i++ {
			res += a[i]
			if w[i] != 1 {
				j += w[i] - 1
				res += a[j]
			} else {
				res += a[i]
			}
		}
		fmt.Fprintln(out, res)
	}

	out.Flush()
}

package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var T int
	con.Scan(&T)
	for testcase := 0; testcase < T; testcase++ {
		var n, k int
		con.Scan(&n, &k)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			con.Scan(&a[i])
		}
		sort.Ints(a)
		w := make([]int, k)
		for i := 0; i < k; i++ {
			con.Scan(&w[i])
		}
		sort.Slice(w, func(i, j int) bool { return w[i] > w[j] })
		sum := 0
		for i := n - k; i < n; i++ {
			sum += a[i]
		}
		j := 0
		for i, l := range w {
			if l == 1 {
				sum += a[n-k+i]
				continue
			}
			sum += a[j]
			j += l - 1
		}
		con.Println(sum)
	}
	return nil
}

package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var T int
	con.Scan(&T)
	for testcase := 0; testcase < T; testcase++ {
		var n, k int
		con.Scan(&n, &k)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			con.Scan(&a[i])
		}
		sort.Slice(a, func(i, j int) bool { return a[i] > a[j] })
		w := make([]int, k)
		for i := 0; i < k; i++ {
			con.Scan(&w[i])
		}
		sort.Ints(w)
		sum := 0
		for i := 0; i < k; i++ {
			sum += a[i]
		}
		base := 0
		lev := 1
		for base < k {
			pos := 0
			for base+pos < k && w[base+pos] == lev {
				sum += a[pos]
				pos++
			}
			a = a[k-base:]
			base += pos
			lev++
		}
		con.Println(sum)
	}
	return nil
}

package main

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

func ri() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

var sc = bufio.NewScanner(os.Stdin)

var t int
func main() {
  sc.Split(bufio.ScanWords)
  Scan(&t)
  for tc := 0; tc < t; tc++ {
    n, k := ri(), ri()
    as := make([]int, n)
    fs := make([]int, k)
    for i := range as {
        as[i] = ri()
    }
    for i := range fs {
        w := ri()
        fs[i] = w-1
    }

    sort.Ints(as)
    sort.Ints(fs)

    var ans int64 = 0
    for i := n-1; n-k-1 < i; i-- {
      ans += int64(as[i])
    }

    j := 0
    for i := k-1; 0 <= i; i-- {
      if fs[i] != 0 {
        ans += int64(as[j])
        j += fs[i]
      } else {
        ans += int64(as[n-i-1])
      }
    }

    Println(ans)
  }
}

package main

import (
  . "fmt"
  "sort"
)

var t int
func main() {
  Scan(&t)
  for tc := 0; tc < t; tc++ {
  	var n, k int
  	Scan(&n, &k)
    as := make([]int, n)
    fs := make([]int, k)
    for i := range as {
        Scan(&as[i])
    }
    for i := range fs {
        var w int
        Scan(&w)
        fs[i] = w-1
    }
    sort.Ints(as)
    sort.Ints(fs)

    ans := 0
    for i := n-1; n-k-1 < i; i-- {
      ans += as[i]
    }

    j := 0
    for i := k-1; 0 <= i; i-- {
      if fs[i] != 0 {
	      ans += as[j]
    	  j += fs[i]
      } else {
        ans += as[n-i-1]
      }
    }

    Println(ans)
  }
}

package main

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

func main() {
	var nTest, n, k int
	var a, w [100000]int

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

	fmt.Fscan(in, &nTest)
	for t := 0; t < nTest; t++ {
		fmt.Fscan(in, &n, &k)

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

		for i := 0; i < k; i++ {
			fmt.Fscan(in, &w[i])
		}

		sort.Slice(a[:], func(i, j int) bool {
			return a[i] > a[j]
		})

		res := 0
		tail := n - 1
		for i := 0; i < k; i++ {
			res += a[i]
			if tail > i {
				res += a[tail]
			} else {
				res += a[k-1-i]
			}

			tail -= w[k-1-i] - 1
		}
		fmt.Fprintln(out, res)
	}

	out.Flush()
}

package main

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

func main() {
	var nTest, n, k int
	var a, w [100000]int64

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

	fmt.Fscan(in, &nTest)
	for t := 0; t < nTest; t++ {
		fmt.Fscan(in, &n, &k)

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

		for i := 0; i < k; i++ {
			fmt.Fscan(in, &w[i])
		}

		sort.Slice(a[:n], func(i, j int) bool {
			return a[i] > a[j]
		})

		sort.Slice(w[:k], func(i, j int) bool {
			return w[i] < w[j]
		})

		res := int64(0)
		tail := int64(n - 1)
		for i := 0; i < k; i++ {
			res += a[i]
			if tail > int64(i) {
				res += a[tail]
			} else {
				res += a[k-1-i]
			}

			tail -= w[k-1-i] - 1
		}
		fmt.Fprintln(out, res)
	}

	out.Flush()
}

package main

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

func main() {
	var nTest, n, k int
	var a, w [100000]int64

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

	fmt.Fscan(in, &nTest)
	for t := 0; t < nTest; t++ {
		fmt.Fscan(in, &n, &k)

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

		for i := 0; i < k; i++ {
			fmt.Fscan(in, &w[i])
		}

		sort.Slice(a[:], func(i, j int) bool {
			return a[i] > a[j]
		})

		res := int64(0)
		tail := int64(n - 1)
		for i := 0; i < k; i++ {
			res += a[i]
			if tail > int64(i) {
				res += a[tail]
			} else {
				res += a[k-1-i]
			}

			tail -= w[k-1-i] - 1
		}
		fmt.Fprintln(out, res)
	}

	out.Flush()
}

package main

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

func main() {
	var nTest, n, k int
	var a, w [100000]int64

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

	fmt.Fscan(in, &nTest)
	for t := 0; t < nTest; t++ {
		fmt.Fscan(in, &n, &k)

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

		for i := 0; i < k; i++ {
			fmt.Fscan(in, &w[i])
		}

		sort.Slice(a[:n], func(i, j int) bool {
			return a[i] > a[j]
		})

		res := int64(0)
		tail := int64(n - 1)
		for i := 0; i < k; i++ {
			res += a[i]
			if tail > int64(i) {
				res += a[tail]
			} else {
				res += a[k-1-i]
			}

			tail -= w[k-1-i] - 1
		}
		fmt.Fprintln(out, res)
	}

	out.Flush()
}


You are given an array $$$a_1, a_2, \dots , a_n$$$ consisting of integers from $$$0$$$ to $$$9$$$. A subarray $$$a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$$$ is good if the sum of elements of this subarray is equal to the length of this subarray ($$$\sum\limits_{i=l}^{r} a_i = r - l + 1$$$).For example, if $$$a = [1, 2, 0]$$$, then there are $$$3$$$ good subarrays: $$$a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0]$$$ and $$$a_{1 \dots 3} = [1, 2, 0]$$$.Calculate the number of good subarrays of the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains a string consisting of $$$n$$$ decimal digits, where the $$$i$$$-th digit is equal to the value of $$$a_i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the number of good subarrays of the array $$$a$$$.

NoteThe first test case is considered in the statement.In the second test case, there are $$$6$$$ good subarrays: $$$a_{1 \dots 1}$$$, $$$a_{2 \dots 2}$$$, $$$a_{1 \dots 2}$$$, $$$a_{4 \dots 4}$$$, $$$a_{5 \dots 5}$$$ and $$$a_{4 \dots 5}$$$. In the third test case there is only one good subarray: $$$a_{2 \dots 6}$$$.

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

var err error

func next() (n string) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return ""
		}
	}
}

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextDouble() (n float64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func Fill(a []int, v int) {
	for i := range a {
		a[i] = v
	}
}

func FillB(a []bool, v bool) {
	for i := range a {
		a[i] = v
	}
}

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
}

const (
	oo  = 100000000
	mod = 1
)

func mult(a, b int64) int64 {
	return (a * b) % mod
}
func add(a, b int64) int64 {
	return (a + b) % mod
}
func sub(a, b int64) int64 {
	return (a - b + mod) % mod
}

var (
	base, a, b map[string]string
	dp         []map[string]int
	pat        string
)

func dfs(i int, x string) int {
	{
		a, test := dp[i][x]
		if test {
			return a
		}
	}
	res := i
	if base[x] != "" {
		for _, c := range []byte(base[x]) {
			if res < len(pat) && pat[res] == c {
				res++
			}
		}
	} else {
		res = dfs(dfs(i, a[x]), b[x])
	}
	dp[i][x] = res
	return res
}

func solve() {
	n := nextInt()
	arr := make([]int, n)
	{
		strin := []byte(next())
		for i := range arr {
			arr[i] = int(strin[i] - '0')
		}
	}
	tot := make([]int, 20*n)
	curr := 10 * n
	var ans int64
	for i := 0; i < n; i++ {
		tot[curr]++
		curr++
		curr -= arr[i]
		ans += int64(tot[curr])
	}
	printf("%d\n", ans)
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	if false {
		file1, err := os.Open("input.txt")
		if err != nil {
			log.Fatal(err)
		}
		file2, err := os.Create("output.txt")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file1, 8192)
		out = bufio.NewWriterSize(file2, 8192)
	}
	defer out.Flush()

	// start := time.Now()

	for t := nextInt(); t > 0; t-- {
		solve()
	}

	// printf("%v\n", time.Now().Sub(start))
}

package main

import "fmt"

func main() {
	var t int
	var n int64
	var s string
	var M map[int64]int64

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

	for t > 0 {
		t--
		fmt.Scanf("%d\n", &n)
		fmt.Scanf("%v\n", &s)

		M = make(map[int64]int64)

		var ans int64 = 0
		var sum int64 = 0

		for i := int64(1); i <= n; i++ {
			x := int64(s[i-1] - '0')

			M[sum-i]++
			sum += x
			ans += M[sum-i-1]
		}

		fmt.Printf("%d\n", ans)
	}
}

package main

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

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}
func scan(a ...interface{}) (n int, err error) {
	return fmt.Fscan(in, a...)
}

var err error

func next() (n string) {
	for {
		_, err = scan(&n)
		L("next err: ", err)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return ""
		}
	}
}

func nextInt() (n int) {
	for {
		_, err = scan(&n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scan(&n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextDouble() (n float64) {
	for {
		_, err = scan(&n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

var (
	out      *bufio.Writer
	in       *bufio.Reader
	printLog bool
)

func init() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	in = bufio.NewReaderSize(os.Stdin, 8192)

}
func L(a ...interface{}) {
	if printLog {
		log.Println(a)
	}
}

// 1. 转化，每个位权重是1，所以先把每个位-1，去除区间长度这个维度的影响
// 2. 从第一位开始累加前缀和
// 3. 逐个去掉开头元素，例如去掉第一个、第二个，对于的要把前缀和减去（可以不直接减，用一个数记住总共减了多少）
// 3. 对于第i个元素x，看已i+1为开头的数组中，前缀和为-x的个数（因为已经转化，每个数-1，所以这里直接找-x，与区间长度无关）
func main() {
	printLog = false
	defer out.Flush()
	t := nextInt()
	L("t: ", t)
	for ; t > 0; t-- {
		n := nextInt()
		_ = n
		s := next()
		arr := make([]int64, len(s))
		for i, c := range s {
			arr[i] = int64(c) - '0' - 1
		}
		L("arr: ", arr)
		// 11010211
		mp := make(map[int64]int64)
		var prefixSum int64 = 0
		for _, i := range arr {
			prefixSum += i
			L("preifx: ", prefixSum)
			mp[prefixSum]++
		}
		L("mp", mp)
		var sub int64 = 0
		var ans int64 = 0
		for _, i := range arr {
			// if cur == 0, ++
			if i-sub == 0 {
				ans++
			}
			// remove i
			mp[i-sub]--
			// sub i
			sub -= i
			L("i", i)
			L("0-sub", 0-sub)
			val, ok := mp[0-sub]
			if ok {
				ans += val
			}
		}
		fmt.Println(ans)
	}

}

package main

import (
	"fmt"
)

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

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

type Pair struct {
	first, second int
}

type byFirst []Pair

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

func (s byFirst) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s byFirst) Less(i, j int) bool {
	return s[i].first < s[j].first
}

type bySecond []Pair

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

func (s bySecond) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s bySecond) Less(i, j int) bool {
	return s[i].second < s[j].second
}

func main() {
	var t int
	fmt.Scan(&t)
	for t > 0 {
		var n int
		fmt.Scan(&n)
		var s string
		fmt.Scan(&s)

		sum := make([]int, n+1)
		for i := 1; i <= n; i++ {
			sum[i] = sum[i-1] + int(s[i-1]-'0')
		}

		var answer int64

		m := make(map[int]int)
		m[0] = 1
		for i := 1; i <= n; i++ {
			answer += int64(m[sum[i]-i])
			m[sum[i]-i]++
		}

		fmt.Println(answer)

		t--
	}
}

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	bf := make([]byte, 1024*1024)
	sc.Buffer(bf, 10*1024*1024)
	sc.Split(bufio.ScanWords)

	sc.Scan()
	t, _  := strconv.Atoi(sc.Text())

	for ; t > 0; t-- {
		sc.Scan(); sc.Scan();

		s := sc.Text()
		var n int64 = int64(len(s))
		a := make([]int64, n+1)
		a[0] = 0

		var i int64

		for i = 0; i < n; i++ {
			a[i+1] = a[i] + int64(s[i] - '0' )
		}

		for i = 0 ; i < n+1; i++ {
			a[i] -= i
		}

		m := make(map[int64]int64)

		for i := range a {
			m[a[i]]++
		}

		// fmt.Println(m)

		var sm int64 = 0

		for _, v := range  m {
			sm += (v*v - v)/2
		}

		fmt.Println(sm)
	}
}

package main

import "fmt"

func main() {
	var t int
	var n int
	var s string
	var M map[int]int

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

	for t > 0 {
		t--
		fmt.Scanf("%d\n", &n)
		fmt.Scanf("%v\n", &s)

		M = make(map[int]int)

		ans := 0
		sum := 0
		for i := 1; i <= n; i++ {
			x := int(s[i-1] - '0')

			M[sum-i]++
			sum += x
			ans += M[sum-i-1]
		}

		fmt.Printf("%d\n", ans)
	}
}

package main

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

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}
func scan(a ...interface{}) (n int, err error) {
	return fmt.Fscan(in, a...)
}

var err error

func next() (n string) {
	for {
		_, err = scan(&n)
		L("next err: ", err)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return ""
		}
	}
}

func nextInt() (n int) {
	for {
		_, err = scan(&n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scan(&n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextDouble() (n float64) {
	for {
		_, err = scan(&n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

var (
	out      *bufio.Writer
	in       *bufio.Reader
	printLog bool
)

func init() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	in = bufio.NewReaderSize(os.Stdin, 8192)

}
func L(a ...interface{}) {
	if printLog {
		log.Println(a)
	}
}

// 1. 转化，每个位权重是1，所以先把每个位-1，去除区间长度这个维度的影响
// 2. 从第一位开始累加前缀和
// 3. 逐个去掉开头元素，例如去掉第一个、第二个，对于的要把前缀和减去（可以不直接减，用一个数记住总共减了多少）
// 3. 对于第i个元素x，看已i+1为开头的数组中，前缀和为-x的个数（因为已经转化，每个数-1，所以这里直接找-x，与区间长度无关）
func main() {
	printLog = false
	defer out.Flush()
	t := nextInt()
	L("t: ", t)
	for ; t > 0; t-- {
		n := nextInt()
		_ = n
		s := next()
		arr := make([]int, len(s))
		for i, c := range s {
			arr[i] = int(c) - '0' - 1
		}
		L("arr: ", arr)
		// 11010211
		mp := make(map[int]int)
		prefixSum := 0
		for _, i := range arr {
			prefixSum += i
			L("preifx: ", prefixSum)
			mp[prefixSum]++
		}
		L("mp", mp)
		sub := 0
		ans := 0
		for _, i := range arr {
			// if cur == 0, ++
			if i-sub == 0 {
				ans++
			}
			// remove i
			mp[i-sub]--
			// sub i
			sub -= i
			L("i", i)
			L("0-sub", 0-sub)
			val, ok := mp[0-sub]
			if ok {
				ans += val
			}
		}
		fmt.Println(ans)
	}

}

package main

import (
	"fmt"
)

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

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

type Pair struct {
	first, second int
}

type byFirst []Pair

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

func (s byFirst) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s byFirst) Less(i, j int) bool {
	return s[i].first < s[j].first
}

type bySecond []Pair

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

func (s bySecond) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s bySecond) Less(i, j int) bool {
	return s[i].second < s[j].second
}

func main() {
	var t int
	fmt.Scan(&t)
	for t > 0 {
		var n int
		fmt.Scan(&n)
		var s string
		fmt.Scan(&s)

		sum := make([]int, n+1)
		for i := 1; i <= n; i++ {
			sum[i] = sum[i-1] + int(s[i-1]-'0')
		}

		answer := 0

		m := make(map[int]int)
		m[0] = 1
		for i := 1; i <= n; i++ {
			answer += m[sum[i]-i]
			m[sum[i]-i]++
		}

		fmt.Println(answer)

		t--
	}
}

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	bf := make([]byte, 1024*1024)
	sc.Buffer(bf, 10*1024*1024)
	sc.Split(bufio.ScanWords)

	sc.Scan()
	t, _  := strconv.Atoi(sc.Text())

	for ; t > 0; t-- {
		sc.Scan(); sc.Scan();

		s := sc.Text()
		n := len(s)
		a := make([]int, n+1)
		a[0] = 0

		for i := 0; i < n; i++ {
			a[i+1] = a[i] + int(s[i] - '0' )
		}

		for i := 0 ; i < n+1; i++ {
			a[i] -= (i)
		}

		m := make(map[int]int)

		for i := range a {
			m[a[i]]++
		}

		sm := 0

		for _, v := range  m {
			sm += (v*v - v)/2
		}

		fmt.Println(sm)
	}
}


Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:  there wouldn't be a pair of any side-adjacent cards with zeroes in a row;  there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.

The first line contains two integers: n (1 ≤ n ≤ 106) — the number of cards containing number 0; m (1 ≤ m ≤ 106) — the number of cards containing number 1.

In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.

package main

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

func main(){
	var n, m int64
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	n, _ = strconv.ParseInt(r.Text(), 0, 64)
	r.Scan()
	m, _ = strconv.ParseInt(r.Text(), 0, 64)
	count := 0
	sum := n + m
	if m > 2*(sum+1)/3 || m < sum/2 {
		w.WriteString("-1")
		w.Flush()
	} else {
		for i:=0; int64(i)<sum; i++ {
			if count == 2 || n > m {
				w.WriteString("0")
				count = 0
				n -= 1
			} else if count == 0 || count == 1 {
				w.WriteString("1")
				count += 1
				m -= 1
			}
		}
	}
	w.Flush()
	w.WriteString("\n")
	w.Flush()
}

package main

import (
	"fmt"
	"bufio"
	"os"
	"strconv"
	// "time"
	// "bytes"
)

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

//Wrong
func main() {
	// defer func(start time.Time) {
	// 	fmt.Println(time.Since(start))
	// }(time.Now())

	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n, m := nextInt(), nextInt()
	// var buf = bytes.Buffer

	if n>m+1 || n*2+2<m {
		print("-1\n")
		return
	}

	if n>m {
		print("0")
		n--
	}

	for n>0 && m>0 {
		if m > n+1 {
			print("11")
			m -= 2
		} else{
			print("1")
			m--
		}

		print("0")
		n--
		// fmt.Println(n, m)
	}

	if m==2 {
		print("11")
	} else if m==1 {
		print("1")
	}
	print("\n")
}

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

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

package main

import (
	"fmt"
	"bufio"
	"os"
	"strconv"
	// "time"
	// "bytes"
)

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

//Wrong
func main() {
	// defer func(start time.Time) {
	// 	fmt.Println(time.Since(start))
	// }(time.Now())

	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n, m := nextInt(), nextInt()
	// var buf = bytes.Buffer
	str := make([]uint8, 0, m+n)

	if n>m+1 || n*2+2<m {
		print("-1\n")
		return
	}

	if n>m {
		// print("0")
		str = append(str, '0')
		n--
	}

	for n>0 && m>0 {
		if m > n+1 {
			// print("11")
			str = append(str, "11"...)
			m -= 2
		} else{
			// print("1")
			str = append(str, '1')
			m--
		}

		str = append(str, '0')
		// print("0")
		n--
		// fmt.Println(n, m)
	}

	if m==2 {
		// print("11")
		str = append(str, "11"...)
	} else if m==1 {
		// print("1")
		str = append(str, '1')
	}
	// print("\n")
	println(string(str))
}

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

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

package main

import (
	"fmt"
	"strings"
)

func main() {

	var n,m  int;

	fmt.Scan(&n);
	fmt.Scan(&m);
	if (m < n - 1 || m > 2 * (n + 1)){
		fmt.Print(-1)
	}else{
		if (m == n){
			s := strings.Repeat("01", m)
			fmt.Printf(s)
		}else{
		    if (m == n - 1){
		        fmt.Print(strings.Repeat("01" , m), 0)
		    }else{
    			max := m - n
    			t := m - 2*n
    			if (t < 0){
    			     t = 0
    			}
    			max -= t
    			s1 := strings.Repeat("110", max)
    			s2 := ""
    			if (n - max > 0){
    			    s2 = strings.Repeat("10", n - max)
    			}
    			s3 := strings.Repeat("1", t)
    			fmt.Print(s1, s2, s3)
		    }

		}
	}
}

// ther are multiple solutions,
// codeforces accepts only the lexicografically biggest...
// ('0'<'1'), no there were other problems

package main

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

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

func main() {
	var (
		i, nz, no, no2, bal, jobb, tmp int32
		out                            *bufio.Writer
	)

	out = bufio.NewWriter(os.Stdout)

	fmt.Scan(&nz)
	fmt.Scan(&no)
	if no < (nz-1) || no > 2*(nz+1) {
		fmt.Fprintln(out, "-1")
	} else {
		//		println("no,nz=", no, nz)
		no -= (nz - 1)
		tmp = min(no, 1)
		bal, no = tmp, no-tmp
		tmp = min(no, 1)
		jobb, no = tmp, no-tmp

		tmp = min(no, 1)
		bal, no = bal+tmp, no-tmp

		tmp = min(no, nz-1)
		no2, no = tmp, no-tmp

		jobb += no

		//		println("no2,bal,jobb=", no2, bal, jobb)

		switch bal {
		case 1:
			fmt.Fprint(out, "1")
		case 2:
			fmt.Fprint(out, "11")
		}

		for i = 0; i < no2; i++ {
			fmt.Fprint(out, "011")
		}
		for ; i < nz-1; i++ {
			fmt.Fprint(out, "01")
		}
		fmt.Fprint(out, "0")

		switch jobb {
		case 1:
			fmt.Fprint(out, "1")
		case 2:
			fmt.Fprint(out, "11")
		}
		fmt.Fprintln(out)
	}
	out.Flush()
}

// ther are multiple solutions,
// codeforces accepts only the lexicografically biggest...
// ('0'<'1')

package main

import (
	"fmt"
)

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

func main() {
	var (
		i, nz, no, no2, bal, jobb, tmp int32
		ans                            []byte
	)

	fmt.Scan(&nz)
	fmt.Scan(&no)
	if no < (nz-1) || no > 2*(nz+1) {
		fmt.Println("-1")
	} else {
		ans = make([]byte, 0, no+nz)
		//		println("no,nz=", no, nz)
		no -= (nz - 1)
		tmp = min(no, 1)
		bal, no = tmp, no-tmp
		tmp = min(no, 1)
		jobb, no = tmp, no-tmp

		tmp = min(no, 1)
		bal, no = bal+tmp, no-tmp

		tmp = min(no, nz-1)
		no2, no = tmp, no-tmp

		jobb += no

		//		println("no2,bal,jobb=", no2, bal, jobb)

		switch bal {
		case 1:
			ans = append(ans, "1"...)
		case 2:
			ans = append(ans, "11"...)
		}

		for i = 0; i < no2; i++ {
			ans = append(ans, "011"...)
		}
		for ; i < nz-1; i++ {
			ans = append(ans, "01"...)
		}
		ans = append(ans, "0"...)

		switch jobb {
		case 1:
			ans = append(ans, "1"...)
		case 2:
			ans = append(ans, "11"...)
		}

		fmt.Println(string(ans))
	}
}

package main

import (
	"fmt"
)

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

func main() {
	var (
		i, nz, no, no2, bal, jobb, tmp int32
		ans                            []byte
	)

	fmt.Scan(&nz)
	fmt.Scan(&no)
	if no < (nz-1) || no > 2*(nz+1) {
		fmt.Println("-1")
	} else {
		ans = make([]byte, 0, no+nz)
		//		println("no,nz=", no, nz)
		no -= (nz - 1)
		tmp = min(no, nz-1)
		no2, no = tmp, no-tmp

		tmp = min(no, 2)
		bal, no = tmp, no-tmp
		jobb = no

		//		println("no2,bal,jobb=", no2, bal, jobb)

		switch bal {
		case 1:
			ans = append(ans, "1"...)
		case 2:
			ans = append(ans, "11"...)
		}

		for i = 0; i < no2; i++ {
			ans = append(ans, "011"...)
		}
		for ; i < nz-1; i++ {
			ans = append(ans, "01"...)
		}
		ans = append(ans, "0"...)

		switch jobb {
		case 1:
			ans = append(ans, "1"...)
		case 2:
			ans = append(ans, "11"...)
		}

		fmt.Println(string(ans))
	}
}

package main

import (
	"fmt"
	"strings"
)

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

	if n-m > 1 || m > (n+1)*2 {
		fmt.Println(-1)
	} else {
		buffer := make([]string, n+m)
		p := 0
		exm := m - n

		if exm > 0 {
			if m == (n+1)*2 {
				buffer[p] = "1"
				buffer[p+1] = "1"
				p += 2
				exm -= 2
			} else {
				buffer[p] = "1"
				p += 1
				exm -= 1
			}

			for i := 0; i < exm; i++ {
				buffer[p] = "0"
				buffer[p+1] = "1"
				buffer[p+2] = "1"
				p += 3
			}
			for i := 0; i < n-exm; i++ {
				buffer[p] = "0"
				buffer[p+1] = "1"
				p += 2
			}
		} else { // exm is 0 or -1
			for i := 0; i < n-1; i++ {
				buffer[p] = "0"
				buffer[p+1] = "1"
				p += 2
			}
			if exm == 0 {
				buffer[p] = "0"
				buffer[p+1] = "1"
				p += 2
			} else {
				buffer[p] = "0"
				p += 1
			}
		}

		fmt.Println(strings.Join(buffer, ""))
	}
}

package main

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

func main() {
    writer := bufio.NewWriter(os.Stdout)
    var n,m int
    fmt.Scan(&n,&m)
    ans, s := true, make([]string,0,n+m)
    for (n > 0) && (m > 1) && (m > n) {
        s = append(s,"110")
        n -= 1
        m -= 2
    }
    for (n > 0) && (m > 0) {
        s = append(s,"10")
        n -= 1
        m -= 1
    }
    if (m <= 2) && (n <= 1) {
        for i := 0; i < m; i++ { s = append(s,"1") }
        for i := 0; i < n; i++ { writer.WriteRune('0') }
        n--
    } else {
        ans = false
    }
    if ans {
        for i := 0; i < len(s); i++ {
            writer.WriteString(s[i])
        }
        writer.WriteRune('\n')
    } else {
        writer.WriteString("-1\n")
    }
    writer.Flush()
}

/*********************************************************************************
*     File Name           :     C.go
*     Created By          :     YIMMON, yimmon.zhuang@gmail.com
*     Creation Date       :     [2014-03-10 23:59]
*     Last Modified       :     [2014-03-11 00:16]
*     Description         :
**********************************************************************************/

package main

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

func main() {
    scanner.Split(bufio.ScanWords)

    var n, m = scanner.NextInt(), scanner.NextInt()
    if m < n-1 || m > (n-1)*2+4 {
        fmt.Println(-1)
    } else {
        m -= n - 1
        res := make([]byte, 0)
        for i := 1; i < n; i++ {
            res = append(res, '0', '1')
            if m > 4 {
                res = append(res, '1')
                m--
            }
        }
        res = append(res, '0')
        if m > 0 {
            for i := Min(2, m); i > 0; i-- {
                fmt.Print(1)
                m--
            }
        }
        fmt.Print(string(res))
        for i := 0; i < m; i++ {
            fmt.Print(1)
        }
        fmt.Println()
    }
}

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

type Scanner struct {
    *bufio.Scanner
}

var scanner = Scanner{bufio.NewScanner(os.Stdin)}

func (self *Scanner) Next() string {
    if !self.Scan() {
        panic(self.Err())
    }
    return self.Text()
}

func (self *Scanner) NextInt() int {
    x, err := strconv.Atoi(self.Next())
    if err != nil {
        panic(err)
    }
    return x
}

package main

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

func main() {
	z := bufio.NewScanner(os.Stdin)
	z.Split(bufio.ScanWords)
	z.Scan()
	zeros, _ := strconv.Atoi(z.Text())
	z.Scan()
	ones, _ := strconv.Atoi(z.Text())

	if ones > 2 * zeros + 2  || zeros > 1+ones {
		fmt.Println(-1)
		return
	}

	var sb strings.Builder
	sb.Grow(zeros + ones)

	if zeros > ones {
		sb.WriteString("0")
		zeros--
	}

	for ;ones > zeros + 1; {
		sb.WriteString("11")
		ones-=2
		if zeros > 0 {
			sb.WriteString("0")
			zeros--
		}
	}

	endsWithOne := false
	if ones == zeros + 1 {
		endsWithOne = true
		ones--
	}

	for i := 0; i < ones; i++ {
		sb.WriteString("10")
	}

	if endsWithOne {
		sb.WriteString("1")
	}
	fmt.Println(sb.String())
}

package main

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

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

var n, m int

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	read(&n, &m)

	if n > m+1 || (n+1)*2 < m {
		write(-1)
		writer.Flush()
		os.Exit(0)
	}

	if n == m+1 {
		write(0)
		n--
	} else if (n+1)*2 == m {
		defer write2(1)
		m -= 2
	} else if m%2 == 1 && n != m {
		defer write(1)
		m -= 1
	}

	for n < m && n > 0 {
		write2(1)
		write(0)
		m -= 2
		n -= 1
	}

	for i := n; i > 0; i-- {
		write(1)
		write(0)
	}
}

func write2(a int) {
	write(a)
	write(a)
}

func write(a int) {
	writer.WriteString(strconv.Itoa(a))
}

func readInt(n *int) {
	scanner.Scan()
	*n, _ = strconv.Atoi(scanner.Text())
}

func read(n *int, m *int) {
	readInt(n)
	readInt(m)
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var m, n int
	fmt.Scan(&m, &n) // m - 0, n - 1

	if m > n + 1 || n > m * 2 + 2 {
		fmt.Println("-1")
		return
	}
	out := ""
	k := 0
	if m > n {
		out += "0"
		m--
	}
	for n > m && n > 0 && m > 0 {
		m--
		n-=2
		k++
	}
	out += strings.Repeat("110", k)
	if m > 0 {
		out += strings.Repeat("10", m)
	}
	if n - m > 0 {
		out += strings.Repeat("1", n - m)
	}
	fmt.Println(out)
}

//	m = 5  n = 4
//	010101010
//

// /problemset/problem/401/C

package main

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

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

	if n > m+1 || m > 2*(n+1) {
		fmt.Println(-1)
		return
	}
	str := make([]int, n)
	count := n
	if n == m+1 {
		str[0] = 0
		for i := 0; i < m; i++ {
			str[i+1] = 10
		}
	} else if m <= 2 * n {
		for i := 0; i < n; i++ {
			str[i] = 10
		}
		for i := 0; i < m-n; i++ {
			str[i] = 110
		}
	} else {
		for i := 0; i <n; i++ {
			str[i] = 110
		}
		if m == 2 *n +1 {
			str = append(str, 1)
		} else {
			str = append(str, 11)
		}
		count ++
	}
	//fmt.Println("+++++")
	byteStr := make([]byte, 0)
	writer := bytes.NewBuffer(byteStr)
	for i := 0; i < count; i++ {
		writer.Write([]byte(fmt.Sprintf("%d", str[i])))
	}
	//fmt.Println("====")
	fmt.Println(string(writer.Bytes()))
}

// 401C
package main

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

func main() {
	var n, m int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)
	if n > m+1 || (n+1)*2 < m {
		fmt.Print(-1)
		return
	}
	m -= n - 1
	if m > 0 {
		fmt.Fprint(out, 1)
		m -= 1
	}
	for i := 0; i < n; i++ {
		if m != 0 {
			m -= 1
			fmt.Fprint(out, 1)
		}
		if i != n-1 {
			fmt.Fprint(out, "01")
		} else {
			fmt.Fprint(out, 0)
		}
	}
	for i := 0; i < m; i++ {
		fmt.Fprint(out, 1)
	}
	out.Flush()
}

// 401C-mic_rizal
package main

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

func main() {
    var n, k int
    o := bufio.NewWriter(os.Stdout)
    fmt.Scan(&n, &k)

    if k < n-1 || k > (n+1)*2 {
        o.WriteString("-1")
        //fmt.Print("-1")
    } else {
        in := n
        for i := 0; i < in; i++ {
            if k == n-1 {
                o.WriteString("0")
                //fmt.Print("0")
                n--
                continue
            }

            if k > n {
                o.WriteString("110")
                //fmt.Print("110")
                k -= 2
                n--
            } else {
                o.WriteString("10")
                //fmt.Print("10")
                k--
                n--
            }

            if n == 0 && k != 0 {
                for i := 0; i < k; i++ {
                    o.WriteString("1")
                    //fmt.Print("1")
                }
                break
            }
        }
    }
    o.Flush()
    fmt.Println()
}

package main

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

func main() {
    scanner.Split(bufio.ScanWords)
    n := scanner.NextInt()
    m := scanner.NextInt()
    var buffer bytes.Buffer
    if 2*n+2 < m || n > m+1 {
        fmt.Println("-1")
    } else {
        if m-n >= 2 {
            buffer.WriteString("11")
            m -= 2
        } else if m-n == 1 {
            buffer.WriteString("1")
            m -= 1
        }
        for i := 0; i < n; i++ {
            buffer.WriteString("0")
            if m > 0 {
                buffer.WriteString("1")
                m--
            }
            if m > n-i-1 {
                buffer.WriteString("1")
                m--
            }
        }
        fmt.Println(buffer.String())
    }
}

type Scanner struct {
    *bufio.Scanner
}

var scanner = Scanner{bufio.NewScanner(os.Stdin)}

func (self *Scanner) Next() string {
    if !self.Scan() {
        panic(self.Err())
    }
    return self.Text()
}

func (self *Scanner) NextInt() int {
    x, err := strconv.Atoi(self.Next())
    if err != nil {
        panic(err)
    }
    return x
}

func (self *Scanner) NextDouble() float64 {
    x, err := strconv.ParseFloat(self.Next(), 64)
    if err != nil {
        panic(err)
    }
    return x
}

package main

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

func main(){
	var n, m int64
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	n, _ = strconv.ParseInt(r.Text(), 0, 64)
	r.Scan()
	m, _ = strconv.ParseInt(r.Text(), 0, 64)
	card := make([]int, n+m)
	count1 := 0
	count := 0
	if m > (n+1)*2 || n > m+1 {
		w.WriteString("-1")
		w.Flush()
	} else {
		for i:=0; int64(i)<n+m; i++ {
			if (n + m)%3 == 0 {
				if int64(count) > n + m - 4 {
					card[i] = 1
					card[i+1] = 0
					card[i+2] = 1
					break
				} else {
					if count1 < 2 {
						card[i] = 1
						count1 += 1
						count += 1
					} else if count1 == 2 {
						card[i] = 0
						count1 = 0
						count += 1
					}
				}
			} else {
				if count1 < 2 {
					card[i] = 1
					count1 += 1
					count += 1
				} else if count1 == 2 {
					card[i] = 0
					count1 = 0
					count += 1
				}
			}
		}
		for j:=0; int64(j)<n+m; j++ {
			w.WriteString(strconv.Itoa(card[j]))
			w.Flush()
		}
	}
	w.WriteString("\n")
	w.Flush()
}

package main

import (
	"fmt"
	"bufio"
	"os"
	"strconv"
	// "time"
	// "bytes"
)

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

//Wrong
func main() {
	// defer func(start time.Time) {
	// 	fmt.Println(time.Since(start))
	// }(time.Now())

	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n, m := nextInt(), nextInt()
	// var buf = bytes.Buffer

	for n>0 && m>0 {
		if m > n+1 {
			print("11")
			m -= 2
		} else if m >= n {
			print("1")
			m--
		} else {
			break
		}
		print("0")
		n--
		// fmt.Println(n, m)
	}

	if n>0 || m>2 {
		writer.Reset(os.Stdout)
		print("-1")
	} else if m==2 {
		print("11")
	} else if m==1 {
		print("1")
	}
	print("\n")
}

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

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

package main

import (
	"fmt"
	"bufio"
	"os"
	"strconv"
	// "time"
	// "bytes"
)

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

//Wrong
func main() {
	// defer func(start time.Time) {
	// 	fmt.Println(time.Since(start))
	// }(time.Now())

	// defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n, m := nextInt(), nextInt()
	// var buf = bytes.Buffer

	for n>0 && m>0 {
		if m > n+1 {
			print("11")
			m -= 2
		} else if m >= n {
			print("1")
			m--
		} else {
			break
		}
		print("0")
		n--
		// fmt.Println(n, m)
	}

	if n>0 || m>2 {
		writer.Reset(os.Stdout)
		print("-1")
	} else if m==2 {
		print("11")
	} else if m==1 {
		print("1")
	}
	print("\n")
}

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

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

package main

import (
	"fmt"
	"strings"
)

func main() {

	var n,m  int;

	fmt.Scan(&n);
	fmt.Scan(&m);
	if (m < n - 1 || m > 2 * (n + 1)){
		fmt.Print(-1)
	}else{
		if (m == n){
			s := strings.Repeat("01", m)
			fmt.Printf(s)
		}else{
			max := m - n
			t := m - 2*n
			if (t < 0){
			     t = 0
			}
			s1 := strings.Repeat("110", max)
			s2 := ""
			if (n - max > 0){
			    s2 = strings.Repeat("10", n - max)
			}
			s3 := strings.Repeat("1", t)
			fmt.Print(s1, s2, s3)

		}
	}
}

// ther are multiple solutions,
// codeforces accepts only the lexicografically biggest...
// ('0'<'1')

package main

import (
	"fmt"
)

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

func main() {
	var (
		i, nz, no, no2, bal, jobb, tmp int32
		ans                            []byte
	)

	fmt.Scan(&nz)
	fmt.Scan(&no)
	if no < (nz-1) || no > 2*(nz+1) {
		fmt.Println("-1")
	} else {
		ans = make([]byte, no+nz, no+nz)
		//		println("no,nz=", no, nz)
		no -= (nz - 1)
		tmp = min(no, 1)
		bal, no = tmp, no-tmp
		tmp = min(no, 1)
		jobb, no = tmp, no-tmp

		tmp = min(no, 1)
		bal, no = bal+tmp, no-tmp

		tmp = min(no, nz-1)
		no2, no = tmp, no-tmp

		jobb += no

		//		println("no2,bal,jobb=", no2, bal, jobb)

		switch bal {
		case 1:
			ans = append(ans, "1"...)
		case 2:
			ans = append(ans, "11"...)
		}

		for i = 0; i < no2; i++ {
			ans = append(ans, "011"...)
		}
		for ; i < nz-1; i++ {
			ans = append(ans, "01"...)
		}
		ans = append(ans, "0"...)

		switch jobb {
		case 1:
			ans = append(ans, "1"...)
		case 2:
			ans = append(ans, "11"...)
		}

		fmt.Println(string(ans))
	}
}

package main

import (
	"fmt"
)

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

func main() {
	var (
		i, nz, no, no2, bal, jobb, tmp int32
		ans                            []byte
	)

	fmt.Scan(&nz)
	fmt.Scan(&no)
	if no < (nz-1) || no > 2*(nz+1) {
		fmt.Println("-1")
	} else {
		ans = make([]byte, no+nz, no+nz)
		//		println("no,nz=", no, nz)
		no -= (nz - 1)
		tmp = min(no, nz-1)
		no2, no = tmp, no-tmp

		tmp = min(no, 2)
		bal, no = tmp, no-tmp
		jobb = no

		//		println("no2,bal,jobb=", no2, bal, jobb)

		switch bal {
		case 1:
			ans = append(ans, "1"...)
		case 2:
			ans = append(ans, "11"...)
		}

		for i = 0; i < no2; i++ {
			ans = append(ans, "011"...)
		}
		for ; i < nz-1; i++ {
			ans = append(ans, "01"...)
		}
		ans = append(ans, "0"...)

		switch jobb {
		case 1:
			ans = append(ans, "1"...)
		case 2:
			ans = append(ans, "11"...)
		}

		fmt.Println(string(ans))
	}
}

package main

import (
	"fmt"
	"strings"
)

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

	if n-m > 1 || m > (n+1)*2 {
		fmt.Println(-1)
	} else {
		buffer := make([]string, n+m)
		p := 0
		exm := m - n

		if exm > 0 {
			if m == (n+1)*2 {
				buffer[p] = "1"
				buffer[p+1] = "1"
				p += 2
				exm -= 2
			} else {
				buffer[p] = "1"
				p += 1
				exm -= 1
			}

			for i := 0; i < exm; i++ {
				buffer[p] = "0"
				buffer[p+1] = "1"
				buffer[p+2] = "1"
				p += 3
			}
			for i := 0; i < n-exm; i++ {
				buffer[p] = "0"
				buffer[p+1] = "1"
				p += 2
			}
		} else { // exm is 0 or -1
			for i := 0; i < n-1; i++ {
				buffer[p] = "0"
				buffer[p+1] = "1"
				p += 2
			}
			if exm > 0 {
				buffer[p] = "0"
				buffer[p+1] = "1"
				p += 2
			} else {
				buffer[p] = "0"
				p += 1
			}
		}

		fmt.Println(strings.Join(buffer, ""))
	}
}

package main

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

func main() {
	z := bufio.NewScanner(os.Stdin)
	z.Split(bufio.ScanWords)
	z.Scan()
	zeros, _ := strconv.Atoi(z.Text())
	z.Scan()
	ones, _ := strconv.Atoi(z.Text())

	if ones > 2 * zeros + 2 {
		fmt.Println(-1)
		return
	}

	var sb strings.Builder
	sb.Grow(zeros + ones)
	n := ones / 2

	for i := 0 ; i < n ; i++ {
		sb.WriteString("11")
		if zeros > 0 {
			sb.WriteString("0")
			zeros--
		}
	}
	if ones % 2 == 1 {
		sb.WriteString("1")
	}
	for i:= 0; i < zeros; i++ {
		sb.WriteString("0")
	}
	fmt.Println(sb.String())
}

package main

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

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

var n, m int

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	read(&n, &m)

	if n > m+1 || (n+1)*2 < m {
		write(-1)
		writer.Flush()
		os.Exit(0)
	}

	if n == m+1 {
		write(0)
		n--
	} else if (n+1)*2 == m {
		defer write2(1)
		m -= 2
	}

	for n < m {
		write2(1)
		write(0)
		m -= 2
		n -= 1
	}
	for i := n; i > 0; i-- {
		write(1)
		write(0)
	}
}

func write2(a int) {
	write(a)
	write(a)
}

func write(a int) {
	writer.WriteString(strconv.Itoa(a))
}

func readInt(n *int) {
	scanner.Scan()
	*n, _ = strconv.Atoi(scanner.Text())
}

func read(n *int, m *int) {
	readInt(n)
	readInt(m)
}

package main

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

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

var n, m int

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	read(&n, &m)

	if n > m+1 || (n+1)*2 < m {
		write(-1)
		writer.Flush()
		os.Exit(0)
	}

	if n == m+1 {
		write(0)
		n--
	} else if (n+1)*2 == m {
		defer write2(1)
		m -= 2
	} else if m%2 == 1 {
		defer write(1)
		m -= 1
	}

	for n < m && n > 0 {
		write2(1)
		write(0)
		m -= 2
		n -= 1
	}

	for i := n; i > 0; i-- {
		write(1)
		write(0)
	}
}

func write2(a int) {
	write(a)
	write(a)
}

func write(a int) {
	writer.WriteString(strconv.Itoa(a))
}

func readInt(n *int) {
	scanner.Scan()
	*n, _ = strconv.Atoi(scanner.Text())
}

func read(n *int, m *int) {
	readInt(n)
	readInt(m)
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var m, n int
	fmt.Scan(&m, &n) // m - 0, n - 1

	if m > n + 1 || n > m * 2 + 2 {
		fmt.Println("-1")
		return
	}
	out := ""
	k := 0
	if m > n {
		out += "0"
	}
	for n > m && n > 0 && m > 0 {
		m--
		n-=2
		k++
	}
	out += strings.Repeat("110", k)
	if m > 0 {
		out += strings.Repeat("10", m)
	}
	if n - m > 0 {
		out += strings.Repeat("1", n - m)
	}
	fmt.Println(out)
}

//	m = 5  n = 4
//	010101010
//

// /problemset/problem/401/C

package main

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

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

	if n > m+1 || m > 2*(n+1) {
		fmt.Println(-1)
		return
	}
	str := make([]int, n)
	count := n
	if n == m+1 {
		str[0] = 0
		for i := 0; i < m; i++ {
			str[i+1] = 10
		}
	} else if m < 2 * n {
		for i := 0; i < n; i++ {
			str[i] = 10
		}
		for i := 0; i < m-n; i++ {
			str[i] = 110
		}
	} else {
		for i := 0; i < n; i++ {
			str[i] = 110
		}
		if m == 2 *n +1 {
			str = append(str, 1)
		} else {
			str = append(str, 11)
		}
		count ++
	}

	for i := 0; i < count; i++ {
		fmt.Print(str[i])
	}
	fmt.Println()
}

package main

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

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

	if n > m+1 || m > 2*(n+1) {
		fmt.Println(-1)
		return
	}
	str := make([]int, n)
	count := n
	if n == m+1 {
		str[0] = 0
		for i := 0; i < m; i++ {
			str[i+1] = 10
		}
	} else if m <= 2 * n {
		for i := 0; i < n; i++ {
			str[i] = 10
		}
		for i := 0; i < m-n; i++ {
			str[i] = 110
		}
	} else {
		for i := 0; i <n; i++ {
			str[i] = 110
		}
		if m == 2 *n +1 {
			str = append(str, 1)
		} else {
			str = append(str, 11)
		}
		count ++
	}
	//fmt.Println("+++++")
	byteStr := make([]byte, n+m)
	writer := bytes.NewBuffer(byteStr)
	for i := 0; i < count; i++ {
		writer.Write([]byte(fmt.Sprintf("%d", str[i])))
	}
	//fmt.Println("====")
	fmt.Println(string(writer.Bytes()))
}

// 401C
package main

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

func main() {
	var n, m int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)
	if n > m+1 || (n+1)*2 < m {
		fmt.Fprint(out, -1)
		return
	}
	m -= n - 1
	if m > 0 {
		fmt.Fprint(out, 1)
		m -= 1
	}
	for i := 0; i < n; i++ {
		if m != 0 {
			m -= 1
			fmt.Fprint(out, 1)
		}
		if i != n-1 {
			fmt.Fprint(out, "01")
		} else {
			fmt.Fprint(out, 0)
		}
	}
	for i := 0; i < m; i++ {
		fmt.Fprint(out, 1)
	}
	out.Flush()
}

// 401C
package main

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

func main() {
	var n, m int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)
	if n > m+1 || (n+1)*2 < m {
		fmt.Fprint(out, "-1")
		return
	}
	m -= n - 1
	if m > 0 {
		fmt.Fprint(out, 1)
		m -= 1
	}
	for i := 0; i < n; i++ {
		if m != 0 {
			m -= 1
			fmt.Fprint(out, 1)
		}
		if i != n-1 {
			fmt.Fprint(out, "01")
		} else {
			fmt.Fprint(out, 0)
		}
	}
	for i := 0; i < m; i++ {
		fmt.Fprint(out, 1)
	}
	out.Flush()
}

// 401C
package main

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

func main() {
	var n, m int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)
	if n > m+1 || (n+1)*2 < m {
		fmt.Fprint(out, "-1")
	}
	m -= n - 1
	if m > 0 {
		fmt.Fprint(out, 1)
		m -= 1
	}
	for i := 0; i < n; i++ {
		if m != 0 {
			m -= 1
			fmt.Fprint(out, 1)
		}
		if i != n-1 {
			fmt.Fprint(out, "01")
		} else {
			fmt.Fprint(out, 0)
		}
	}
	for i := 0; i < m; i++ {
		fmt.Fprint(out, 1)
	}
	out.Flush()
}

// 401C
package main

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

func main() {
	var n, m int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)
	if n > m+1 || (n+1)*2 < m {
		fmt.Fprint(out, -1)
		return
	}
	m -= n - 1
	if m > 0 {
		fmt.Fprint(out, 1)
		m -= 1
	}
	for i := 0; i < n; i++ {
		if m != 0 {
			m -= 1
			fmt.Fprint(out, 1)
		}
		if i != n-1 {
			fmt.Fprint(out, "01")
		} else {
			fmt.Fprint(out, 0)
		}
	}
	for i := 0; i < m; i++ {
		fmt.Fprint(out, 1)
	}
}

// 401C
package main

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

func main() {
	var n, m int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)
	if n > m+1 || (n+1)*2 < m {
		fmt.Fprint(out, -1)
	}
	m -= n - 1
	if m > 0 {
		fmt.Fprint(out, 1)
		m -= 1
	}
	for i := 0; i < n; i++ {
		if m != 0 {
			m -= 1
			fmt.Fprint(out, 1)
		}
		if i != n-1 {
			fmt.Fprint(out, "01")
		} else {
			fmt.Fprint(out, 0)
		}
	}
	for i := 0; i < m; i++ {
		fmt.Fprint(out, 1)
	}
	out.Flush()
}

package main

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

func main() {
    scanner.Split(bufio.ScanWords)
    n := scanner.NextInt()
    m := scanner.NextInt()
    if 2*n+2 < m || n > m+1 {
        fmt.Println("-1")
    } else {
        if m-n >= 2 {
            fmt.Printf("11")
            m -= 2
        } else if m-n == 1 {
            fmt.Printf("1")
            m -= 1
        }
        for i := 0; i < n; i++ {
            fmt.Printf("0")
            if m > 0 {
                fmt.Printf("1")
                m--
            }
            if m > 0 {
                fmt.Printf("1")
                m--
            }
        }
        fmt.Println()
    }
}

type Scanner struct {
    *bufio.Scanner
}

var scanner = Scanner{bufio.NewScanner(os.Stdin)}

func (self *Scanner) Next() string {
    if !self.Scan() {
        panic(self.Err())
    }
    return self.Text()
}

func (self *Scanner) NextInt() int {
    x, err := strconv.Atoi(self.Next())
    if err != nil {
        panic(err)
    }
    return x
}

func (self *Scanner) NextDouble() float64 {
    x, err := strconv.ParseFloat(self.Next(), 64)
    if err != nil {
        panic(err)
    }
    return x
}