package main

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

func handleInput() (int, []int, []int) {
	n := nextInt()
	a := make([]int, n)

	l := make([]int, n)
	for i, counter := 0, make(map[int]int, n); i < n; i++ {
		a[i] = nextInt()
		l[i] = counter[a[i]] + 1
		counter[a[i]] = l[i]
	}

	r, maxsize := make([]int, n), 0
	for j, counter := n-1, make(map[int]int, n); j >= 0; j-- {
		r[j] = counter[a[j]] + 1
		counter[a[j]] = r[j]
		if maxsize < r[j] {
			maxsize = r[j]
		}
	}
	return maxsize, l, r
}

type fenwick []int

func (this fenwick) get(idx int) int {
	sum := 0
	for idx > 0 {
		sum, idx = sum+this[idx], idx-(-idx&idx)
	}
	return sum
}

func (this fenwick) add(idx int, val int) {
	for idx < len(this) {
		this[idx], idx = this[idx]+val, idx+(-idx&idx)
	}
}

func solveBIT(maxsize int, l []int, r []int) int64 {
	fen := make(fenwick, maxsize+1)
	var count int64
	for i := len(l) - 1; i >= 0; i-- {
		count += int64(fen.get(l[i] - 1))
		fen.add(r[i], 1)
	}
	return count
}

func main() {
	//defer profile.Start(profile.ProfilePath(".")).Stop()
	defer flush()

	solve := solveBIT
	printn(solve(handleInput()))
}

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

var scanner = bufio.NewScanner(os.Stdin)

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

func nextWord() string {
	return next()
}

func nextLine() string {
	defer scanner.Split(bufio.ScanWords)
	scanner.Split(bufio.ScanLines)
	return strings.TrimSpace(next())
}

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

var stdout = bufio.NewWriter(os.Stdout)

func printa(a ...interface{}) (int, error) {
	return fmt.Fprint(stdout, a...)
}

func printn(a ...interface{}) (int, error) {
	return fmt.Fprintln(stdout, a...)
}

func printf(format string, a ...interface{}) (int, error) {
	return fmt.Fprintf(stdout, format, a...)
}

func flush() error {
	return stdout.Flush()
}

package main

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

func handleInput() (int, []int, []int) {
	n := nextInt()
	a := make([]int, n)

	l := make([]int, n)
	for i, counter := 0, make(map[int]int, n); i < n; i++ {
		a[i] = nextInt()
		l[i] = counter[a[i]] + 1
		counter[a[i]] = l[i]
	}

	r, maxsize := make([]int, n), 0
	for j, counter := n-1, make(map[int]int, n); j >= 0; j-- {
		r[j] = counter[a[j]] + 1
		counter[a[j]] = r[j]
		if maxsize < r[j] {
			maxsize = r[j]
		}
	}
	return maxsize, l, r
}

type fenwick []int

func (this fenwick) get(idx int) int {
	sum := 0
	for idx > 0 {
		sum, idx = sum+this[idx], idx-(-idx&idx)
	}
	return sum
}

func (this fenwick) add(idx int, val int) {
	for idx < len(this) {
		this[idx], idx = this[idx]+val, idx+(-idx&idx)
	}
}

func solveBIT(maxsize int, l []int, r []int) int64 {
	fen := make(fenwick, maxsize+1)
	var count int64
	for i := len(l) - 1; i >= 0; i-- {
		count += int64(fen.get(l[i] - 1))
		fen.add(r[i], 1)
	}
	return count
}

func solveDaC(maxsize int, l []int, r []int) int64 {
	var solvePartial func(int, int) int64
	solvePartial = func(s, e int) int64 {
		if e-s < 2 {
			return 0
		}
		mid := (s + e) / 2
		p1, p2 := solvePartial(s, mid), solvePartial(mid, e)

		pl, pr := make([]int, mid-s), make([]int, e-mid)
		copy(pl, l[s:])
		copy(pr, r[mid:])
		sort.Sort(sort.IntSlice(pl))
		sort.Sort(sort.IntSlice(pr))

		var count int64
		for i, j := 0, 0; i < len(pl); i++ {
			for j < len(pr) && pl[i] > pr[j] {
				j++
			}
			count += int64(j)
		}
		return p1 + p2 + count
	}
	return solvePartial(0, len(l))
}

func main() {
	//defer profile.Start(profile.ProfilePath(".")).Stop()
	defer flush()

	solve := solveDaC
	printn(solve(handleInput()))
}

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

var scanner = bufio.NewScanner(os.Stdin)

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

func nextWord() string {
	return next()
}

func nextLine() string {
	defer scanner.Split(bufio.ScanWords)
	scanner.Split(bufio.ScanLines)
	return strings.TrimSpace(next())
}

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

var stdout = bufio.NewWriter(os.Stdout)

func printa(a ...interface{}) (int, error) {
	return fmt.Fprint(stdout, a...)
}

func printn(a ...interface{}) (int, error) {
	return fmt.Fprintln(stdout, a...)
}

func printf(format string, a ...interface{}) (int, error) {
	return fmt.Fprintf(stdout, format, a...)
}

func flush() error {
	return stdout.Flush()
}

package main

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

func handleInput() (int, []int, []int) {
	n := nextInt()
	a := make([]int, n)
	counter := make(map[int]int, n)

	l := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = nextInt()
		l[i] = counter[a[i]] + 1
		counter[a[i]] = l[i]
	}

	r, maxsize := make([]int, n), 0
	for i := 0; i < n; i++ {
		r[i] = counter[a[i]]
		counter[a[i]] = r[i] - 1
		if maxsize < r[i] {
			maxsize = r[i]
		}
	}

	return maxsize, l, r
}

type fenwick []int

func (this fenwick) get(idx int) int {
	sum := 0
	for idx > 0 {
		sum, idx = sum+this[idx], idx-(-idx&idx)
	}
	return sum
}

func (this fenwick) add(idx int, val int) {
	for idx < len(this) {
		this[idx], idx = this[idx]+val, idx+(-idx&idx)
	}
}

func solveBIT(maxsize int, l []int, r []int) int64 {
	fen := make(fenwick, maxsize+1)
	var count int64
	for i := len(l) - 1; i >= 0; i-- {
		count += int64(fen.get(l[i] - 1))
		fen.add(r[i], 1)
	}
	return count
}

func solveDaC0(maxsize int, l []int, r []int) int64 {
	// DaC with global merge buf
	buf := make([]int, len(l))
	merge := func(s, mid, e int, a []int) {
		cur, i, j := s, s, mid
		for i < mid && j < e {
			if a[i] < a[j] {
				buf[cur], cur, i = a[i], cur+1, i+1
			} else {
				buf[cur], cur, j = a[j], cur+1, j+1
			}
		}
		for i < mid {
			buf[cur], cur, i = a[i], cur+1, i+1
		}
		for j < e {
			buf[cur], cur, j = a[j], cur+1, j+1
		}
		copy(a[s:e], buf[s:e])
	}
	var solvePartial func(int, int) int64
	solvePartial = func(s, e int) int64 {
		if e-s < 2 {
			return 0
		}
		mid := (s + e) / 2
		count := solvePartial(s, mid) + solvePartial(mid, e)

		for i, j := s, mid; i < mid; i++ {
			for j < e && l[i] > r[j] {
				j++
			}
			count += int64(j - mid)
		}

		merge(s, mid, e, l)
		merge(s, mid, e, r)

		return count
	}
	return solvePartial(0, len(l))
}

func solveDaC1(maxsize int, l []int, r []int) int64 {
	// In this solution, Merge buf will be allocated for each merge
	// operation which is definitly wasteful
	merge := func(a []int, mid int) []int {
		buf := make([]int, len(a))
		cur, i, j := 0, 0, mid
		for i < mid && j < len(buf) {
			if a[i] < a[j] {
				buf[cur], cur, i = a[i], cur+1, i+1
			} else {
				buf[cur], cur, j = a[j], cur+1, j+1
			}
		}
		for i < mid {
			buf[cur], cur, i = a[i], cur+1, i+1
		}
		for j < len(buf) {
			buf[cur], cur, j = a[j], cur+1, j+1
		}
		return buf
	}
	var solvePartial func(int, int) int64
	solvePartial = func(s, e int) int64 {
		if e-s < 2 {
			return 0
		}
		mid := (s + e) / 2
		count := solvePartial(s, mid) + solvePartial(mid, e)

		for i, j := s, mid; i < mid; i++ {
			for j < e && l[i] > r[j] {
				j++
			}
			count += int64(j - mid)
		}

		copy(l[s:], merge(l[s:e], mid-s))
		copy(r[s:], merge(r[s:e], mid-s))

		return count
	}
	return solvePartial(0, len(l))
}

