Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array $$$a$$$ consisting of $$$n$$$ positive integers. An operation consists of choosing an element and either adding $$$1$$$ to it or subtracting $$$1$$$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $$$1$$$. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!

The first line contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)  — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. ($$$1 \le a_i \le 10^{12}$$$)  — the elements of the array.

Print a single integer  — the minimum number of operations required to make the array good.

NoteIn the first example, the first array is already good, since the greatest common divisor of all the elements is $$$2$$$.In the second example, we may apply the following operations:  Add $$$1$$$ to the second element, making it equal to $$$9$$$.  Subtract $$$1$$$ from the third element, making it equal to $$$6$$$.  Add $$$1$$$ to the fifth element, making it equal to $$$2$$$.  Add $$$1$$$ to the fifth element again, making it equal to $$$3$$$. The greatest common divisor of all elements will then be equal to $$$3$$$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.

package main

import (
	"bufio"
	"fmt"
	"io"
	"math/rand"
	"os"
	"strconv"
	"time"
)

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)

	n := NextInt()

	a := make([]int64, n)
	var res int64
	for i := 0; i < n; i++ {
		a[i] = NextInt64()
		if a[i]%2 == 1 {
			res++
		}
	}

	rand.Seed(time.Now().UnixNano())
	possible := make([]int64, 0, 100000)

	for i := 0; i <= 16; i++ {
		pos := rand.Intn(n)
		possible = possible[:0]
		for j := -1; j <= 1; j++ {
			d := a[pos] + int64(j)
			if d <= 0 {
				continue
			}
			for k := int64(2); k*k <= d; k++ {
				if d%k == 0 {
					possible = append(possible, k)
					for d%k == 0 {
						d /= k
					}
				}
			}
			if d != 1 {
				possible = append(possible, d)
			}

			for _, prime := range possible {
				// stderr("prime", prime)
				var cur int64
				for i := 0; cur < res && i < n; i++ {
					t := a[i] % prime
					if a[i] < prime || prime-t < t {
						cur += prime - t
					} else {
						cur += t
					}
				}
				if cur < res {
					res = cur
				}
			}
		}
	}
	fmt.Fprintln(out, res)
}


Just to remind, girls in Arpa's land are really nice.Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≤ i < k, and a1 = x and ak = y.  Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.

The first line contains integers n, m and w (1  ≤  n  ≤  1000, , 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 1000) — the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106) — the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.

Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.

NoteIn the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.

package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"os"
)

func RapidReader() io.Reader {
	b, _ := ioutil.ReadAll(os.Stdin)
	return bytes.NewReader(b)
}

func main() {
	reader := RapidReader()

	n, m, w := 0, 0, 0
	fmt.Fscan(reader, &n, &m, &w)

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

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

	xs, ys := make([]int, m), make([]int, m)
	for i := 0; i < m; i++ {
		fmt.Fscan(reader, &xs[i], &ys[i])
		xs[i]--
		ys[i]--
	}

	group := newDisjointSet(n)
	for i := 0; i < m; i++ {
		group[xs[i]].Union(group[ys[i]])
	}

	// groupWeight, groupValue := make(map[*Element]int), make(map[*Element]int)
	groupItems := make(map[*Element][]Item)
	for i := 0; i < n; i++ {
		root := group[i].Root()
		groupItems[root] = append(groupItems[root], Item{wh[i], bh[i]})
	}
	for key, items := range groupItems {
		sumW, sumV := 0, 0
		for _, item := range items {
			sumW += item.Weight
			sumV += item.Value
		}
		groupItems[key] = append(groupItems[key], Item{sumW, sumV})
	}

	ans := Knapsack01Group(groupItems, w)
	fmt.Println(ans)
}

// https://en.wikipedia.org/wiki/Disjoint-set_data_structure
type Element struct {
	Parent *Element
}

func newDisjointSet(n int) []*Element {
	ds := make([]*Element, n)
	for i := 0; i < n; i++ {
		ds[i] = new(Element)
		ds[i].Parent = ds[i]
	}
	return ds
}

func (x *Element) Root() *Element {
	if x.Parent == x {
		return x
	}
	x.Parent = x.Parent.Root()
	return x.Parent
}

func (x *Element) Union(y *Element) {
	if rand.Intn(2) == 0 {
		x.Root().Parent = y.Root()
	} else {
		y.Root().Parent = x.Root()
	}
}

type Item struct {
	Weight, Value int
}

func Knapsack01Group(itemGroups map[*Element][]Item, capacity int) int {
	dp := make([]int, capacity+1)
	for _, group := range itemGroups {
		for sum1 := len(dp) - 1; sum1 >= 0; sum1-- {
			for _, item := range group {
				func(sum2 int, newValue int) {
					if 0 <= sum2 && sum2 < len(dp) && dp[sum2] < newValue {
						dp[sum2] = newValue
					}
				}(sum1+item.Weight, dp[sum1]+item.Value)
			}
		}
	}
	return dp[capacity]
}

package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"os"
)

func RapidReader() io.Reader {
	b, _ := ioutil.ReadAll(os.Stdin)
	return bytes.NewReader(b)
}

func main() {
	reader := RapidReader()

	n, m, w := 0, 0, 0
	fmt.Fscanf(reader, "%d%d%d ", &n, &m, &w)

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

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

	xs, ys := make([]int, m), make([]int, m)
	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d%d ", &xs[i], &ys[i])
		xs[i]--
		ys[i]--
	}

	group := newDisjointSet(n)
	for i := 0; i < m; i++ {
		group[xs[i]].Union(group[ys[i]])
	}

	// groupWeight, groupValue := make(map[*Element]int), make(map[*Element]int)
	groupItems := make(map[*Element][]Item)
	for i := 0; i < n; i++ {
		root := group[i].Root()
		groupItems[root] = append(groupItems[root], Item{wh[i], bh[i]})
	}
	for key, items := range groupItems {
		sumW, sumV := 0, 0
		for _, item := range items {
			sumW += item.Weight
			sumV += item.Value
		}
		groupItems[key] = append(groupItems[key], Item{sumW, sumV})
	}

	ans := Knapsack01Group(groupItems, w)
	fmt.Println(ans)
}

// https://en.wikipedia.org/wiki/Disjoint-set_data_structure
type Element struct {
	Parent *Element
}

func newDisjointSet(n int) []*Element {
	ds := make([]*Element, n)
	for i := 0; i < n; i++ {
		ds[i] = new(Element)
		ds[i].Parent = ds[i]
	}
	return ds
}

func (x *Element) Root() *Element {
	if x.Parent == x {
		return x
	}
	x.Parent = x.Parent.Root()
	return x.Parent
}

func (x *Element) Union(y *Element) {
	if rand.Intn(2) == 0 {
		x.Root().Parent = y.Root()
	} else {
		y.Root().Parent = x.Root()
	}
}

type Item struct {
	Weight, Value int
}

func Knapsack01Group(itemGroups map[*Element][]Item, capacity int) int {
	dp := make([]int, capacity+1)
	for _, group := range itemGroups {
		for sum1 := len(dp) - 1; sum1 >= 0; sum1-- {
			for _, item := range group {
				func(sum2 int, newValue int) {
					if 0 <= sum2 && sum2 < len(dp) && dp[sum2] < newValue {
						dp[sum2] = newValue
					}
				}(sum1+item.Weight, dp[sum1]+item.Value)
			}
		}
	}
	return dp[capacity]
}

package main

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

type Hos struct {
    w, b int
}

func solve() {
    n, m, maxW := readInt(), readInt(), readInt()
    w, b := readIntArray(n), readIntArray(n)
    h, a := make([]Hos, n), make([][]int, n)
    for i := range w {
        h[i] = Hos{w[i], b[i]}
    }
    for i := 0; i < m; i++ {
        x, y := readInt()-1, readInt()-1
        a[x] = append(a[x], y)
        a[y] = append(a[y], x)
    }

    was := make([]bool, n)
    g := [][]Hos{}
    for i := range w {
        if was[i] {
            continue
        }

        q, group := []int{i}, []int{}
        was[i] = true
        for len(q) > 0 {
            cur := q[len(q)-1]
            q, group = q[:len(q)-1], append(group, cur)
            for _, f := range a[cur] {
                if !was[f] {
                    was[f] = true
                    q = append(q, f)
                }
            }
        }

        sw, sb, curG := 0, 0, []Hos{}
        for _, i := range group {
            sw += h[i].w
            sb += h[i].b
            curG = append(curG, h[i])
        }
        curG = append(curG, Hos{sw, sb})
        g = append(g, curG)
    }

    prev := make([]int, maxW+1)
    for i := range g {
        curG, cur := g[i], make([]int, maxW+1)
        for j := 0; j <= maxW; j++ {
            val := prev[j]
            for _, hos := range curG {
                if hos.w <= j {
                    if curB := hos.b + prev[j-hos.w]; curB > val {
                        val = curB
                    }
                }
            }
            cur[j] = val
        }
        prev = cur
    }
    fmt.Println(prev[maxW])
}