func solveDaCNaive(maxsize int, l []int, r []int) int64 {
	var solvePartial func(int, int) int64
	solvePartial = func(s, e int) int64 {
		if e-s < 2 {
			return 0
		}
		mid := (s + e) / 2
		p1, p2 := solvePartial(s, mid), solvePartial(mid, e)

		pl, pr := make([]int, mid-s), make([]int, e-mid)
		copy(pl, l[s:])
		copy(pr, r[mid:])
		sort.Sort(sort.IntSlice(pl))
		sort.Sort(sort.IntSlice(pr))

		var count int64
		for i, j := 0, 0; i < len(pl); i++ {
			for j < len(pr) && pl[i] > pr[j] {
				j++
			}
			count += int64(j)
		}
		return p1 + p2 + count
	}
	return solvePartial(0, len(l))
}

func main() {
	//defer profile.Start(profile.ProfilePath(".")).Stop()
	defer flush()

	solve := solveBIT
	printn(solve(handleInput()))
}

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

var scanner = bufio.NewScanner(os.Stdin)

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

func nextWord() string {
	return next()
}

func nextLine() string {
	defer scanner.Split(bufio.ScanWords)
	scanner.Split(bufio.ScanLines)
	return strings.TrimSpace(next())
}

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

var stdout = bufio.NewWriter(os.Stdout)

func printa(a ...interface{}) (int, error) {
	return fmt.Fprint(stdout, a...)
}

func printn(a ...interface{}) (int, error) {
	return fmt.Fprintln(stdout, a...)
}

func printf(format string, a ...interface{}) (int, error) {
	return fmt.Fprintf(stdout, format, a...)
}

func flush() error {
	return stdout.Flush()
}

package main

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

func handleInput() (int, []int, []int) {
	n := nextInt()
	a := make([]int, n)

	l := make([]int, n)
	for i, counter := 0, make(map[int]int, n); i < n; i++ {
		a[i] = nextInt()
		l[i] = counter[a[i]] + 1
		counter[a[i]] = l[i]
	}

	r, maxsize := make([]int, n), 0
	for j, counter := n-1, make(map[int]int, n); j >= 0; j-- {
		r[j] = counter[a[j]] + 1
		counter[a[j]] = r[j]
		if maxsize < r[j] {
			maxsize = r[j]
		}
	}
	return maxsize, l, r
}

type fenwick []int

func (this fenwick) get(idx int) int {
	sum := 0
	for idx > 0 {
		sum, idx = sum+this[idx], idx-(-idx&idx)
	}
	return sum
}

func (this fenwick) add(idx int, val int) {
	for idx < len(this) {
		this[idx], idx = this[idx]+val, idx+(-idx&idx)
	}
}

func solveBIT(maxsize int, l []int, r []int) int64 {
	fen := make(fenwick, maxsize+1)
	var count int64
	for i := len(l) - 1; i >= 0; i-- {
		count += int64(fen.get(l[i] - 1))
		fen.add(r[i], 1)
	}
	return count
}

func solveDaC0(maxsize int, l []int, r []int) int64 {
	// DaC with global merge buf
	buf := make([]int, len(l))
	merge := func(s, mid, e int, a []int) {
		cur, i, j := s, s, mid
		for i < mid && j < e {
			if a[i] < a[j] {
				buf[cur], cur, i = a[i], cur+1, i+1
			} else {
				buf[cur], cur, j = a[j], cur+1, j+1
			}
		}
		for i < mid {
			buf[cur], cur, i = a[i], cur+1, i+1
		}
		for j < e {
			buf[cur], cur, j = a[j], cur+1, j+1
		}
		copy(a[s:e], buf[s:e])
	}
	var solvePartial func(int, int) int64
	solvePartial = func(s, e int) int64 {
		if e-s < 2 {
			return 0
		}
		mid := (s + e) / 2
		count := solvePartial(s, mid) + solvePartial(mid, e)

		for i, j := s, mid; i < mid; i++ {
			for j < e && l[i] > r[j] {
				j++
			}
			count += int64(j - mid)
		}

		merge(s, mid, e, l)
		merge(s, mid, e, r)

		return count
	}
	return solvePartial(0, len(l))
}

func solveDaC1(maxsize int, l []int, r []int) int64 {
	// In this solution, Merge buf will be allocated for each merge
	// operation which is definitly wasteful
	merge := func(a []int, mid int) []int {
		buf := make([]int, len(a))
		cur, i, j := 0, 0, mid
		for i < mid && j < len(buf) {
			if a[i] < a[j] {
				buf[cur], cur, i = a[i], cur+1, i+1
			} else {
				buf[cur], cur, j = a[j], cur+1, j+1
			}
		}
		for i < mid {
			buf[cur], cur, i = a[i], cur+1, i+1
		}
		for j < len(buf) {
			buf[cur], cur, j = a[j], cur+1, j+1
		}
		return buf
	}
	var solvePartial func(int, int) int64
	solvePartial = func(s, e int) int64 {
		if e-s < 2 {
			return 0
		}
		mid := (s + e) / 2
		count := solvePartial(s, mid) + solvePartial(mid, e)

		for i, j := s, mid; i < mid; i++ {
			for j < e && l[i] > r[j] {
				j++
			}
			count += int64(j - mid)
		}

		copy(l[s:], merge(l[s:e], mid-s))
		copy(r[s:], merge(r[s:e], mid-s))

		return count
	}
	return solvePartial(0, len(l))
}

func solveDaCNaive(maxsize int, l []int, r []int) int64 {
	var solvePartial func(int, int) int64
	solvePartial = func(s, e int) int64 {
		if e-s < 2 {
			return 0
		}
		mid := (s + e) / 2
		p1, p2 := solvePartial(s, mid), solvePartial(mid, e)

		pl, pr := make([]int, mid-s), make([]int, e-mid)
		copy(pl, l[s:])
		copy(pr, r[mid:])
		sort.Sort(sort.IntSlice(pl))
		sort.Sort(sort.IntSlice(pr))

		var count int64
		for i, j := 0, 0; i < len(pl); i++ {
			for j < len(pr) && pl[i] > pr[j] {
				j++
			}
			count += int64(j)
		}
		return p1 + p2 + count
	}
	return solvePartial(0, len(l))
}

func main() {
	//defer profile.Start(profile.ProfilePath(".")).Stop()
	defer flush()

	solve := solveDaC0
	printn(solve(handleInput()))
}

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

var scanner = bufio.NewScanner(os.Stdin)

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

func nextWord() string {
	return next()
}

func nextLine() string {
	defer scanner.Split(bufio.ScanWords)
	scanner.Split(bufio.ScanLines)
	return strings.TrimSpace(next())
}

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

var stdout = bufio.NewWriter(os.Stdout)

func printa(a ...interface{}) (int, error) {
	return fmt.Fprint(stdout, a...)
}

func printn(a ...interface{}) (int, error) {
	return fmt.Fprintln(stdout, a...)
}

func printf(format string, a ...interface{}) (int, error) {
	return fmt.Fprintf(stdout, format, a...)
}

func flush() error {
	return stdout.Flush()
}

package main

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

func handleInput() (int, []int, []int) {
	n := nextInt()
	a := make([]int, n)

	l := make([]int, n)
	for i, counter := 0, make(map[int]int, n); i < n; i++ {
		a[i] = nextInt()
		l[i] = counter[a[i]] + 1
		counter[a[i]] = l[i]
	}

	r, maxsize := make([]int, n), 0
	for j, counter := n-1, make(map[int]int, n); j >= 0; j-- {
		r[j] = counter[a[j]] + 1
		counter[a[j]] = r[j]
		if maxsize < r[j] {
			maxsize = r[j]
		}
	}
	return maxsize, l, r
}

type fenwick []int

func (this fenwick) get(idx int) int {
	sum := 0
	for idx > 0 {
		sum, idx = sum+this[idx], idx-(-idx&idx)
	}
	return sum
}

func (this fenwick) add(idx int, val int) {
	for idx < len(this) {
		this[idx], idx = this[idx]+val, idx+(-idx&idx)
	}
}

func solveBIT(maxsize int, l []int, r []int) int64 {
	fen := make(fenwick, maxsize+1)
	var count int64
	for i := len(l) - 1; i >= 0; i-- {
		count += int64(fen.get(l[i] - 1))
		fen.add(r[i], 1)
	}
	return count
}

func solveDaC0(maxsize int, l []int, r []int) int64 {
	// DaC with global merge buf
	buf := make([]int, len(l))
	merge := func(s, mid, e int, a []int) {
		cur, i, j := s, s, mid
		for i < mid && j < e {
			if a[i] < a[j] {
				buf[cur], cur, i = a[i], cur+1, i+1
			} else {
				buf[cur], cur, j = a[j], cur+1, j+1
			}
		}
		for i < mid {
			buf[cur], cur, i = a[i], cur+1, i+1
		}
		for j < e {
			buf[cur], cur, j = a[j], cur+1, j+1
		}
		copy(a[s:e], buf[s:e])
	}
	var solvePartial func(int, int) int64
	solvePartial = func(s, e int) int64 {
		if e-s < 2 {
			return 0
		}
		mid := (s + e) / 2
		count := solvePartial(s, mid) + solvePartial(mid, e)

		for i, j := s, mid; i < mid; i++ {
			for j < e && l[i] > r[j] {
				j++
			}
			count += int64(j - mid)
		}

		merge(s, mid, e, l)
		merge(s, mid, e, r)

		return count
	}
	return solvePartial(0, len(l))
}