// Helpers

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

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

// Math

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return 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
}

// IO

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

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

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

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

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

// Sort

type Ints64 []int64

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

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer

var n, m, W, cntGroup int
var w, b []int
var adj [][]int
var group []int
var groupW, groupB int
var sumW, sumB []int
var members [][]int
var dp [][]int

func dfs(u int) {
	members[cntGroup] = append(members[cntGroup], u)
	group[u] = cntGroup
	groupW += w[u]
	groupB += b[u]
	for _, v := range adj[u] {
		if group[v] == 0 {
			dfs(v)
		}
	}
}

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

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()

	fmt.Fscanf(bufin, "%d %d %d\n", &n, &m, &W)

	w = make([]int, n+1)
	for i := 1; i <= n; i++ {
		fmt.Fscanf(bufin, "%d\n", &w[i])
	}

	b = make([]int, n+1)
	for i := 1; i <= n; i++ {
		fmt.Fscanf(bufin, "%d\n", &b[i])
	}

	adj = make([][]int, n+1)
	var u, v int
	for i := 1; i <= m; i++ {
		fmt.Fscanf(bufin, "%d %d\n", &u, &v)
		adj[u] = append(adj[u], v)
		adj[v] = append(adj[v], u)
	}

	group = make([]int, n+1)
	sumW = make([]int, n+1)
	sumB = make([]int, n+1)
	members = make([][]int, n+1)
	cntGroup = 0
	for u := 1; u <= n; u++ {
		if group[u] == 0 {
			cntGroup++
			groupW = 0
			groupB = 0
			dfs(u)
			sumW[cntGroup] = groupW
			sumB[cntGroup] = groupB
		}
	}

	dp = make([][]int, cntGroup+1)
	for g := 0; g <= cntGroup; g++ {
		dp[g] = make([]int, W+1)
	}

	for ig := 1; ig <= cntGroup; ig++ {
		for iw := 1; iw <= W; iw++ {
			dp[ig][iw] = dp[ig-1][iw]
			if iw >= sumW[ig] {
				dp[ig][iw] = max(dp[ig][iw], dp[ig-1][iw-sumW[ig]]+sumB[ig])
			}
			for _, i := range members[ig] {
				if iw >= w[i] {
					dp[ig][iw] = max(dp[ig][iw], dp[ig-1][iw-w[i]]+b[i])
				}
			}
		}
	}

	fmt.Fprintf(bufout, "%d\n", dp[cntGroup][W])
}

package main

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

type DJSet struct {
	upper []int
}

func NewDJSet(n int) *DJSet {
	s := DJSet{upper: make([]int, n)}
	for i := 0; i < n; i++ {
		s.upper[i] = -1
	}
	return &s
}

func (s *DJSet) Root(x int) int {
	if s.upper[x] < 0 {
		return x
	} else {
		s.upper[x] = s.Root(s.upper[x])
	}
	return s.upper[x]
}

func (s *DJSet) Union(x, y int) bool {
	x = s.Root(x)
	y = s.Root(y)
	if x != y {
		if s.upper[y] < s.upper[x] {
			x, y = y, x
		}
		s.upper[x] += s.upper[y]
		s.upper[y] = x
	}
	return x == y
}

func (s *DJSet) Equiv(x, y int) bool {
	return s.Root(x) == s.Root(y)
}

func (s *DJSet) Count() int {
	ct := 0
	for _, u := range s.upper {
		if u < 0 {
			ct++
		}
	}
	return ct
}

func solve() {
	n := readInt()
	m := readInt()
	W := readInt()
	w := readIntArray(n)
	b := readIntArray(n)
	djset := NewDJSet(n)
	for i := 0; i < m; i++ {
		djset.Union(readInt()-1, readInt()-1)
	}
	dp := make([]int, 1050)
	for i := 0; i < len(dp); i++ {
		dp[i] = -100000000
	}
	dp[0] = 0
	for i := 0; i < n; i++ {
		if djset.upper[i] >= 0 {
			continue
		}
		ndp := make([]int, len(dp))
		copy(ndp, dp)
		sw := 0
		sb := 0
		for j := 0; j < n; j++ {
			if djset.Equiv(i, j) {
				for k := 0; k+w[j] < len(dp); k++ {
					ndp[k+w[j]] = max(ndp[k+w[j]], dp[k]+b[j])
				}
				sw += w[j]
				sb += b[j]
			}
		}
		for k := 0; k+sw < len(dp); k++ {
			ndp[k+sw] = max(ndp[k+sw], dp[k]+sb)
		}
		dp = ndp
	}
	best := 0
	for i := 0; i <= W; i++ {
		best = max(best, dp[i])
	}
	fmt.Println(best)
}

// Helpers

const INPUT = `4 2 11
2 4 6 6
6 4 2 1
1 2
2 3`

var scanner *bufio.Scanner

func main() {
	if true || len(os.Getenv("ONLINE_JUDGE")) > 0 {
		scanner = bufio.NewScanner(os.Stdin)
	} else {
		scanner = bufio.NewScanner(strings.NewReader(INPUT))
	}
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

// Math

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return 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
}

// IO

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

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

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

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

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

// Sort

type Ints64 []int64

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

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

type DJSet struct {
	upper []int
}

func NewDJSet(n int) *DJSet {
	s := DJSet{upper: make([]int, n)}
	for i := 0; i < n; i++ {
		s.upper[i] = -1
	}
	return &s
}

func (s *DJSet) Root(x int) int {
	if s.upper[x] < 0 {
		return x
	} else {
		s.upper[x] = s.Root(s.upper[x])
	}
	return s.upper[x]
}

func (s *DJSet) Union(x, y int) bool {
	x = s.Root(x)
	y = s.Root(y)
	if x != y {
		if s.upper[y] < s.upper[x] {
			x, y = y, x
		}
		s.upper[x] += s.upper[y]
		s.upper[y] = x
	}
	return x == y
}

func (s *DJSet) Equiv(x, y int) bool {
	return s.Root(x) == s.Root(y)
}

func (s *DJSet) Count() int {
	ct := 0
	for _, u := range s.upper {
		if u < 0 {
			ct++
		}
	}
	return ct
}

func solve() {
	n := readInt()
	m := readInt()
	W := readInt()
	w := readIntArray(n)
	b := readIntArray(n)
	djset := NewDJSet(n)
	for i := 0; i < m; i++ {
		djset.Union(readInt()-1, readInt()-1)
	}
	dp := make([]int, 1050)
	for i := 0; i < len(dp); i++ {
		dp[i] = -100000000
	}
	dp[0] = 0
	for i := 0; i < n; i++ {
		if djset.upper[i] >= 0 {
			continue
		}
		ndp := make([]int, len(dp))
		copy(ndp, dp)
		sw := 0
		sb := 0
		for j := 0; j < n; j++ {
			if djset.Equiv(i, j) {
				for k := 0; k+w[j] < len(dp); k++ {
					ndp[k+w[j]] = max(ndp[k+w[j]], dp[k]+b[j])
				}
				sw += w[j]
				sb += b[j]
			}
		}
		for k := 0; k+sw < len(dp); k++ {
			ndp[k+sw] = max(ndp[k+sw], dp[k]+sb)
		}
		dp = ndp
	}
	best := 0
	for i := 0; i <= W; i++ {
		best = max(best, dp[i])
	}
	fmt.Println(best)
}

// Helpers

const INPUT = `4 2 11
2 4 6 6
6 4 2 1
1 2
2 3`

var scanner *bufio.Scanner

func main() {
	if len(os.Getenv("ONLINE_JUDGE")) > 0 {
		scanner = bufio.NewScanner(os.Stdin)
	} else {
		scanner = bufio.NewScanner(strings.NewReader(INPUT))
	}
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

// Math

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return 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
}

// IO

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

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

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

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

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

// Sort

type Ints64 []int64

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

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/


Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view):  Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.

The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≤ n ≤ 100000). The i-th (1 ≤ i ≤ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.

Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.

NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled:   In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher:   In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:

package main

import "os"
import "bufio"
import "fmt"

func main(){
	var s string
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	fmt.Fscan(r, &s)
	c, cc := 0, 0
	if len(s)%2 != 0 {
		w.WriteString("No\n")
	} else {
		for i:=0; i<len(s); i++ {
			if i%2 == 0 {
				if string(s[i]) == "+" {
					cc += 1
				} else {
					c += 1
				}
			} else {
				if string(s[i]) == "+" {
					c += 1
				} else {
					cc += 1
				}
			}
		}
		if c == cc {
			w.WriteString("Yes\n")
		} else {
			w.WriteString("No\n")
		}
	}
	w.Flush()
}

package main

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

var (
	inout   *bufio.ReadWriter = bufio.NewReadWriter(bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout))
	s string
	n int
)