func solveDaC1(maxsize int, l []int, r []int) int64 {
	// In this solution, Merge buf will be allocated for each merge
	// operation which is definitly wasteful
	merge := func(a []int, mid int) []int {
		buf := make([]int, len(a))
		cur, i, j := 0, 0, mid
		for i < mid && j < len(buf) {
			if a[i] < a[j] {
				buf[cur], cur, i = a[i], cur+1, i+1
			} else {
				buf[cur], cur, j = a[j], cur+1, j+1
			}
		}
		for i < mid {
			buf[cur], cur, i = a[i], cur+1, i+1
		}
		for j < len(buf) {
			buf[cur], cur, j = a[j], cur+1, j+1
		}
		return buf
	}
	var solvePartial func(int, int) int64
	solvePartial = func(s, e int) int64 {
		if e-s < 2 {
			return 0
		}
		mid := (s + e) / 2
		count := solvePartial(s, mid) + solvePartial(mid, e)

		for i, j := s, mid; i < mid; i++ {
			for j < e && l[i] > r[j] {
				j++
			}
			count += int64(j - mid)
		}

		copy(l[s:], merge(l[s:e], mid-s))
		copy(r[s:], merge(r[s:e], mid-s))

		return count
	}
	return solvePartial(0, len(l))
}

func solveDaCNaive(maxsize int, l []int, r []int) int64 {
	var solvePartial func(int, int) int64
	solvePartial = func(s, e int) int64 {
		if e-s < 2 {
			return 0
		}
		mid := (s + e) / 2
		p1, p2 := solvePartial(s, mid), solvePartial(mid, e)

		pl, pr := make([]int, mid-s), make([]int, e-mid)
		copy(pl, l[s:])
		copy(pr, r[mid:])
		sort.Sort(sort.IntSlice(pl))
		sort.Sort(sort.IntSlice(pr))

		var count int64
		for i, j := 0, 0; i < len(pl); i++ {
			for j < len(pr) && pl[i] > pr[j] {
				j++
			}
			count += int64(j)
		}
		return p1 + p2 + count
	}
	return solvePartial(0, len(l))
}

func main() {
	//defer profile.Start(profile.ProfilePath(".")).Stop()
	defer flush()

	solve := solveDaC1
	printn(solve(handleInput()))
}

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

var scanner = bufio.NewScanner(os.Stdin)

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

func nextWord() string {
	return next()
}

func nextLine() string {
	defer scanner.Split(bufio.ScanWords)
	scanner.Split(bufio.ScanLines)
	return strings.TrimSpace(next())
}

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

var stdout = bufio.NewWriter(os.Stdout)

func printa(a ...interface{}) (int, error) {
	return fmt.Fprint(stdout, a...)
}

func printn(a ...interface{}) (int, error) {
	return fmt.Fprintln(stdout, a...)
}

func printf(format string, a ...interface{}) (int, error) {
	return fmt.Fprintf(stdout, format, a...)
}

func flush() error {
	return stdout.Flush()
}


package main

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

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

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func flush()                            { writer.Flush() }
func pp(a interface{})                  { fmt.Println(a) }

func solve(s string, k int) {
  res := 0
  for i := 0; i*2 < k; i++ {
    freq := make([]int, 26)
    for j := i; j < len(s); j += k {
      freq[int(s[j]-'a')]++
    }
    if k-1-i != i {
      for j := k - 1 - i; j < len(s); j += k {
        freq[int(s[j]-'a')]++
      }
    }
    sum, max := 0, 0
    for _, c := range freq {
      sum += c
      if c > max {
        max = c
      }
    }
    res += sum - max
  }
  printf("%d\n", res)
}

func main() {
  defer flush()

  var t int
  scanf("%d\n", &t)
  for i := 1; i <= t; i++ {
    var n, k int
    scanf("%d %d\n", &n, &k)
    var s string
    scanf("%s\n", &s)
    solve(s, k)
  }
}

package main

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

var lineDelim = byte('\r')
var reader *bufio.Reader = bufio.NewReader(os.Stdin)

func ReadIntsAndTrim() []int {
	str, _ := reader.ReadString(lineDelim)
	str = strings.TrimSpace(str)
    numbersRaw := strings.Split(str, " ")
    var numbers []int
    for _, i := range numbersRaw {
        n, _ := strconv.ParseInt(i, 10, 0)
        numbers = append(numbers, int(n))
    }

    return numbers
}

func ReadInt() int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    n, _ := strconv.Atoi(str)

    return int(n)
}

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

func ReadStringAndTrim() string {
	str, _ := reader.ReadString(lineDelim)
	str = strings.TrimSpace(str)

	return str
}

func CountSetsLetters(i, j int, a *[][]int) int {
	var sum int
	var max int
	b := *a
	for k := 0; k < 26; k++ {
		cSum := b[i][k] + b[j][k]
		sum += cSum
		max = Max(max, cSum)
	}

	return sum - max
}

func main() {
	nTestCases := ReadInt()
	for nTestCases != 0 {
		input := ReadIntsAndTrim()
		str := ReadStringAndTrim()
		n := input[0]
		k := input[1]
		r := []rune(str)
		var kSets [][]int
		for i := 0; i < k; i++ {
			lowercaseLettersCodes := make([]int, 26)
			kSets = append(kSets, lowercaseLettersCodes)
		}
		for i := 0; i < n; i++ {
			letterPos := int(r[i]) - int('a')
			kSets[i % k][letterPos] += 1
		}
		var sum int
		for i := 0; i < k; i++ {
			sum += CountSetsLetters(i, k - i - 1, &kSets)
		}
		fmt.Println(sum / 2)
		nTestCases -= 1
	}
}

package main

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

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

	defer out.Flush()
	var t int
	fmt.Fscanf(in,"%d\n",&t)
	for T := 0 ; T < t ; T ++ {
		var n, k int
		var s string
		fmt.Fscanf(in, "%d %d\n", &n, &k)
		fmt.Fscanf(in, "%s\n", &s)
		kit := n / k
		output := 0
		a := make([]int, n)
		for i := 0 ; i <= k / 2 ; i ++ {
			m := make(map[byte]int)
			cnt := 0
			for j := 0 ; j < kit ; j ++ {
				if a[j*k + i] == 0 {
					m[s[j*k + i]] ++
					a[j*k + i] = 1
					cnt ++
				}
				if a[j*k + k - i - 1] == 0 {
					m[s[j*k + k - i - 1]] ++
					a[j*k + k - i - 1] = 1
					cnt ++
				}
			}
			maxx := 0
			for _, val := range m {
				if val > maxx{
					maxx = val
				}
			}
			output += (cnt - maxx)
		}
		fmt.Println(output)
	}
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		arrs := strings.Split(string(line), " ")
		n, _ := strconv.ParseInt(arrs[0], 10, 64)
		k, _ := strconv.ParseInt(arrs[1], 10, 64)
		flag := make([]bool, n)
		str := readLine(reader)
		result := 0
		for i := int64(0); i < k; i++ {
			m := make(map[byte]int)
			traverse(str, &flag, i, k, &m)
			sum, max := 0,0
			for _, v := range m {
				sum += v
				if v > max {
					max = v
				}
			}
			result += sum - max
		}
		fmt.Println(result)
	}
}

func traverse(str []byte, flag *[]bool, index, k int64, m *map[byte]int) {
	if index >= int64(len(str)) || index < 0 || (*flag)[index] {
		return
	}
	(*flag)[index] = true
	count := (*m)[str[index]]
	(*m)[str[index]] = count + 1
	traverse(str, flag, index+k, k, m)
	traverse(str, flag, index-k, k, m)
	traverse(str, flag, int64(len(str))-1-index, k, m)
}

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/problemset/problem/1332/C
*/

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"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
	S    []rune
	cnts [][30]int
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n, k = ReadInt2()
		S = ReadRuneSlice()

		solve()
	}
}

func solve() {
	// uf := NewUnionFind(n)
	// for i := 0; i <= (n-1)/2; i++ {
	// 	j := n - 1 - i
	// 	uf.Unite(i, j)

	// 	for l := i + k; l < n; l += k {
	// 		uf.Unite(i, l)
	// 	}
	// }
	// for i := 0; i < n; i++ {
	// 	PrintfDebug("%d ", uf.Root(i))
	// }
	// PrintfDebug("\n")

	cnts = make([][30]int, n)

	for i := 0; i < n; i++ {
		cnts[i%k][S[i]-'a']++
	}
	ans := 0
	for i := 0; i < k; i++ {
		ans += differ(i, k-1-i)
	}
	fmt.Println(ans / 2)
}

func differ(u, v int) int {
	ret, mx := 0, 0
	for j := 0; j < 26; j++ {
		ret += cnts[u][j] + cnts[v][j]
		ChMax(&mx, cnts[u][j]+cnts[v][j])
	}
	return ret - mx
}