func next() string {
	box := []byte{}
	for ;;{
		char, err := inout.ReadByte()
		if err!=nil||char==' '||char=='\n' {
			return string(box)
		} else if char == '\r' {
			_, _ = inout.ReadByte()
			return string(box)
		} else {
			box=append(box, char)
		}
	}
}

func main() {
	defer inout.Flush()
	s=next()
	n=len(s)
	if n%2==1 {
		fmt.Fprintln(inout, "No")
		return
	}
	hit:=0
	st:=make([]byte, n)
	for j:=0;j<n;j++ {
		if hit==0 || st[hit-1]!=s[j] {
			st[hit]=s[j]
			hit++
		} else {
			hit--
		}
	}
	if hit!=0 {
		fmt.Fprintln(inout, "No")
	} else {
		fmt.Fprintln(inout, "Yes")
	}
}

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    var x string
    fmt.Fscan(reader,&x)
    ans := false
    if len(x)%2 == 0 {
        s := make([]byte,0,len(x))
        for i := 0; i < len(x); i++ {
            if (len(s) == 0) || (s[len(s)-1] != x[i]) {
                s = append(s,x[i])
            } else {
                s = s[:len(s)-1]
            }
        }
        if len(s) == 0 { ans = true }
    }
    if ans { fmt.Println("Yes") } else { fmt.Println("No") }
}

//343B
package main

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

var io = bufio.NewReadWriter(bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout))
var sequence string
var n int

func nextstring() string {
	x := []byte{}
	for {
		c, errors := io.ReadByte()
		if c == '\r' {
			_, _ = io.ReadByte()
			return string(x)
		} else if errors != nil || c == ' ' || c == '\n' {
			return string(x)
		} else {
			x = append(x, c)
		}
	}
}

func main() {
	defer io.Flush()
	sequence = nextstring()
	n = len(sequence)
	if n%2 == 1 {
		fmt.Fprintln(io, "No")
		return
	}
	t := make([]byte, n)
	cr := 0
	for i := 0; i < n; i++ {
		if cr != 0 && t[cr-1] == sequence[i] {
			cr--
		} else {
			t[cr] = sequence[i]
			cr++
		}
	}
	if cr == 0 {
		fmt.Fprintln(io, "Yes")
	} else {
		fmt.Fprintln(io, "No")
	}
}

package main

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

var (
	rw   *bufio.ReadWriter = bufio.NewReadWriter(bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout))
	seq string
	n int
)

func nextString() string {
	token := []byte{}
	for {
		c, err := rw.ReadByte()
		if err != nil || c == ' ' || c == '\n' {
			return string(token)
		} else if c == '\r' {
			_, _ = rw.ReadByte()
			return string(token)
		} else {
			token = append(token, c)
		}
	}
}

func main() {
	defer rw.Flush()
	seq = nextString()
	n = len(seq)
	if n % 2 == 1 {
		fmt.Fprintln(rw, "No")
		return
	}
	st := make([]byte, n)
	sz := 0
	for i := 0; i < n; i++ {
		if sz == 0 || st[sz-1] != seq[i] {
			st[sz] = seq[i]
			sz++
		} else {
			sz--
		}
	}
	if sz == 0 {
		fmt.Fprintln(rw, "Yes")
	} else {
		fmt.Fprintln(rw, "No")
	}
}

package main

import "os"
import "bufio"

func main(){
	var s string
	r := bufio.NewScanner(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	s = r.Text()
	c, cc := 0, 0
	if len(s)%2 != 0 {
		w.WriteString("No\n")
	} else {
		for i:=0; i<len(s); i++ {
			if i%2 == 0 {
				if string(s[i]) == "+" {
					cc += 1
				} else {
					c += 1
				}
			} else {
				if string(s[i]) == "+" {
					c += 1
				} else {
					cc += 1
				}
			}
		}
		if c == cc {
			w.WriteString("Yes\n")
		} else {
			w.WriteString("No\n")
		}
	}
	w.Flush()
}

package main

import "os"
import "bufio"

func main(){
	var s string
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanLines)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	s = r.Text()
	c, cc := 0, 0
	if len(s)%2 != 0 {
		w.WriteString("No\n")
	} else {
		for i:=0; i<len(s); i++ {
			if i%2 == 0 {
				if string(s[i]) == "+" {
					cc += 1
				} else {
					c += 1
				}
			} else {
				if string(s[i]) == "+" {
					c += 1
				} else {
					cc += 1
				}
			}
		}
		if c == cc {
			w.WriteString("Yes\n")
		} else {
			w.WriteString("No\n")
		}
	}
	w.Flush()
}

package main

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

func main() {
    var i,t int
    var s string
    input := bufio.NewReader(os.Stdin)
    fmt.Fscan(input,&s)
    for i=0;i<len(s);i++ {
    	if (s[i]=='+') {
    	        if(int(s[i])^i%2!=0){
        		t++
        	} else {
        		t--
        	}
    	} else {
    		t--
    	}
    }
    if t!=0 {
    	fmt.Println("No")
    } else {
    	fmt.Println("Yes")
    }
}

package main

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

var (
	inout   *bufio.ReadWriter = bufio.NewReadWriter(bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout))
	s string
	n int
)

func next() string {
	box := []byte{}
	for {
		char, err := inout.ReadByte()
		if err != nil || char == ' ' || char == '\n' {
			return string(box)
		} else if char == '\r' {
			_, _ = inout.ReadByte()
			return string(box)
		} else {
			box=append(box,char)
		}
	}
}

func main() {
	s = next()
	n = len(s)
	if n%2==1 {
		fmt.Fprintln(inout, "No")
		return
	}
	st := make([]byte, n)
	hit := 0
	for i:=0;i<n;i++ {
		if hit==0 || st[hit-1]!=s[i] {
			st[hit] = s[i]
			hit++
		} else {
			hit--
		}
	}
	if hit==0 {
		fmt.Fprintln(inout, "Yes")
	} else {
		fmt.Fprintln(inout, "No")
	}
	inout.Flush()
}


There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows:   $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$.

package main

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

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

	var T, n, m, k, q int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m, &k, &q)
		a := make([][2]int, q)
		for i := range a {
			Fscan(in, &a[i][0], &a[i][1])
		}
		ans := int64(1)
		x, y := map[int]bool{}, map[int]bool{}
		for i := q - 1; i >= 0 && len(x) < n && len(y) < m; i-- {
			r, c := a[i][0], a[i][1]
			if !x[r] || !y[c] {
				ans = ans * int64(k) % 998244353
				x[r] = true
				y[c] = true
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var x, y [2e5 + 1]int
	var t, n, m, k, q int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &m, &k, &q)
		a := make([][2]int, q)
		for i := range a {
			Fscan(in, &a[i][0], &a[i][1])
		}
		ans := int64(1)
		for i, nx, ny := q-1, 0, 0; i >= 0 && nx < n && ny < m; i-- {
			r, c := a[i][0], a[i][1]
			if x[r] != t || y[c] != t {
				ans = ans * int64(k) % 998244353
				if x[r] != t {
					x[r] = t
					nx++
				}
				if y[c] != t {
					y[c] = t
					ny++
				}
			}
		}
		Fprintln(out, ans)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
var x, y [2e5 + 1]int

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

	var t, n, m, k, q int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &m, &k, &q)
		a := make([][2]int, q)
		for i := range a {
			Fscan(in, &a[i][0], &a[i][1])
		}
		ans := int64(1)
		for i, nx, ny := q-1, 0, 0; i >= 0 && nx < n && ny < m; i-- {
			r, c := a[i][0], a[i][1]
			if x[r] != t || y[c] != t {
				ans = ans * int64(k) % 998244353
				if x[r] != t {
					x[r] = t
					nx++
				}
				if y[c] != t {
					y[c] = t
					ny++
				}
			}
		}
		Fprintln(out, ans)
	}
}