// ChMax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// 0-based
// uf := NewUnionFind(n)
// uf.Root(x) 			// Get root node of the node x
// uf.Unite(x, y) 	// Unite node x and node y
// uf.Same(x, y) 		// Judge x and y are in the same connected component.
// uf.CcSize(x) 		// Get size of the connected component including node x
// uf.CcNum() 			// Get number of connected components

// UnionFind provides disjoint set algorithm.
// Node id starts from 0 (0-based setting).
type UnionFind struct {
	parents []int
}

// NewUnionFind returns a pointer of a new instance of UnionFind.
func NewUnionFind(n int) *UnionFind {
	uf := new(UnionFind)
	uf.parents = make([]int, n)

	for i := 0; i < n; i++ {
		uf.parents[i] = -1
	}

	return uf
}

// Root method returns root node of an argument node.
// Root method is a recursive function.
func (uf *UnionFind) Root(x int) int {
	if uf.parents[x] < 0 {
		return x
	}

	// route compression
	uf.parents[x] = uf.Root(uf.parents[x])
	return uf.parents[x]
}

// Unite method merges a set including x and a set including y.
func (uf *UnionFind) Unite(x, y int) bool {
	xp := uf.Root(x)
	yp := uf.Root(y)

	if xp == yp {
		return false
	}

	// merge: xp -> yp
	// merge larger set to smaller set
	if uf.CcSize(xp) > uf.CcSize(yp) {
		xp, yp = yp, xp
	}
	// update set size
	uf.parents[yp] += uf.parents[xp]
	// finally, merge
	uf.parents[xp] = yp

	return true
}

// Same method returns whether x is in the set including y or not.
func (uf *UnionFind) Same(x, y int) bool {
	return uf.Root(x) == uf.Root(y)
}

// CcSize method returns the size of a set including an argument node.
func (uf *UnionFind) CcSize(x int) int {
	return -uf.parents[uf.Root(x)]
}

// CcNum method returns the number of connected components.
// Time complextity is O(n)
func (uf *UnionFind) CcNum() int {
	res := 0
	for i := 0; i < len(uf.parents); i++ {
		if uf.parents[i] < 0 {
			res++
		}
	}
	return res
}

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