package main

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

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

	var T, n, m, k, q int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m, &k, &q)
		a := make([][2]int, q)
		for i := range a {
			Fscan(in, &a[i][0], &a[i][1])
		}
		x, y := map[int]bool{}, map[int]bool{}
		ans := int64(1)
		for i := q - 1; i >= 0; i-- {
			r, c := a[i][0], a[i][1]
			if len(x) < n && len(y) < m && (!x[r] || !y[c]) {
				ans = ans * int64(k) % 998244353
				x[r] = true
				y[c] = true
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

const mod = 998244353

var x, y [200005]int
var X, Y [200005]bool

func main() {
	var t, n, m, k, q, N, M int
	var ans int64
	readInt(&t)
	for tt := 0; tt < t; tt++ {
		ans = 1
		N = 0
		M = 0
		readInt(&n)
		readInt(&m)
		readInt(&k)
		readInt(&q)
		maxn := 0
		for i := 1; i <= q; i++ {
			readInt(&x[i])
			readInt(&y[i])
			if x[i] > maxn {
				maxn = x[i]
			}
			if y[i] > maxn {
				maxn = y[i]
			}
		}
		for i := 0; i <= maxn; i++ {
			X[i] = false
			Y[i] = false
		}
		for i := q; i >= 1 && N < n && M < m; i-- {
			if !X[x[i]] || !Y[y[i]] {
				if !X[x[i]] {
					N++
					X[x[i]] = true
				}
				if !Y[y[i]] {
					M++
					Y[y[i]] = true
				}
				ans = ans * int64(k) % mod
			}
		}
		fmt.Println(ans)
	}
}

var in = bufio.NewReader(os.Stdin)

func readInt(out *int) error {
	var ans, sign int = 0, 1
	var readed = false
	c, err := in.ReadByte()
	for ; err == nil && (c < '0' || '9' < c); c, err = in.ReadByte() {
		if c == '-' {
			sign = -sign
		}
	}
	for ; err == nil && '0' <= c && c <= '9'; c, err = in.ReadByte() {
		ans = ans<<3 + ans<<1 + int(c-'0')
		readed = true
	}
	if readed {
		*out = ans * sign
		return nil
	}
	return err
}

package main

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

const Mod = 998244353

func solve(ops [][]int, n, m, k, q int) {
	ans := int64(1)
	sx, sy := make(map[int]bool), make(map[int]bool)
	for i := q - 1; i >= 0; i-- {
		fl := false
		row := ops[i][0]
		col := ops[i][1]
		_, ok1 := sx[row]
		_, ok2 := sy[col]
		if !ok1 {
			fl = true
			sx[row] = true
		}
		if !ok2 {
			fl = true
			sy[col] = true
		}
		if fl {
			ans = (int64(ans) * int64(k) % Mod)
		}
		if len(sx) == n || len(sy) == m {
			break
		}
	}
	fmt.Println(ans)
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < t; i++ {
		scanner.Scan()
		n, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		m, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		k, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		q, _ := strconv.Atoi(scanner.Text())

		ops := make([][]int, q)
		for j := 0; j < q; j++ {
			scanner.Scan()
			ops[j] = make([]int, 2)
			ops[j][0], _ = strconv.Atoi(scanner.Text())
			scanner.Scan()
			ops[j][1], _ = strconv.Atoi(scanner.Text())
		}
		solve(ops, n, m, k, q)
	}

}

package main

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

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

	var T, n, m, k, q int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m, &k, &q)
		a := make([][2]int, q)
		for i := range a {
			Fscan(in, &a[i][0], &a[i][1])
		}
		x, y := map[int]bool{}, map[int]bool{}
		ans := int64(1)
		for i := q - 1; i >= 0; i-- {
			r, c := a[i][0], a[i][1]
			if len(x) < n && len(y) < m && (!x[r] || y[c]) {
				ans = ans * int64(k) % 998244353
				x[r] = true
				y[c] = true
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

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

	var T, n, m, k, q int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m, &k, &q)
		a := make([][2]int, q)
		for i := range a {
			Fscan(in, &a[i][0], &a[i][1])
		}
		x, y := map[int]bool{}, map[int]bool{}
		for i := q - 1; i >= 0; i-- {
			r, c := a[i][0], a[i][1]
			if x[r] && y[c] {
				q--
			} else {
				x[r] = true
				y[c] = true
			}
		}
		ans := int64(1)
		for ; q > 0; q-- {
			ans = ans * int64(k) % 998244353
		}
		Fprintln(out, ans)
	}
}

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

package main

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

const mod = 998244353

var x, y [200005]int
var X, Y [200005]bool

func main() {
	var t, n, m, k, q, ans, N, M int
	readInt(&t)
	for tt := 0; tt < t; tt++ {
		ans = 1
		N = 0
		M = 0
		readInt(&n)
		readInt(&m)
		readInt(&k)
		readInt(&q)
		maxn := 0
		for i := 1; i <= q; i++ {
			readInt(&x[i])
			readInt(&y[i])
			if x[i] > maxn {
				maxn = x[i]
			}
			if y[i] > maxn {
				maxn = y[i]
			}
		}
		for i := 0; i <= maxn; i++ {
			X[i] = false
			Y[i] = false
		}
		for i := q; i >= 1 && N < n && M < m; i-- {
			if !X[x[i]] || !Y[y[i]] {
				if !X[x[i]] {
					N++
					X[x[i]] = true
				}
				if !Y[y[i]] {
					M++
					Y[y[i]] = true
				}
				ans *= k
				ans %= mod
			}
		}
		fmt.Println(ans)
	}
}

var in = bufio.NewReader(os.Stdin)

func readInt(out *int) error {
	var ans, sign int = 0, 1
	var readed = false
	c, err := in.ReadByte()
	for ; err == nil && (c < '0' || '9' < c); c, err = in.ReadByte() {
		if c == '-' {
			sign = -sign
		}
	}
	for ; err == nil && '0' <= c && c <= '9'; c, err = in.ReadByte() {
		ans = ans<<3 + ans<<1 + int(c-'0')
		readed = true
	}
	if readed {
		*out = ans * sign
		return nil
	}
	return err
}

package main

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

const mod = 998244353

var x, y [200005]int
var X, Y [200005]bool

func main() {
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t, n, m, k, q, ans, N, M int
	readInt(&t)
	for tt := 0; tt < t; tt++ {
		ans = 1
		N = 0
		M = 0
		readInt(&n)
		readInt(&m)
		readInt(&k)
		readInt(&q)
		maxn := 0
		for i := 1; i <= q; i++ {
			readInt(&x[i])
			readInt(&y[i])
			if x[i] > maxn {
				maxn = x[i]
			}
			if y[i] > maxn {
				maxn = y[i]
			}
		}
		for i := 0; i <= maxn; i++ {
			X[i] = false
			Y[i] = false
		}
		for i := q; i >= 1 && N < n && M < m; i-- {
			if !X[x[i]] || !Y[y[i]] {
				if !X[x[i]] {
					N++
					X[x[i]] = true
				}
				if !Y[y[i]] {
					M++
					Y[y[i]] = true
				}
				ans *= k
				ans %= mod
			}
		}
		fmt.Fprintln(out, ans)
	}
}

var in = bufio.NewReader(os.Stdin)

func readInt(out *int) error {
	var ans, sign int = 0, 1
	var readed = false
	c, err := in.ReadByte()
	for ; err == nil && (c < '0' || '9' < c); c, err = in.ReadByte() {
		if c == '-' {
			sign = -sign
		}
	}
	for ; err == nil && '0' <= c && c <= '9'; c, err = in.ReadByte() {
		ans = ans<<3 + ans<<1 + int(c-'0')
		readed = true
	}
	if readed {
		*out = ans * sign
		return nil
	}
	return err
}


For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:  Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.

The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).

If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.

NoteIn the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5 In the second example, g(1) = g(2) = g(3) = 1

package main

import (
	"bytes"
	"fmt"
)

func divide(n, a, b int) (x, y int, ok bool) {
	if a < b {
		y, x, ok = divide(n, b, a)
		return
	}
	x = n / a
	for x > 0 && (n-x*a)%b != 0 {
		x--
	}
	if (n-x*a)%b != 0 {
		return 0, 0, false
	}
	return x, (n - x*a) / b, true
}

func main() {
	var n, a, b int
	fmt.Scan(&n, &a, &b)

	x, y, ok := divide(n, a, b)
	if !ok {
		fmt.Println("-1")
		return
	}

	var seq []int

	i := 1
	for j := 0; j < x; j++ {
		for k := 0; k < a; k++ {
			if k < a-1 {
				seq = append(seq, i+1)
			} else {
				seq = append(seq, i-a+1)
			}
			i++
		}
	}
	for j := 0; j < y; j++ {
		for k := 0; k < b; k++ {
			if k < b-1 {
				seq = append(seq, i+1)
			} else {
				seq = append(seq, i-b+1)
			}
			i++
		}
	}

	var buf bytes.Buffer
	for i, x := range seq {
		fmt.Fprint(&buf, x)
		if i < len(seq)-1 {
			fmt.Fprint(&buf, " ")
		}
	}
	fmt.Println(buf.String())
}