/*********** 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"
	"io"
	"os"
)

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

	var t, n, k int
	var s []byte
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &k, &s)
		ans := 0
		for i := 0; i < k/2; i++ {
			cnt := [26]int{}
			for j := i; j < n; j += k {
				cnt[s[j]-'a']++
			}
			for j := k - 1 - i; j < n; j += k {
				cnt[s[j]-'a']++
			}
			max := 0
			for _, c := range cnt {
				if c > max {
					max = c
				}
			}
			ans += 2*n/k - max
		}
		if k&1 == 1 {
			cnt := [26]int{}
			for j := k / 2; j < n; j += k {
				cnt[s[j]-'a']++
			}
			max := 0
			for _, c := range cnt {
				if c > max {
					max = c
				}
			}
			ans += n/k - max
		}
		Fprintln(out, ans)
	}
}

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

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
    // adjust the following cap as needed
    // 2 << 17 is good enough to scan strings of len 2*10^5
    // cap could go as high as 2 << 26 before cf judge breaks
    maxCap := 2 << 20
    buf := make([]byte, maxCap)
    s.Buffer(buf, maxCap)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		_, k := reader.NextInt64(), reader.NextInt64()
		s := reader.NextString()
		writer.Printf("%d\n", sol(k, s))
	}
}

func sol(k int64, s string) int64 {
	chunks := []string{}
	for i := k; i <= int64(len(s)); i += k {
		chunks = append(chunks, s[i-k:i])
	}
	var l, r int64
	if k%2 == 1 {
		l, r = k/2, k/2
	} else {
		l, r = k/2-1, k/2
	}

	ret := int64(0)

	// middle element
	if k%2 == 1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
		}
		ret += int64(len(chunks)) - max(chars)
		l--
		r++
	}

	// remaining elements
	for l >= 0 && r <= k-1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
			chars[chunk[r]]++
		}
		ret += int64(len(chunks))*2 - max(chars)
		l--
		r++
	}

	return ret
}

func max(m map[byte]int64) int64 {
	maxSoFar := int64(0)
	for _, v := range m {
		if v > maxSoFar {
			maxSoFar = v
		}
	}
	return maxSoFar
}

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	maxCap := 2 << 20
	buf := make([]byte, maxCap)
	s.Buffer(buf, maxCap)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		_, k := reader.NextInt64(), reader.NextInt64()
		s := reader.NextString()
		writer.Printf("%d\n", sol(k, s))
	}
}

func sol(k int64, s string) int64 {
	chunks := []string{}
	for i := k; i <= int64(len(s)); i += k {
		chunks = append(chunks, s[i-k:i])
	}
	var l, r int64
	if k%2 == 1 {
		l, r = k/2, k/2
	} else {
		l, r = k/2-1, k/2
	}

	ret := int64(0)

	// middle element
	if k%2 == 1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
		}
		ret += int64(len(chunks)) - max(chars)
		l--
		r++
	}

	// remaining elements
	for l >= 0 && r <= k-1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
			chars[chunk[r]]++
		}
		ret += int64(len(chunks))*2 - max(chars)
		l--
		r++
	}

	return ret
}

func max(m map[byte]int64) int64 {
	maxSoFar := int64(0)
	for _, v := range m {
		if v > maxSoFar {
			maxSoFar = v
		}
	}
	return maxSoFar
}

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	maxCap := 2 << 17
	buf := make([]byte, maxCap)
	s.Buffer(buf, maxCap)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		_, k := reader.NextInt64(), reader.NextInt64()
		s := reader.NextString()
		writer.Printf("%d\n", sol(k, s))
	}
}

func sol(k int64, s string) int64 {
	chunks := []string{}
	for i := k; i <= int64(len(s)); i += k {
		chunks = append(chunks, s[i-k:i])
	}
	var l, r int64
	if k%2 == 1 {
		l, r = k/2, k/2
	} else {
		l, r = k/2-1, k/2
	}

	ret := int64(0)

	// middle element
	if k%2 == 1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
		}
		ret += int64(len(chunks)) - max(chars)
		l--
		r++
	}

	// remaining elements
	for l >= 0 && r <= k-1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
			chars[chunk[r]]++
		}
		ret += int64(len(chunks))*2 - max(chars)
		l--
		r++
	}

	return ret
}

func max(m map[byte]int64) int64 {
	maxSoFar := int64(0)
	for _, v := range m {
		if v > maxSoFar {
			maxSoFar = v
		}
	}
	return maxSoFar
}

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

const MAX_CAPACITY = 2 << 26

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	buf := make([]byte, MAX_CAPACITY)
	s.Buffer(buf, MAX_CAPACITY)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		_, k := reader.NextInt64(), reader.NextInt64()
		s := reader.NextString()
		writer.Printf("%d\n", sol(k, s))
	}
}

func sol(k int64, s string) int64 {
	chunks := []string{}
	for i := k; i <= int64(len(s)); i += k {
		chunks = append(chunks, s[i-k:i])
	}
	var l, r int64
	if k%2 == 1 {
		l, r = k/2, k/2
	} else {
		l, r = k/2-1, k/2
	}

	ret := int64(0)

	// middle element
	if k%2 == 1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
		}
		ret += int64(len(chunks)) - max(chars)
		l--
		r++
	}

	// remaining elements
	for l >= 0 && r <= k-1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
			chars[chunk[r]]++
		}
		ret += int64(len(chunks))*2 - max(chars)
		l--
		r++
	}

	return ret
}

func max(m map[byte]int64) int64 {
	maxSoFar := int64(0)
	for _, v := range m {
		if v > maxSoFar {
			maxSoFar = v
		}
	}
	return maxSoFar
}

package main

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

var lineDelim = byte('\r')
var reader *bufio.Reader = bufio.NewReader(os.Stdin)

func ReadInts() []int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    numbersRaw := strings.Split(str, " ")
    var numbers []int
    for _, i := range numbersRaw {
        n, _ := strconv.Atoi(i)
        numbers = append(numbers, int(n))
    }

    return numbers
}

func ReadInt() int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    n, _ := strconv.Atoi(str)

    return int(n)
}

func ReadString() string {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]

    return str
}

func IsRuneSetPalindrome(a []rune, len int) (isPalindrome bool, incorrectIndexes []int) {
	if len == 0 {
		return
	}
	isPalindrome = true
	if len == 1 {
		return
	}
	middle := len / 2
	for i := 0; i < middle; i++ {
		lastPos := len - 1 - i
		if a[i] != a[lastPos] {
			isPalindrome = false
			incorrectIndexes = append(incorrectIndexes, lastPos)
		}
	}

	return
}

func IsKPeriodicRuneSet(w []rune, len , k int) (isKPeriodic bool, incorrectIndexes []int) {
	if !(len % k == 0) {
		return
	}
	middle := len / 2
	if (len % 2 != 0) {
		middle += 1
	}
	isKPeriodic = true
	for i := 0; i < middle; i++ {
		period := i + k
		if !(w[i] == w[period]) {
			isKPeriodic = false
			incorrectIndexes = append(incorrectIndexes, period)
		}
	}

	return
}

func RuneSetFrequencyArray(w []rune, len int, lowerLimit int, upperLimit int) []int {
	n := upperLimit - lowerLimit
	frequencyArray := make([]int, n)
	if len == 0 {
		return frequencyArray
	}
	for i := 0; i < len; i++ {
		index := int(w[i]) - lowerLimit
		frequencyArray[index] += 1
	}

	return frequencyArray
}

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

	return max
}

func main() {
	nTestCases := ReadInt()
	fmt.Printf("nTestCases: %#v", nTestCases)
	for nTestCases != 0 {
		input := ReadInts()
		fmt.Printf("input: %#v", input)
		str := ReadString()
		fmt.Printf("str: %#v", str)
		n := input[0]
		fmt.Printf("n: %#v", n)
		k := input[1]
		fmt.Printf("k: %#v", k)
		r := []rune(str)
		isPalindrome, pIncorrectPos := IsRuneSetPalindrome(r, n)
		isKPeriodicRuneSet, kIncorrectPos := IsKPeriodicRuneSet(r, n, k)
		if isPalindrome && isKPeriodicRuneSet {
			fmt.Println(0)
		} else if isPalindrome && !isKPeriodicRuneSet {
			fmt.Println(len(kIncorrectPos))
		} else {
			runeSetFrequencyArray := RuneSetFrequencyArray(r, n, 97, 122)
			lenFA := len(runeSetFrequencyArray)
			mostFrequentRunePos := GetMaxInt(runeSetFrequencyArray, lenFA)
			min := n - mostFrequentRunePos
			nP := len(pIncorrectPos)
			if nP % 2 != 0 {
				min += 1
			}
			fmt.Println(min)
		}
		nTestCases -= 1
	}
}

package main

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

var lineDelim = byte('\r')
var reader *bufio.Reader = bufio.NewReader(os.Stdin)

// func ReadInts() []int {
//     str, _ := reader.ReadString(lineDelim)
//     str = str[:len(str)-1]
//     numbersRaw := strings.Split(str, " ")
//     var numbers []int
//     for _, i := range numbersRaw {
//         n, _ := strconv.Atoi(i)
//         numbers = append(numbers, int(n))
//     }

//     return numbers
// }
func ReadIntsAndTrim() []int {
	str, _ := reader.ReadString(lineDelim)
	str = strings.TrimSpace(str)
    numbersRaw := strings.Split(str, " ")
    var numbers []int
    for _, i := range numbersRaw {
        n, _ := strconv.ParseInt(i, 10, 0)
        numbers = append(numbers, int(n))
    }

    return numbers
}

func ReadInt() int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    n, _ := strconv.Atoi(str)

    return int(n)
}

// func ReadString() string {
//     str, _ := reader.ReadString(lineDelim)
//     str = str[:len(str)-1]

//     return str
// }
func ReadStringAndTrim() string {
	str, _ := reader.ReadString(lineDelim)
	str = strings.TrimSpace(str)

	return str
}

func IsRuneSetPalindrome(a []rune, len int) (isPalindrome bool, incorrectIndexes []int) {
	if len == 0 {
		return
	}
	isPalindrome = true
	if len == 1 {
		return
	}
	middle := len / 2
	for i := 0; i < middle; i++ {
		lastPos := len - 1 - i
		if a[i] != a[lastPos] {
			isPalindrome = false
			incorrectIndexes = append(incorrectIndexes, lastPos)
		}
	}

	return
}

func IsKPeriodicRuneSet(w []rune, len , k int) (isKPeriodic bool, incorrectIndexes []int) {
	if !(len % k == 0) {
		return
	}
	middle := len / 2
	if (len % 2 != 0) {
		middle += 1
	}
	isKPeriodic = true
	for i := 0; i < middle; i++ {
		period := i + k
		if !(w[i] == w[period]) {
			isKPeriodic = false
			incorrectIndexes = append(incorrectIndexes, period)
		}
	}

	return
}

func RuneSetFrequencyArray(w []rune, len int, lowerLimit int, upperLimit int) []int {
	n := upperLimit - lowerLimit
	frequencyArray := make([]int, n)
	if len == 0 {
		return frequencyArray
	}
	for i := 0; i < len; i++ {
		index := int(w[i]) - lowerLimit
		frequencyArray[index] += 1
	}

	return frequencyArray
}

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

	return max
}

func main() {
	nTestCases := ReadInt()
	fmt.Printf("nTestCases: %#v\n", nTestCases)
	for nTestCases != 0 {
		input := ReadIntsAndTrim()
		fmt.Printf("input: %#v\n", input)
		str := ReadStringAndTrim()
		fmt.Printf("str: %#v\n", str)
		n := input[0]
		fmt.Printf("n: %#v\n", n)
		k := input[1]
		fmt.Printf("k: %#v\n", k)
		r := []rune(str)
		isPalindrome, pIncorrectPos := IsRuneSetPalindrome(r, n)
		isKPeriodicRuneSet, kIncorrectPos := IsKPeriodicRuneSet(r, n, k)
		if isPalindrome && isKPeriodicRuneSet {
			fmt.Println(0)
		} else if isPalindrome && !isKPeriodicRuneSet {
			fmt.Println(len(kIncorrectPos))
		} else {
			runeSetFrequencyArray := RuneSetFrequencyArray(r, n, 97, 122)
			lenFA := len(runeSetFrequencyArray)
			mostFrequentRunePos := GetMaxInt(runeSetFrequencyArray, lenFA)
			min := n - mostFrequentRunePos
			nP := len(pIncorrectPos)
			if nP % 2 != 0 {
				min += 1
			}
			fmt.Println(min)
		}
		nTestCases -= 1
	}
}

package main

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

var lineDelim = byte('\r')
var reader *bufio.Reader = bufio.NewReader(os.Stdin)

func ReadInts() []int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    numbersRaw := strings.Split(str, " ")
    var numbers []int
    for _, i := range numbersRaw {
        n, _ := strconv.Atoi(i)
        numbers = append(numbers, int(n))
    }

    return numbers
}

func ReadInt() int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    n, _ := strconv.Atoi(str)

    return int(n)
}

func ReadString() string {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]

    return str
}

func IsRuneSetPalindrome(a []rune, len int) (isPalindrome bool, incorrectIndexes []int) {
	if len == 0 {
		return
	}
	isPalindrome = true
	if len == 1 {
		return
	}
	middle := len / 2
	for i := 0; i < middle; i++ {
		lastPos := len - 1 - i
		if a[i] != a[lastPos] {
			isPalindrome = false
			incorrectIndexes = append(incorrectIndexes, lastPos)
		}
	}

	return
}

func IsKPeriodicRuneSet(w []rune, len , k int) (isKPeriodic bool, incorrectIndexes []int) {
	if !(len % k == 0) {
		return
	}
	middle := len / 2
	if (len % 2 != 0) {
		middle += 1
	}
	isKPeriodic = true
	for i := 0; i < middle; i++ {
		period := i + k
		if !(w[i] == w[period]) {
			isKPeriodic = false
			incorrectIndexes = append(incorrectIndexes, period)
		}
	}

	return
}

func RuneSetFrequencyArray(w []rune, len int, lowerLimit int, upperLimit int) []int {
	n := upperLimit - lowerLimit
	frequencyArray := make([]int, n)
	if len == 0 {
		return frequencyArray
	}
	for i := 0; i < len; i++ {
		index := int(w[i]) - lowerLimit
		frequencyArray[index] += 1
	}

	return frequencyArray
}

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

	return max
}

func main() {
	nTestCases := ReadInt()
	for nTestCases != 0 {
		input := ReadInts()
		n := input[0]
		k := input[1]
		str := ReadString()
		r := []rune(str)
		isPalindrome, pIncorrectPos := IsRuneSetPalindrome(r, n)
		isKPeriodicRuneSet, kIncorrectPos := IsKPeriodicRuneSet(r, n, k)
		if isPalindrome && isKPeriodicRuneSet {
			fmt.Println(0)
		} else if isPalindrome && !isKPeriodicRuneSet {
			fmt.Println(len(kIncorrectPos))
		} else if !isPalindrome && !isKPeriodicRuneSet {
			runeSetFrequencyArray := RuneSetFrequencyArray(r, n, 97, 122)
			lenFA := len(runeSetFrequencyArray)
			mostFrequentRunePos := GetMaxInt(runeSetFrequencyArray, lenFA)
			var min int
			nP := len(pIncorrectPos)
			if nP % 2 == 0 {
				min = n - mostFrequentRunePos
			} else {
				min = n - mostFrequentRunePos + 1
			}
			fmt.Println(min)
		}
		nTestCases -= 1
	}
}

package main

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

var lineDelim = byte('\r')
var reader *bufio.Reader = bufio.NewReader(os.Stdin)

func ReadInts() []int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    numbersRaw := strings.Split(str, " ")
    var numbers []int
    for _, i := range numbersRaw {
        n, _ := strconv.Atoi(i)
        numbers = append(numbers, int(n))
    }

    return numbers
}

func ReadInt() int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    n, _ := strconv.Atoi(str)

    return int(n)
}

func ReadString() string {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]

    return str
}

func IsRuneSetPalindrome(a []rune, len int) (isPalindrome bool, incorrectIndexes []int) {
	if len == 0 {
		return
	}
	isPalindrome = true
	if len == 1 {
		return
	}
	middle := len / 2
	for i := 0; i < middle; i++ {
		lastPos := len - 1 - i
		if a[i] != a[lastPos] {
			isPalindrome = false
			incorrectIndexes = append(incorrectIndexes, lastPos)
		}
	}

	return
}

func IsKPeriodicRuneSet(w []rune, len , k int) (isKPeriodic bool, incorrectIndexes []int) {
	if !(len % k == 0) {
		return
	}
	middle := len / 2
	if (len % 2 != 0) {
		middle += 1
	}
	isKPeriodic = true
	for i := 0; i < middle; i++ {
		period := i + k
		if !(w[i] == w[period]) {
			isKPeriodic = false
			incorrectIndexes = append(incorrectIndexes, period)
		}
	}

	return
}

func RuneSetFrequencyArray(w []rune, len int, lowerLimit int, upperLimit int) []int {
	n := upperLimit - lowerLimit
	frequencyArray := make([]int, n)
	if len == 0 {
		return frequencyArray
	}
	for i := 0; i < len; i++ {
		index := int(w[i]) - lowerLimit
		frequencyArray[index] += 1
	}

	return frequencyArray
}

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

	return max
}

func main() {
	nTestCases := ReadInt()
	for nTestCases != 0 {
		input := ReadInts()
		n := input[0]
		k := input[1]
		str := ReadString()
		r := []rune(str)
		isPalindrome, pIncorrectPos := IsRuneSetPalindrome(r, n)
		isKPeriodicRuneSet, kIncorrectPos := IsKPeriodicRuneSet(r, n, k)
		if isPalindrome && isKPeriodicRuneSet {
			fmt.Println(0)
		} else if isPalindrome && !isKPeriodicRuneSet {
			fmt.Println(len(kIncorrectPos))
		} else {
			runeSetFrequencyArray := RuneSetFrequencyArray(r, n, 97, 122)
			lenFA := len(runeSetFrequencyArray)
			mostFrequentRunePos := GetMaxInt(runeSetFrequencyArray, lenFA)
			var min int
			nP := len(pIncorrectPos)
			if nP % 2 == 0 {
				min = n - mostFrequentRunePos
			} else {
				min = n - mostFrequentRunePos + 1
			}
			fmt.Println(min)
		}
		nTestCases -= 1
	}
}

package main

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

var lineDelim = byte('\r')
var reader *bufio.Reader = bufio.NewReader(os.Stdin)

func ReadIntsAndTrim() []int {
	str, _ := reader.ReadString(lineDelim)
	str = strings.TrimSpace(str)
    numbersRaw := strings.Split(str, " ")
    var numbers []int
    for _, i := range numbersRaw {
        n, _ := strconv.ParseInt(i, 10, 0)
        numbers = append(numbers, int(n))
    }

    return numbers
}

func ReadInt() int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    n, _ := strconv.Atoi(str)

    return int(n)
}

func ReadStringAndTrim() string {
	str, _ := reader.ReadString(lineDelim)
	str = strings.TrimSpace(str)

	return str
}

func IsRuneSetPalindrome(a []rune, len int) (isPalindrome bool, incorrectIndexes []int) {
	if len == 0 {
		return
	}
	isPalindrome = true
	if len == 1 {
		return
	}
	middle := len / 2
	for i := 0; i < middle; i++ {
		lastPos := len - 1 - i
		if a[i] != a[lastPos] {
			isPalindrome = false
			incorrectIndexes = append(incorrectIndexes, lastPos)
		}
	}

	return
}

func IsKPeriodicRuneSet(w []rune, len , k int) (isKPeriodic bool, incorrectIndexes []int) {
	if !(len % k == 0) {
		return
	}
	middle := len / 2
	if (len % 2 != 0) {
		middle += 1
	}
	isKPeriodic = true
	for i := 0; i < middle; i++ {
		period := i + k
		if !(w[i] == w[period]) {
			isKPeriodic = false
			incorrectIndexes = append(incorrectIndexes, period)
		}
	}

	return
}

func RuneSetFrequencyArray(w []rune, len int, lowerLimit int, upperLimit int) []int {
	n := upperLimit - lowerLimit
	frequencyArray := make([]int, n)
	if len == 0 {
		return frequencyArray
	}
	for i := 0; i < len; i++ {
		index := int(w[i]) - lowerLimit
		frequencyArray[index] += 1
	}

	return frequencyArray
}

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

	return max
}

func main() {
	nTestCases := ReadInt()
	for nTestCases != 0 {
		input := ReadIntsAndTrim()
		str := ReadStringAndTrim()
		n := input[0]
		k := input[1]
		r := []rune(str)
		isPalindrome, pIncorrectPos := IsRuneSetPalindrome(r, n)
		isKPeriodicRuneSet, kIncorrectPos := IsKPeriodicRuneSet(r, n, k)
		if isPalindrome && isKPeriodicRuneSet {
			fmt.Println(0)
		} else if isPalindrome && !isKPeriodicRuneSet {
			fmt.Println(len(kIncorrectPos))
		} else {
			nP := len(pIncorrectPos)
			for i := 0; i < nP; i++ {
				pos := pIncorrectPos[i]
				r[pos] = r[n - pos - 1]
			}
			runeSetFrequencyArray := RuneSetFrequencyArray(r, n, 97, 122)
			lenFA := len(runeSetFrequencyArray)
			mostFrequentRuneCount := GetMaxInt(runeSetFrequencyArray, lenFA)
			min := n - mostFrequentRuneCount
			if n % 2 != 0 {
				min += 1
			}
			fmt.Println(min)
		}
		nTestCases -= 1
	}
}

package main

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

var lineDelim = byte('\r')
var reader *bufio.Reader = bufio.NewReader(os.Stdin)

func ReadInts() []int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    numbersRaw := strings.Split(str, " ")
    var numbers []int
    for _, i := range numbersRaw {
        n, _ := strconv.Atoi(i)
        numbers = append(numbers, int(n))
    }

    return numbers
}

func ReadInt() int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    n, _ := strconv.Atoi(str)

    return int(n)
}

func ReadString() string {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]

    return str
}

func IsRuneSetPalindrome(a []rune, len int) (isPalindrome bool, incorrectIndexes []int) {
	if len == 0 {
		return
	}
	isPalindrome = true
	if len == 1 {
		return
	}
	middle := len / 2
	for i := 0; i < middle; i++ {
		lastPos := len - 1 - i
		if a[i] != a[lastPos] {
			isPalindrome = false
			incorrectIndexes = append(incorrectIndexes, lastPos)
		}
	}

	return
}

func IsKPeriodicRuneSet(w []rune, len , k int) (isKPeriodic bool, incorrectIndexes []int) {
	if !(len % k == 0) {
		return
	}
	middle := len / 2
	if (len % 2 != 0) {
		middle += 1
	}
	isKPeriodic = true
	for i := 0; i < middle; i++ {
		period := i + k
		if !(w[i] == w[period]) {
			isKPeriodic = false
			incorrectIndexes = append(incorrectIndexes, period)
		}
	}

	return
}

func RuneSetFrequencyArray(w []rune, len int, lowerLimit int, upperLimit int) []int {
	n := upperLimit - lowerLimit
	frequencyArray := make([]int, n)
	if len == 0 {
		return frequencyArray
	}
	for i := 0; i < len; i++ {
		index := int(w[i]) - lowerLimit
		frequencyArray[index] += 1
	}

	return frequencyArray
}

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

	return max
}

func main() {
	nTestCases := ReadInt()
	for nTestCases != 0 {
		input := ReadInts()
		str := ReadString()
		n := input[0]
		k := input[1]
		r := []rune(str)
		isPalindrome, pIncorrectPos := IsRuneSetPalindrome(r, n)
		isKPeriodicRuneSet, kIncorrectPos := IsKPeriodicRuneSet(r, n, k)
		if isPalindrome && isKPeriodicRuneSet {
			fmt.Println(0)
		} else if isPalindrome && !isKPeriodicRuneSet {
			fmt.Println(len(kIncorrectPos))
		} else {
			runeSetFrequencyArray := RuneSetFrequencyArray(r, n, 97, 122)
			lenFA := len(runeSetFrequencyArray)
			mostFrequentRunePos := GetMaxInt(runeSetFrequencyArray, lenFA)
			var min int
			nP := len(pIncorrectPos)
			if nP % 2 == 0 {
				min = n - mostFrequentRunePos
			} else {
				min = n - mostFrequentRunePos + 1
			}
			fmt.Println(min)
		}
		nTestCases -= 1
	}
}

package main

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

var lineDelim = byte('\r')
var reader *bufio.Reader = bufio.NewReader(os.Stdin)

func ReadInts() []int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    numbersRaw := strings.Split(str, " ")
    var numbers []int
    for _, i := range numbersRaw {
        n, _ := strconv.Atoi(i)
        numbers = append(numbers, int(n))
    }

    return numbers
}

func ReadInt() int {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]
    n, _ := strconv.Atoi(str)

    return int(n)
}

func ReadString() string {
    str, _ := reader.ReadString(lineDelim)
    str = str[:len(str)-1]

    return str
}

func IsRuneSetPalindrome(a []rune, len int) (isPalindrome bool, incorrectIndexes []int) {
	if len == 0 {
		return
	}
	isPalindrome = true
	if len == 1 {
		return
	}
	middle := len / 2
	for i := 0; i < middle; i++ {
		lastPos := len - 1 - i
		if a[i] != a[lastPos] {
			isPalindrome = false
			incorrectIndexes = append(incorrectIndexes, lastPos)
		}
	}

	return
}

func IsKPeriodicRuneSet(w []rune, len , k int) (isKPeriodic bool, incorrectIndexes []int) {
	if !(len % k == 0) {
		return
	}
	middle := len / 2
	if (len % 2 != 0) {
		middle += 1
	}
	isKPeriodic = true
	for i := 0; i < middle; i++ {
		period := i + k
		if !(w[i] == w[period]) {
			isKPeriodic = false
			incorrectIndexes = append(incorrectIndexes, period)
		}
	}

	return
}

func RuneSetFrequencyArray(w []rune, len int, lowerLimit int, upperLimit int) []int {
	n := upperLimit - lowerLimit
	frequencyArray := make([]int, n)
	if len == 0 {
		return frequencyArray
	}
	for i := 0; i < len; i++ {
		index := int(w[i]) - lowerLimit
		frequencyArray[index] += 1
	}

	return frequencyArray
}

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

	return max
}

func main() {
	nTestCases := ReadInt()
	fmt.Printf("nTestCases: %#v\n", nTestCases)
	for nTestCases != 0 {
		input := ReadInts()
		fmt.Printf("input: %#v\n", input)
		str := ReadString()
		fmt.Printf("str: %#v\n", str)
		n := input[0]
		fmt.Printf("n: %#v\n", n)
		k := input[1]
		fmt.Printf("k: %#v\n", k)
		r := []rune(str)
		isPalindrome, pIncorrectPos := IsRuneSetPalindrome(r, n)
		isKPeriodicRuneSet, kIncorrectPos := IsKPeriodicRuneSet(r, n, k)
		if isPalindrome && isKPeriodicRuneSet {
			fmt.Println(0)
		} else if isPalindrome && !isKPeriodicRuneSet {
			fmt.Println(len(kIncorrectPos))
		} else {
			runeSetFrequencyArray := RuneSetFrequencyArray(r, n, 97, 122)
			lenFA := len(runeSetFrequencyArray)
			mostFrequentRunePos := GetMaxInt(runeSetFrequencyArray, lenFA)
			min := n - mostFrequentRunePos
			nP := len(pIncorrectPos)
			if nP % 2 != 0 {
				min += 1
			}
			fmt.Println(min)
		}
		nTestCases -= 1
	}
}

package main

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

type BufferedWriter interface {
    Printf(format string, a ...interface{})
    Flush()
}

type writerImpl struct {
    *bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
    return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
    fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
    impl.Writer.Flush()
}

type WordScanner interface {
    NextInt() int
    NextInt64() int64
    NextString() string
}

type wordScannerImpl struct {
    *bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
    s := bufio.NewScanner(reader)
    s.Split(bufio.ScanWords)
    return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
    impl.Scan()
    return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
    defer writer.Flush()
    t := reader.NextInt64()
    for ; t > 0; t-- {
        _, k := reader.NextInt64(), reader.NextInt64()
        s := reader.NextString()
        writer.Printf("%d\n", sol(k, s))
    }
}

func sol(k int64, s string) int64 {
    chunks := []string{}
    for i := k; i <= int64(len(s)); i += k {
        chunks = append(chunks, s[i-k:i])
    }
    var l, r int64
    if k % 2 == 1 {
        l, r = k/2, k/2
    } else {
        l, r = k/2 -1, k/2
    }

    ret := int64(0)

    // middle element
    if k % 2 == 1 {
        chars := map[byte]int64{}
        for _, chunk := range chunks {
            chars[chunk[l]]++
        }
        ret += int64(len(chunks)) - max(chars)
        l--
        r++
    }

    // remaining elements
    for l >= 0 && r <= k-1 {
        chars := map[byte]int64{}
        for _, chunk := range chunks {
            chars[chunk[l]]++
            chars[chunk[r]]++
        }
        ret += int64(len(chunks))*2 - max(chars)
        l--
        r++
    }

    return ret
}

func max(m map[byte]int64) int64 {
    maxSoFar := int64(0)
    for _, v := range m {
        if v > maxSoFar {
            maxSoFar = v
        }
    }
    return maxSoFar
}

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	maxCap := 2 << 15
	buf := make([]byte, maxCap)
	s.Buffer(buf, maxCap)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		_, k := reader.NextInt64(), reader.NextInt64()
		s := reader.NextString()
		writer.Printf("%d\n", sol(k, s))
	}
}

func sol(k int64, s string) int64 {
	chunks := []string{}
	for i := k; i <= int64(len(s)); i += k {
		chunks = append(chunks, s[i-k:i])
	}
	var l, r int64
	if k%2 == 1 {
		l, r = k/2, k/2
	} else {
		l, r = k/2-1, k/2
	}

	ret := int64(0)

	// middle element
	if k%2 == 1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
		}
		ret += int64(len(chunks)) - max(chars)
		l--
		r++
	}

	// remaining elements
	for l >= 0 && r <= k-1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
			chars[chunk[r]]++
		}
		ret += int64(len(chunks))*2 - max(chars)
		l--
		r++
	}

	return ret
}

func max(m map[byte]int64) int64 {
	maxSoFar := int64(0)
	for _, v := range m {
		if v > maxSoFar {
			maxSoFar = v
		}
	}
	return maxSoFar
}

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	maxCap := 2 << 16
	buf := make([]byte, maxCap)
	s.Buffer(buf, maxCap)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		_, k := reader.NextInt64(), reader.NextInt64()
		s := reader.NextString()
		writer.Printf("%d\n", sol(k, s))
	}
}

func sol(k int64, s string) int64 {
	chunks := []string{}
	for i := k; i <= int64(len(s)); i += k {
		chunks = append(chunks, s[i-k:i])
	}
	var l, r int64
	if k%2 == 1 {
		l, r = k/2, k/2
	} else {
		l, r = k/2-1, k/2
	}

	ret := int64(0)

	// middle element
	if k%2 == 1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
		}
		ret += int64(len(chunks)) - max(chars)
		l--
		r++
	}

	// remaining elements
	for l >= 0 && r <= k-1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
			chars[chunk[r]]++
		}
		ret += int64(len(chunks))*2 - max(chars)
		l--
		r++
	}

	return ret
}

func max(m map[byte]int64) int64 {
	maxSoFar := int64(0)
	for _, v := range m {
		if v > maxSoFar {
			maxSoFar = v
		}
	}
	return maxSoFar
}

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	maxCap := 2 << 10
	buf := make([]byte, maxCap)
	s.Buffer(buf, maxCap)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		_, k := reader.NextInt64(), reader.NextInt64()
		s := reader.NextString()
		writer.Printf("%d\n", sol(k, s))
	}
}

func sol(k int64, s string) int64 {
	chunks := []string{}
	for i := k; i <= int64(len(s)); i += k {
		chunks = append(chunks, s[i-k:i])
	}
	var l, r int64
	if k%2 == 1 {
		l, r = k/2, k/2
	} else {
		l, r = k/2-1, k/2
	}

	ret := int64(0)

	// middle element
	if k%2 == 1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
		}
		ret += int64(len(chunks)) - max(chars)
		l--
		r++
	}

	// remaining elements
	for l >= 0 && r <= k-1 {
		chars := map[byte]int64{}
		for _, chunk := range chunks {
			chars[chunk[l]]++
			chars[chunk[r]]++
		}
		ret += int64(len(chunks))*2 - max(chars)
		l--
		r++
	}

	return ret
}

func max(m map[byte]int64) int64 {
	maxSoFar := int64(0)
	for _, v := range m {
		if v > maxSoFar {
			maxSoFar = v
		}
	}
	return maxSoFar
}


package main

import (
	"fmt"
	"container/list"
	"bufio"
	"os"
	"strings"
	"strconv"
)

var n int
var weight []int64
var head []*list.List

type Edge struct{
	Value int64
	to int
}
func dfs(u int, mx int64, par int) int{
	if  mx > weight[u] {
		return 0
	}
	if mx < 0 {
		mx = 0
	}
	ret := 1
	for e := head[u].Front(); e != nil; e= e.Next() {
		edge, _ := e.Value.(*Edge)
		if edge.to != par {
			ret += dfs(edge.to, mx + edge.Value, u)
		}
	}
	return ret
}
func main() {
	fmt.Scanf("%d\n", &n)
	weight = make([]int64, n)
	head = make([]*list.List, n)
	reader := bufio.NewReaderSize(os.Stdin, 10000000)
	byte, _, _ := reader.ReadLine()
	strs := strings.Split(string(byte), " ")
	for i:=0; i < n; i++ {
		weight[i], _ = strconv.ParseInt(strs[i], 10, 64)
		head[i] = &list.List{}
	}

	for i:=1; i < n; i++ {
		byte, _, _ = reader.ReadLine()
		strs = strings.Split(string(byte), " ")
		to, _ := strconv.Atoi(strs[0])
		value, _ := strconv.ParseInt(strs[1], 10, 64)
		e := &Edge{Value: value, to: to-1}
		ve := &Edge{Value: value, to: i}
		head[i].PushBack(e)
		head[to - 1].PushBack(ve)
	}
	fmt.Println(n - dfs(0, 0, 0))
}

package main

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

var n int
var weight []int64
var head [][]*Edge

type Edge struct{
	Value int64
	to int
}
func dfs(u int, mx int64, par int) int{
	if  mx > weight[u] {
		return 0
	}
	if mx < 0 {
		mx = 0
	}
	ret := 1
	for _, edge := range head[u] {
		if edge.to != par {
			ret += dfs(edge.to, mx + edge.Value, u)
		}
	}
	return ret
}
func main() {
	fmt.Scanf("%d\n", &n)
	weight = make([]int64, n)
	head = make([][]*Edge, n)
	reader := bufio.NewReaderSize(os.Stdin, 10000000)
	byte, _, _ := reader.ReadLine()
	strs := strings.Split(string(byte), " ")
	for i:=0; i < n; i++ {
		weight[i], _ = strconv.ParseInt(strs[i], 10, 64)
	}

	for i:=1; i < n; i++ {
		byte, _, _ = reader.ReadLine()
		strs = strings.Split(string(byte), " ")
		to, _ := strconv.Atoi(strs[0])
		value, _ := strconv.ParseInt(strs[1], 10, 64)
		e := &Edge{Value: value, to: to-1}
		ve := &Edge{Value: value, to: i}
		head[i] = append(head[i], e)
		head[to - 1] = append(head[to - 1], ve)
	}
	fmt.Println(n - dfs(0, 0, 0))
}

package main

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

func main() {
	n := getInt()
	A := getNint(n)

	C := make([]int, n+1)
	G := make([][]int, n+1)
	for i := 2; i <= n; i++ {
		p, c := getInt(), getInt()
		C[i] = c
		G[i] = append(G[i], p)
		G[p] = append(G[p], i)
	}

	V := make([]bool, n+1) // vis?
	P := make([]bool, n+1) // pruned?
	q := make([]int, 1, n)
	D := make([]int64, n+1) // dist
	q[0] = 1
	var ans int
	for i := 0; i < len(q); i++ {
		v := q[i]
		V[v] = true
		for _, u := range G[v] {
			if V[u] {
				continue
			}
			V[u] = true
			q = append(q, u)
			D[u] = D[v] + int64(C[u])
			remax64(&D[u], 0)
			P[u] = P[v] || D[u] > int64(A[u-1])
			if P[u] {
				ans++
			}
		}
	}
	fmt.Println(ans)
}

type Input struct {
	*bufio.Scanner
}

var globalInput = wrapStdin()

func wrapStdin() Input {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	return Input{Scanner: sc}
}
func getInt() int {
	globalInput.Scan()
	x, _ := strconv.Atoi(globalInput.Text())
	return x
}
func getIntOk() (int, bool) {
	ok := globalInput.Scan()
	x, _ := strconv.Atoi(globalInput.Text())
	return x, ok
}
func getNint(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		v[i] = getInt()
	}
	return v
}
func getVint(v []int) bool {
	var ok bool
	for i := 0; i < len(v); i++ {
		v[i], ok = getIntOk()
	}
	return ok
}
func getWord() string {
	globalInput.Scan()
	return globalInput.Text()
}
func getWordOk() (string, bool) {
	ok := globalInput.Scan()
	return globalInput.Text(), ok
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}
func min64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func max64(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func minStr(a, b string) string {
	if a < b {
		return a
	}
	return b
}
func maxStr(a, b string) string {
	if a < b {
		return b
	}
	return a
}
func remin(a *int, b int) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remax(a *int, b int) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}
func remin64(a *int64, b int64) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remax64(a *int64, b int64) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}
func reminStr(a *string, b string) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remaxStr(a *string, b string) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func abs64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

type (
	FLess    func(i, j int) bool
	FSwap    func(i, j int)
	wrapSort struct {
		Length int
		FLess
		FSwap
	}
)

func (w *wrapSort) Len() int           { return w.Length }
func (w *wrapSort) Less(i, j int) bool { return w.FLess(i, j) }
func (w *wrapSort) Swap(i, j int)      { w.FSwap(i, j) }
func wsort(length int, fless func(i, j int) bool, fswap func(i, j int)) {
	sort.Sort(&wrapSort{length, fless, fswap})
}

package main

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

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

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

type Vertex struct {
  Id int
  Limit int64
  Edges []*Edge
  Seen bool
}

type Edge struct {
  V *Vertex
  Cost int64
}

var (
  vertices []*Vertex
  deleted int
)

func visit(u *Vertex, pathCost int64) {
  u.Seen = true
  if pathCost > u.Limit {
    return
  }
  deleted--
  for _, edge := range u.Edges {
    v := edge.V
    if v.Seen {
      continue
    }
    nextPathCost := pathCost + edge.Cost
    if nextPathCost < 0 {
      nextPathCost = 0
    }
    visit(v, nextPathCost)
  }
}

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

  n := getI()
  vertices = make([]*Vertex, n + 1)
  for i := 1; i <= n; i++ {
    vertices[i] = &Vertex{ i, getI64(), []*Edge{}, false }
  }
  for u := 2; u <= n; u++ {
    v, cost := getI(), getI64()
    uPtr, vPtr := vertices[u], vertices[v]
    uPtr.Edges = append(uPtr.Edges, &Edge{ vPtr, cost })
    vPtr.Edges = append(vPtr.Edges, &Edge{ uPtr, cost })
  }

  deleted = n
  visit(vertices[1], 0)
  writer.WriteString(fmt.Sprintf("%d\n", deleted))
}

package main

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

func main() {
	n := getInt()
	A := getNint(n)

	C := make([]int, n+1)
	G := make([][]int, n+1)
	for i := 2; i <= n; i++ {
		p, c := getInt(), getInt()
		C[i] = c
		G[i] = append(G[i], p)
		G[p] = append(G[p], i)
	}

	V := make([]bool, n+1) // vis?
	P := make([]bool, n+1) // pruned?
	q := make([]int, 1, n)
	D := make([]int64, n+1) // dist
	q[0] = 1
	var ans int
	for i := 0; i < len(q); i++ {
		v := q[i]
		V[v] = true
		for _, u := range G[v] {
			if V[u] {
				continue
			}
			V[u] = true
			q = append(q, u)
			D[u] = D[v] + int64(C[u])
			P[u] = P[v] || D[u] > int64(A[u-1])
			if P[u] {
				ans++
			}
		}
	}
	fmt.Println(ans)
}

type Input struct {
	*bufio.Scanner
}

var globalInput = wrapStdin()

func wrapStdin() Input {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	return Input{Scanner: sc}
}
func getInt() int {
	globalInput.Scan()
	x, _ := strconv.Atoi(globalInput.Text())
	return x
}
func getIntOk() (int, bool) {
	ok := globalInput.Scan()
	x, _ := strconv.Atoi(globalInput.Text())
	return x, ok
}
func getNint(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		v[i] = getInt()
	}
	return v
}
func getVint(v []int) bool {
	var ok bool
	for i := 0; i < len(v); i++ {
		v[i], ok = getIntOk()
	}
	return ok
}
func getWord() string {
	globalInput.Scan()
	return globalInput.Text()
}
func getWordOk() (string, bool) {
	ok := globalInput.Scan()
	return globalInput.Text(), ok
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}
func min64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func max64(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func minStr(a, b string) string {
	if a < b {
		return a
	}
	return b
}
func maxStr(a, b string) string {
	if a < b {
		return b
	}
	return a
}
func remin(a *int, b int) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remax(a *int, b int) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}
func remin64(a *int64, b int64) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remax64(a *int64, b int64) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}
func reminStr(a *string, b string) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remaxStr(a *string, b string) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func abs64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

type (
	FLess    func(i, j int) bool
	FSwap    func(i, j int)
	wrapSort struct {
		Length int
		FLess
		FSwap
	}
)

func (w *wrapSort) Len() int           { return w.Length }
func (w *wrapSort) Less(i, j int) bool { return w.FLess(i, j) }
func (w *wrapSort) Swap(i, j int)      { w.FSwap(i, j) }
func wsort(length int, fless func(i, j int) bool, fswap func(i, j int)) {
	sort.Sort(&wrapSort{length, fless, fswap})
}