Monocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams.Monocarp has $$$n$$$ problems that none of his students have seen yet. The $$$i$$$-th problem has a topic $$$a_i$$$ (an integer from $$$1$$$ to $$$n$$$) and a difficulty $$$b_i$$$ (an integer from $$$1$$$ to $$$n$$$). All problems are different, that is, there are no two tasks that have the same topic and difficulty at the same time.Monocarp decided to select exactly $$$3$$$ problems from $$$n$$$ problems for the problemset. The problems should satisfy at least one of two conditions (possibly, both):  the topics of all three selected problems are different;  the difficulties of all three selected problems are different. Your task is to determine the number of ways to select three problems for the problemset.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 50000$$$) — the number of testcases. The first line of each testcase contains an integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of problems that Monocarp have. In the $$$i$$$-th of the following $$$n$$$ lines, there are two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the topic and the difficulty of the $$$i$$$-th problem. It is guaranteed that there are no two problems that have the same topic and difficulty at the same time. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

Print the number of ways to select three training problems that meet either of the requirements described in the statement.

NoteIn the first example, you can take the following sets of three problems:  problems $$$1$$$, $$$2$$$, $$$4$$$;  problems $$$1$$$, $$$3$$$, $$$4$$$;  problems $$$2$$$, $$$3$$$, $$$4$$$. Thus, the number of ways is equal to three.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for c:=1;c<=t;c++{
		var n int64
		fmt.Fscan(in,&n)
		a := make([]int,n+5)
		b := make([]int,n+5)
		mpt := map[int]int{}
		mpd := map[int]int{}
		sum := n*(n-1)*(n-2)/6
		var i int64
		for i=1;i<=n;i++{
			fmt.Fscan(in,&a[i],&b[i])
			mpt[a[i]]++
			mpd[b[i]]++
		}
		for i=1;i<=n;i++{
			sum -= int64(int64(mpt[a[i]]-1)*int64(mpd[b[i]]-1))
		}
		fmt.Fprintln(out,sum)
	}
}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

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

func MIN(x, y int64) int64 {
	if x > y {
		return y
	} else {
		return x
	}
}

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

func MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

func MAX(x, y int64) int64 {
	if x > y {
		return x
	} else {
		return y
	}
}

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}
}

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

func MODULE(x, y int) int {
	if x > y {
		return x - y
	} else {
		return y - x
	}
}

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

func Sum(n, m int) int {
	var ans int

	if n == 1 {
		return 0
	} else {
		for i := 2; i < n; i++ {
			ans = (ans + Sum(i, m)) % m
		}
		for j := 2; j < n+1; j++ {
			ans = (ans + Sum(n/j, m)) % m
		}
		return ans
	}
}

func ChangeStringToDate(x string) (t time.Time, err error) {
	t, err = time.Parse("2006-01-02", x)
	return
}

func DiffrenceBetweenTwoDates(first, second time.Time) int64 {
	date := first
	date2 := second
	k := date.Unix() - date2.Unix()
	return k
}

func Union(a, b []int) []int {
	m := make(map[int]bool)

	for _, item := range a {
		m[item] = true
	}

	for _, item := range b {
		if _, ok := m[item]; !ok {
			a = append(a, item)
		}
	}
	return a
}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

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

		type X struct {
			topic    int
			dificult int
		}

		ARR := make([]X, n)
		N := make([]int64, n+1)
		M := make([]int64, n+1)

		for i := 0; i < n; i++ {
			fmt.Fscan(input, &ARR[i].topic, &ARR[i].dificult)
			N[ARR[i].dificult]++
			M[ARR[i].topic]++
		}

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

		// Another := make([]int, 0)
		// begin := ARR[0].topic
		// count := 1
		// for i := 1; i < n; i++ {
		// 	if ARR[i].topic == begin {
		// 		count++
		// 	} else {
		// 		Another = append(Another, count)
		// 		count = 1
		// 		begin = ARR[i].topic
		// 	}
		// }
		var sum int64
		// if ARR[0].topic != ARR[n-1].topic {
		// 	for i := 0; i < n-1; i++ {
		// 		for j := i + 1; j < n; j++ {
		// 			if ARR[i].topic == ARR[j].topic {
		// 				sum += N[ARR[i].dificult] + N[ARR[j].dificult] - 2
		// 			} else {
		// 				break
		// 			}
		// 		}
		// 	}
		// }

		for i := 0; i < n; i++ {
			q := ARR[i].topic
			numberOfThatTopic := M[q]
			sum += (numberOfThatTopic - 1) * (N[ARR[i].dificult] - 1)
		}
		var anss int64

		anss = int64(n) * int64(n-1) * int64(n-2) / 6
		anss = anss - sum
		fmt.Println(anss)

	}

}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

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

func MIN(x, y int64) int64 {
	if x > y {
		return y
	} else {
		return x
	}
}

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

func MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

func MAX(x, y int64) int64 {
	if x > y {
		return x
	} else {
		return y
	}
}

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}
}

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

func MODULE(x, y int) int {
	if x > y {
		return x - y
	} else {
		return y - x
	}
}

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

func Sum(n, m int) int {
	var ans int

	if n == 1 {
		return 0
	} else {
		for i := 2; i < n; i++ {
			ans = (ans + Sum(i, m)) % m
		}
		for j := 2; j < n+1; j++ {
			ans = (ans + Sum(n/j, m)) % m
		}
		return ans
	}
}

func ChangeStringToDate(x string) (t time.Time, err error) {
	t, err = time.Parse("2006-01-02", x)
	return
}

func DiffrenceBetweenTwoDates(first, second time.Time) int64 {
	date := first
	date2 := second
	k := date.Unix() - date2.Unix()
	return k
}

func Union(a, b []int) []int {
	m := make(map[int]bool)

	for _, item := range a {
		m[item] = true
	}

	for _, item := range b {
		if _, ok := m[item]; !ok {
			a = append(a, item)
		}
	}
	return a
}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

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

		type X struct {
			topic    int
			dificult int
		}

		ARR := make([]X, n)
		N := make([]int64, n+1)
		M := make([]int64, n+1)

		for i := 0; i < n; i++ {
			fmt.Fscan(input, &ARR[i].topic, &ARR[i].dificult)
			N[ARR[i].dificult]++
			M[ARR[i].topic]++
		}

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

		// Another := make([]int, 0)
		// begin := ARR[0].topic
		// count := 1
		// for i := 1; i < n; i++ {
		// 	if ARR[i].topic == begin {
		// 		count++
		// 	} else {
		// 		Another = append(Another, count)
		// 		count = 1
		// 		begin = ARR[i].topic
		// 	}
		// }
		var sum int64
		// if ARR[0].topic != ARR[n-1].topic {
		// 	for i := 0; i < n-1; i++ {
		// 		for j := i + 1; j < n; j++ {
		// 			if ARR[i].topic == ARR[j].topic {
		// 				sum += N[ARR[i].dificult] + N[ARR[j].dificult] - 2
		// 			} else {
		// 				break
		// 			}
		// 		}
		// 	}
		// }

		for i := 0; i < n; i++ {
			q := ARR[i].topic
			numberOfThatTopic := M[q]
			sum += (numberOfThatTopic - 1) * (N[ARR[i].dificult] - 1)
		}
		var ans int64

		ans = int64(n) * int64(n-1) * int64(n-2) / 6
		ans = ans - sum
		fmt.Println(ans)

	}

}

package main

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

var n int

var pr [][2]int

var topic [][][2]int
var diff [][][2]int

var bit []map[int]int

const LOCAL = false

func main() {

	r := bufio.NewReader(os.Stdin)

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

	if LOCAL {
		rand.Seed(time.Now().UnixNano())

		for tt := 0 ; tt < t; tt++ {
			n = 10
			pr = make([][2]int, n)

			mm := make([][]bool, n + 1)

			for j := 0; j < n + 1; j++ {
				mm[j] = make([]bool, n + 1)
			}

			for i := 0; i < n; i++ {

				var top int
				var diff int

				for ;; {
					top = 1 + rand.Intn(n)
					diff = 1 + rand.Intn(n)

					if !mm[top][diff] {
						mm[top][diff] = true
						break
					}
				}

				pr[i][0] = top
				pr[i][1] = diff
			}

			a1 := solve(n)
			a2 := solve_stupid(n)

			if a1 != a2 {
				fmt.Println("ERROR")
				fmt.Println(a1)
				fmt.Println(a2)
				fmt.Println(pr)
				break
			}
		}

		return
	}

	for i := 0; i < t; i++ {
		fmt.Fscan(r, &n)

		pr = make([][2]int, n)

		for  j := 0; j < n; j++ {
			fmt.Fscan(r, &pr[j][0], &pr[j][1])
		}

		ans := solve(n)

		fmt.Println(ans)
	}
}

func solve_stupid(n int) int64 {
	var ans int64

	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			for k := j + 1; k < n; k++ {
				p1 := pr[i]
				p2 := pr[j]
				p3 := pr[k]

				if p1[0] == p2[0] || p1[0] == p3[0] || p2[0] == p3[0] {

					if p1[1] == p2[1] || p1[1] == p3[1] || p2[1] == p3[1] {
						continue

					} else {
						ans++
					}

				} else {
					ans++
				}
			}
		}
	}

	return ans
}

func solve(n int) int64 {
	var ans int64

	topic = make([][][2]int, n + 1)
	diff = make([][][2]int, n + 1)

	for i := 0; i < n; i++ {
		p := pr[i]

		topic[p[0]] = append(topic[p[0]], p)
		diff[p[1]] = append(diff[p[1]], p)
	}

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

	for i := 1; i <= n; i++ {
		t := topic[i]

		for j := 0; j < len(t); j++ {
			p := t[j]

			d := p[1]

			dd := diff[d]

			diffs := len(dd) - 1

			topicSum[i] += int64(diffs)
		}

	}

	for i := 1; i <= n; i++ {
		d := diff[i]

		for j := 0; j < len(d); j++ {
			p := d[j]

			top := p[0]

			tt := topic[top]

			tops := len(tt) - 1

			diffSum[i] += int64(tops)

		}
	}

	var all = (int64(n) - 1) * (int64(n) - 2)/2

	for i := 0; i < n; i++ {
		p := pr[i]

		top := p[0]
		di := p[1]

		sum1 := topicSum[top]

		sum1 = sum1 - int64(len(diff[di])) + 1

		sum2 := diffSum[di]

		sum2 = sum2 - int64(len(topic[top])) + 1

		ans += all - sum1 - sum2 - (int64(len(diff[di])) - 1) * (int64(len(topic[top])) - 1)
	}

	return ans/3
}

func update(n int, bit *[]map[int]int, x, y int, delta int) {
	for ;x <= n; x += x & -x {
		y1 := y
		for ; y1 <= n; y1 += y1 & -y1 {
			(*bit)[x][y1] += delta
		}
	}
}

func get(x, y int, bit *[]map[int]int) int64 {
	var ret int64 = 0

	for ; x > 0; x -= x & -x {
		y1 := y
		for ; y1 > 0; y1 -= y1 & -y1 {

			ret += int64((*bit)[x][y1])
		}
	}
	return ret
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for c:=1;c<=t;c++{
		var n int64
		fmt.Fscan(in,&n)
		a := make([]int,n+5)
		b := make([]int,n+5)
		mpt := map[int]int{}
		mpd := map[int]int{}
		sum := n*(n-1)*(n-2)/6
		var i int64
		for i=1;i<=n;i++{
			fmt.Fscan(in,&a[i],&b[i])
			mpt[a[i]]++
			mpd[b[i]]++
		}
		for i=1;i<=n;i++{
			sum -= int64((mpt[a[i]]-1)*(mpd[b[i]]-1))
		}
		fmt.Fprintln(out,sum)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for c:=1;c<=t;c++{
		var n int
		fmt.Fscan(in,&n)
		a := make([]int,n+5)
		b := make([]int,n+5)
		mpt := map[int]int{}
		mpd := map[int]int{}
		sum := n*(n-1)*(n-2)/6
		for i:=1;i<=n;i++{
			fmt.Fscan(in,&a[i],&b[i])
			mpt[a[i]]++
			mpd[b[i]]++
		}
		for i:=1;i<=n;i++{
			sum -= (mpt[a[i]]-1)*(mpd[b[i]]-1)
		}
		fmt.Fprintln(out,sum)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	const mod = 1000000007
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for c:=1;c<=t;c++{
		var n, k int
		fmt.Fscan(in,&n,&k)
		a := make([]int,n+5)
		cnt:=0
		ans:=0
		for i:=k;i>=1;i--{
			cnt++
			if i==k{
				ans += 1
				for j:=1;j<=n;j++{
					a[j]=1
				}
				continue
			}
			if cnt%2==0{
				pre := 0
				for j:=n;j>=1;j--{
					ans = (ans%(mod) + a[j]%(mod))%(mod)
					temp := a[j]
					a[j] = pre
					pre = (pre%(mod) + temp%(mod))%(mod)
				}
			}else{
				pre := 0
				for j:=1;j<=n;j++{
					ans = (ans%(mod) + a[j]%(mod))%(mod)
					temp := a[j]
					a[j] = pre
					pre = (pre%(mod) + temp%(mod))%(mod)
				}
			}
		}
		fmt.Fprintln(out,ans%mod)
	}
}

package main

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

var n int

var pr [][2]int

var topic [][][2]int
var diff [][][2]int

var bit []map[int]int

func main() {

	r := bufio.NewReader(os.Stdin)

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

	for i := 0; i < t; i++ {
		fmt.Fscan(r, &n)

		pr = make([][2]int, n)

		for  j := 0; j < n; j++ {
			fmt.Fscan(r, &pr[j][0], &pr[j][1])
		}

		ans := solve(n)

		fmt.Println(ans)
	}
}

func solve(n int) int64 {
	var ans int64

	topic = make([][][2]int, n + 1)
	diff = make([][][2]int, n + 1)

	for i := 0; i < n; i++ {
		p := pr[i]

		topic[p[0]] = append(topic[p[0]], p)
		diff[p[1]] = append(diff[p[1]], p)
	}

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

	for i := 1; i <= n; i++ {
		t := topic[i]

		for j := 0; j < len(t); j++ {
			p := t[j]

			d := p[1]

			dd := diff[d]

			diffs := len(dd) - 1

			topicSum[i] += int64(diffs)
		}

	}

	for i := 1; i <= n; i++ {
		d := diff[i]

		for j := 0; j < len(d); j++ {
			p := d[j]

			top := p[0]

			tt := topic[top]

			tops := len(tt) - 1

			diffSum[i] += int64(tops)

		}
	}

	var all = (int64(n) - 1) * (int64(n) - 2)/2

	for i := 0; i < n; i++ {
		p := pr[i]

		top := p[0]
		di := p[1]

		sum1 := topicSum[top]

		sum1 = sum1 - int64(len(diff[di])) + 1

		sum2 := diffSum[di]

		sum2 = sum2 - int64(len(topic[top])) + 1

		ans += all - sum1 - sum2
	}

	return ans/3
}

func update(n int, bit *[]map[int]int, x, y int, delta int) {
	for ;x <= n; x += x & -x {
		y1 := y
		for ; y1 <= n; y1 += y1 & -y1 {
			(*bit)[x][y1] += delta
		}
	}
}

func get(x, y int, bit *[]map[int]int) int64 {
	var ret int64 = 0

	for ; x > 0; x -= x & -x {
		y1 := y
		for ; y1 > 0; y1 -= y1 & -y1 {

			ret += int64((*bit)[x][y1])
		}
	}
	return ret
}


You have a sequence $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, consisting of integers between $$$1$$$ and $$$m$$$. You also have a string $$$s$$$, consisting of $$$m$$$ characters B.You are going to perform the following $$$n$$$ operations.   At the $$$i$$$-th ($$$1 \le i \le n$$$) operation, you replace either the $$$a_i$$$-th or the $$$(m + 1 - a_i)$$$-th character of $$$s$$$ with A. You can replace the character at any position multiple times through the operations. Find the lexicographically smallest string you can get after these operations.A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ of the same length if and only if in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2000$$$). The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 50$$$) — the length of the sequence $$$a$$$ and the length of the string $$$s$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the sequence $$$a$$$.

For each test case, print a string of length $$$m$$$ — the lexicographically smallest string you can get. Each character of the string should be either capital English letter A or capital English letter B.

NoteIn the first test case, the sequence $$$a = [1, 1, 3, 1]$$$. One of the possible solutions is the following.   At the $$$1$$$-st operation, you can replace the $$$1$$$-st character of $$$s$$$ with A. After it, $$$s$$$ becomes ABBBB.  At the $$$2$$$-nd operation, you can replace the $$$5$$$-th character of $$$s$$$ with A (since $$$m+1-a_2=5$$$). After it, $$$s$$$ becomes ABBBA.  At the $$$3$$$-rd operation, you can replace the $$$3$$$-rd character of $$$s$$$ with A. After it, $$$s$$$ becomes ABABA.  At the $$$4$$$-th operation, you can replace the $$$1$$$-st character of $$$s$$$ with A. After it, $$$s$$$ remains equal to ABABA.  The resulting string is ABABA. It is impossible to produce a lexicographically smaller string.In the second test case, you are going to perform only one operation. You can replace either the $$$2$$$-nd character or $$$4$$$-th character of $$$s$$$ with A. You can get strings BABBB and BBBAB after the operation. The string BABBB is the lexicographically smallest among these strings.In the third test case, the only string you can get is A.In the fourth test case, you can replace the $$$1$$$-st and $$$2$$$-nd characters of $$$s$$$ with A to get AABB.In the fifth test case, you can replace the $$$1$$$-st and $$$3$$$-rd characters of $$$s$$$ with A to get ABABBBB.

package main

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

func Min[T int | int64 | float64](x, y T) T {
	if x < y {
		return x

	}
	return y

}

func Max[T int | int64 | float64](x, y T) T {
	if x > y {
		return x

	}
	return y

}

func main() {
	var t int
	read := bufio.NewReader(os.Stdin)
	fmt.Fscan(read, &t)
	for ; t > 0; t-- {
		var (
			n, m, min int
		)
		fmt.Fscan(read, &n, &m)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(read, &a[i])
		}
		b := make([]bool, m)
		for _, val := range a {
			min = Min(m-val, val-1)
			val = Max(m-val, val-1)
			if b[min] {
				b[val] = true
				continue
			}
			b[min] = true
		}
		s := make([]byte, m)
		for index, val := range b {
			if val {
				s[index] = 'A'
			} else {
				s[index] = 'B'
			}
		}
		fmt.Println(string(s))
	}
}

package main

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

func Min[T int | int64 | float64](x, y T) T {
	if x < y {
		return x

	}
	return y

}

func Max[T int | int64 | float64](x, y T) T {
	if x > y {
		return x

	}
	return y

}

func main() {
	var t int
	read := bufio.NewReader(os.Stdin)
	fmt.Fscan(read, &t)
	for ; t > 0; t-- {
		var (
			n, m, min int
		)
		fmt.Fscan(read, &n, &m)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(read, &a[i])
		}
		b := make([]bool, m)
		for _, val := range a {
			min = Min(m-val, val-1)
			val = Max(m-val, val-1)
			if b[min] {
				b[val] = true
				continue
			}
			b[min] = true
		}
		for _, val := range b {
			if val {
				fmt.Print("A")
			} else {
				fmt.Print("B")
			}
		}
		fmt.Println()
	}
}

package main

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

func packAddrs(n []int) []interface{} {
	p := make([]interface{}, len(n))
	for i := range n {
		p[i] = &n[i]

	}
	return p

}

func Min[T int | int64 | float64](x, y T) T {
	if x < y {
		return x

	}
	return y

}

func Max[T int | int64 | float64](x, y T) T {
	if x > y {
		return x

	}
	return y

}

func main() {
	var t int
	read := bufio.NewReader(os.Stdin)
	fmt.Fscanln(read, &t)
	for ; t > 0; t-- {
		var (
			n, m, min int
		)
		fmt.Fscanln(read, &n, &m)
		a := make([]int, n)
		fmt.Fscanln(read, packAddrs(a)...)
		b := make([]bool, m)
		for _, val := range a {
			min = Min(m-val, val-1)
			val = Max(m-val, val-1)
			if b[min] {
				b[val] = true
				continue
			}
			b[min] = true
		}
		for _, val := range b {
			if val {
				fmt.Print("A")
			} else {
				fmt.Print("B")
			}
		}
		fmt.Println()
	}
}

package main

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

var symbols = map[bool]string{
	true:  "A",
	false: "B",
}

var in = bufio.NewReader(os.Stdin)

func main() {
	t := readInt()

	for i := 0; i < t; i++ {
		_, strLen := readTwoInts()
		a := readArrInt()

		str := make([]bool, strLen)
		for _, ai := range a {
			ai -= 1
			smaller, greater := ai, strLen-1-ai
			if smaller > greater {
				smaller, greater = greater, smaller
			}

			if str[smaller] == false {
				str[smaller] = true
				continue
			}

			if str[greater] == false {
				str[greater] = true
				continue
			}
		}

		for _, b := range str {
			fmt.Print(symbols[b])
		}
		fmt.Println()
	}
}

func readInt() int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readTwoInts() (int, int) {
	r := readArrInt()
	return r[0], r[1]
}

func readArrString() []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt() []int {
	numbs := readArrString()
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

package main

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

func main() {
	CF1706A(os.Stdin, os.Stdout)
}
func CF1706A(in io.Reader, out io.Writer) {
	r := bufio.NewReader(in)
	w := bufio.NewWriter(out)
	defer w.Flush()

	var T int64
	fmt.Fscan(r, &T)
	for ; T > 0; T-- {
		var n, m int
		fmt.Fscan(r, &n, &m)
		s := bytes.Repeat([]byte("B"), m)
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &arr[i])
		}
		for _, v := range arr {
			left, right := v-1, m-v
			if left > right {
				left, right = right, left
			}

			if s[left] == 'A' {
				s[right] = 'A'
			} else {
				s[left] = 'A'
			}

		}
		fmt.Fprintln(w, string(s))
	}
}

package main

import (
	"fmt"
)
func main() {
	time := 0
	fmt.Scanf("%d\n", &time)
	for time > 0 {
		time--
		ls, le := 0, 0
		fmt.Scanf("%d %d\n", &ls, &le)
		str := make([]byte, le)
		for i := range str {
			str[i] = byte('B')
		}
		squ := make([]int, ls)
		for i := range squ {
			fmt.Scan(&squ[i])
			squ[i]--
		}
		fmt.Scanf("\n")
		for _, v := range squ {
			vi := le - v - 1
			if v < vi {
				if str[v] != byte('A') {
					str[v] = byte('A')
				} else {
					str[vi] = byte('A')
				}
			} else {
				if str[vi] != byte('A') {
					str[vi] = byte('A')
				} else {
					str[v] = byte('A')
				}
			}
		}
		fmt.Println(string(str))
	}
}

package main

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

var reader *bufio.Reader

func main() {
	var (
		t int
		n int
		m int
	)

	reader = bufio.NewReader(os.Stdin)

	_, _ = fmt.Fscanln(reader, &t)

	for i := 0; i < t; i++ {
		_, _ = fmt.Fscanln(reader, &n, &m)

		solve(n, m)
	}
}

func solve(n, m int) {
	count := make(map[int]int)

	for n > 0 {
		n--

		var v int
		_, _ = fmt.Fscan(reader, &v)

		count[v-1]++
	}
	_, _ = fmt.Fscanln(reader)

	// true if A placed in ind position
	var answer = make([]bool, m)
	for k, counted := range count {
		if counted >= 2 {
			answer[k] = true
			answer[m-k-1] = true
		} else {
			var (
				a int
				b int
			)
			if k < m-k-1 {
				a = k
				b = m - k - 1
			} else {
				b = k
				a = m - k - 1
			}

			if answer[a] {
				answer[b] = true
			} else {
				answer[a] = true
			}
		}
	}

	var result strings.Builder
	for _, a := range answer {
		if a {
			result.WriteString("A")
		} else {
			result.WriteString("B")
		}
	}

	fmt.Println(result.String())
}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n,m int
		fmt.Fscan(in,&n,&m)
		row1:= make([]int,n)
		row2:= make([]int,n)
		for j:=0;j<n;j++{
			fmt.Fscan(in,&row1[j])
			row2[j]=(m+1-row1[j])
		}
		word:= make([]string,m)
		for j:=0;j<m;j++{
			word[j]="B"
		}
		for j:=0;j<n;j++{
			if row1[j] <= row2[j] {
				if string(word[row1[j]-1]) == "B" {
					word[row1[j]-1] = "A"
					continue
				}
			}
			if string(word[row2[j]-1]) == "B" {
				word[row2[j]-1] = "A"
			} else {
				word[row1[j]-1] = "A"
			}
		}
		for j:=0;j<len(word);j++{
			fmt.Fprintf(out,"%v",string(word[j]))
		}
		fmt.Fprintln(out,)
	}
}

// https://codeforces.com/problemset/problem/1706/A

// 1706A - Another String Minimization Problem

// You have a sequence a1,a2,…,an of length n, consisting of integers between 1 and m. You also have a string s, consisting of m characters B.
// You are going to perform the following n operations.
//  • At the i-th (1≤i≤n) operation, you replace either the ai-th or the (m+1−ai)-th character of s with A. You can replace the character at any position multiple times through the operations.
// Find the lexicographically smallest string you can get after these operations.
// A string x is lexicographically smaller than a string y of the same length if and only if in the first position where x and y differ, the string x has a letter that appears earlier in the alphabet than the corresponding letter in y.

// Input
// The first line contains the number of test cases t (1≤t≤2000).
// The first line of each test case contains two integers n and m (1≤n,m≤50) — the length of the sequence a and the length of the string s respectively.
// The second line contains n integers a1,a2,…,an (1≤ai≤m) — the sequence a.

// Output
// For each test case, print a string of length m — the lexicographically smallest string you can get. Each character of the string should be either capital English letter A or capital English letter B.

// Example
// input
// 6
// 4 5
// 1 1 3 1
// 1 5
// 2
// 4 1
// 1 1 1 1
// 2 4
// 1 3
// 2 7
// 7 5
// 4 5
// 5 5 3 5
// output
// ABABA
// BABBB
// A
// AABB
// ABABBBB
// ABABA

// Note

// In the first test case, the sequence a=[1,1,3,1]. One of the possible solutions is the following.
//  • At the 1-st operation, you can replace the 1-st character of s with A. After it, s becomes ABBBB.
//  • At the 2-nd operation, you can replace the 5-th character of s with A (since m+1−a2=5). After it, s becomes ABBBA.
//  • At the 3-rd operation, you can replace the 3-rd character of s with A. After it, s becomes ABABA.
//  • At the 4-th operation, you can replace the 1-st character of s with A. After it, s remains equal to ABABA.
// The resulting string is ABABA. It is impossible to produce a lexicographically smaller string.
// In the second test case, you are going to perform only one operation. You can replace either the 2-nd character or 4-th character of s with A. You can get strings BABBB and BBBAB after the operation. The string BABBB is the lexicographically smallest among these strings.
// In the third test case, the only string you can get is A.
// In the fourth test case, you can replace the 1-st and 2-nd characters of s with A to get AABB.
// In the fifth test case, you can replace the 1-st and 3-rd characters of s with A to get ABABBBB.

// Tutorial

// Let's iterate through the elements of a. For convenience, we'll make ai=min(ai,m+1−ai). If the ai-th character of s is not currently A, then we should replace it. Otherwise, we replace the (m+1−ai)-th character. This is because if we have the choice between replacing two characters, replacing the one with the smaller index will result in a lexicographically smaller string.
// Alternatively, we can keep track of how many times either x or m+1−x appears in a for each 1≤x≤⌈m/2⌉.
//  • If they appear 0 times, neither of these indices in s can become A.
//  • If they appear 1 time, it is optimal to set the x-th character to A, since this will produce a lexicographically smaller string.
//  • Otherwise, they appear at least 2 times, and it is possible to set both the x-th and (m+1−x)-th character to A.

package main

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

func main() {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	var c int
	var t, n, m, a, i uint
	var s []byte
	var cnt []uint

	for c, _ = fmt.Fscan(reader, &t); c == 1; c, _ = fmt.Fscan(reader, &t) {
		for ; t > 0; t-- {
			fmt.Fscan(reader, &n, &m)
			cnt = make([]uint, m)
			s = make([]byte, m)

			for i = 0; i < n; i++ {
				fmt.Fscan(reader, &a)
				a--

				if a > m-1-a {
					a = m - 1 - a
				}

				cnt[a]++
			}

			for i = 0; i < m; i++ {
				s[i] = 'B'
			}

			for i = 0; i < m; i++ {
				if cnt[i] > 0 {
					s[i] = 'A'

					if cnt[i] > 1 {
						s[m-i-1] = 'A'
					}
				}
			}

			fmt.Fprintln(writer, string(s))
		}
	}

	writer.Flush()
}

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, m := readTwoNums(reader)
		A := readNNums(reader, n)
		res := solve(A, m)
		buf.WriteString(res)
		buf.WriteByte('\n')
	}

	fmt.Print(buf.String())
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(A []int, m int) string {
	res := make([]byte, m)
	for i := 0; i < m; i++ {
		res[i] = 'B'
	}

	for _, i := range A {
		j := m + 1 - i
		x := i - 1
		y := j - 1
		if x > y {
			x, y = y, x
		}
		if res[x] == 'B' {
			res[x] = 'A'
		} else {
			res[y] = 'A'
		}
	}

	return string(res)
}

package main

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

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

func main() {
	defer out.Flush()
	var t, n, m int
	for fmt.Fscan(in, &t); t > 0; t-- {
		fmt.Fscan(in, &n, &m)
		var s string
		for i := 0; i < m; i++ {
			s += "B"
		}
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &a[i])
		}
		c := []byte(s)
		for i := 0; i < n; i++ {
			p := a[i] - 1
			q := m - 1 - p
			if p > q {
				p, q = q, p
			}
			// fmt.Fprintln(out, "test:", p, q)
			if c[p] == 'B' {
				c[p] = 'A'
			} else {
				c[q] = 'A'
			}
		}
		fmt.Fprintln(out, string(c))
	}
}

package main

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

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

func main() {
	defer out.Flush()

	var test int
	fmt.Fscan(in, &test)
	for i := 0; i < test; i++ {
		solve()
	}
}

func solve() {
	var n, m, x int
	fmt.Fscan(in, &n, &m)
	s := []byte{}
	for i := 0; i < m; i++ {
		s = append(s, 'B')
	}
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &x)
		x--
		y := m - 1 - x
		if x > y {
			x, y = y, x
		}

		if s[x] == 'B' {
			s[x] = 'A'
		} else {
			s[y] = 'A'
		}
	}
	fmt.Fprintln(out, string(s))
}

package main

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

var (
	reader  = bufio.NewReader(os.Stdin)
	t, n, m int
	a       []int
)

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

func solve(n, m int, a []int) string {
	b := strings.Repeat("B", m)
	for _, p := range a {
		k := min(p, m+1-p)
		if b[k-1] == 'B' {
			b = b[:k-1] + "A" + b[k:]
		} else {
			b = b[:m-k] + "A" + b[m-k+1:]
		}
	}
	return b
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n, &m)
		a = make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
		}
		fmt.Println(solve(n, m, a))
	}
}

package main

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

var bufferedStdin = bufio.NewReader(os.Stdin)
var bufferedStdout = bufio.NewWriter(os.Stdout)

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

func solve() {
	var n, m int
	_, _ = fmt.Fscan(bufferedStdin, &n, &m)
	answer := make([]rune, m)
	for i := 0; i < m; i++ {
		answer[i] = 'B'
	}
	for i := 0; i < n; i++ {
		var a int
		_, _ = fmt.Fscan(bufferedStdin, &a)
		ind := min(a-1, m-a)
		if answer[ind] == 'A' {
			answer[m-1-ind] = 'A'
		} else {
			answer[ind] = 'A'
		}
	}
	for _, value := range answer {
		_, _ = fmt.Fprintf(bufferedStdout, "%c", value)
	}
	_, _ = fmt.Fprint(bufferedStdout, "\n")
}

func main() {
	var t int
	_, _ = fmt.Fscan(bufferedStdin, &t)
	for i := 0; i < t; i++ {
		solve()
	}
	_ = bufferedStdout.Flush()
}

package main

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

type CF1706A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1706A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1706A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1706A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1706A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1706A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1706A
Date: 22/07/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1706/A
Problem: CF1706A
**/
func (in *CF1706A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n, m := in.NextInt(), in.NextInt()
		arr := make([]int, n)
		mapa := make(map[int]bool)
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}

		for i := 0; i < n; i++ {
			a := arr[i]
			b := m + 1 - arr[i]
			_, eA := mapa[a]
			_, eB := mapa[b]

			if a < b && !eA {
				mapa[a] = true
			} else if b < a && !eB {
				mapa[b] = true
			} else if !eA {
				mapa[a] = true
			} else {
				mapa[b] = true
			}
		}

		var ans strings.Builder
		for i := 0; i < m; i++ {
			if _, e := mapa[i+1]; e {
				ans.WriteString("A")
			} else {
				ans.WriteString("B")
			}
		}

		fmt.Println(ans.String())
	}
}

func NewCF1706A(r *bufio.Reader) *CF1706A {
	return &CF1706A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1706A(bufio.NewReader(os.Stdin)).Run()
}

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Scan()
	tests := sc.Text()
	cnt, _ := strconv.Atoi(tests)
	for cnt > 0 {
		sc.Scan()
		one := sc.Text()
		cur := strings.Split(one, " ")
		m, _ := strconv.Atoi(cur[0])
		n, _ := strconv.Atoi(cur[1])
		sc.Scan()
		arr := strings.Split(sc.Text(), " ")
		source := make([]byte, n)
		for i := 0; i < n; i++ {
			source[i] = 'B'
		}
		for i := 0; i < m; i++ {
			index, _ := strconv.Atoi(arr[i])
			index1, index2 := index-1, n-index
			if index1 > index2 {
				index1, index2 = index2, index1
			}
			if index1 < index2 && source[index1] == 'B' {
				source[index1] = 'A'
			} else {
				source[index2] = 'A'
			}
		}
		fmt.Printf("%s\n", string(source))
		cnt--
	}
}

package main

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

var _, _, _ = main, rw, do

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

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n, m int
		fmt.Fscan(r, &n, &m)
		b := make([]int, n)
		for i := range b {
			fmt.Fscan(r, &b[i])
		}
		w1 := do(n, m, b)
		fmt.Fprintln(w, w1)
	}
}

func do(n, m int, b []int) string {
	c := make([]byte, m)
	for i := range c {
		c[i] = 'B'
	}
	for _, v := range b {
		if v > m-v+1 {
			v = m - v + 1
		}
		if c[v-1] == 'B' {
			c[v-1] = 'A'
		} else {
			c[m-v] = 'A'
		}
	}
	return string(c)
}

package main

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

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

	n := readInt(in)
	for i := 0; i < n; i++ {
		solution(in, out)
	}
}

func solution(in *bufio.Reader, out *bufio.Writer) {
	v := readArrInt(in)
	k := v[1]
	arr := readArrInt(in)
	bools := make([]bool, k)

	for _, v := range arr {
		idx1 := v - 1
		idx2 := k - v
		firstIdx := Min(idx1, idx2)
		secondIdx := Max(idx1, idx2)
		if bools[firstIdx] {
			bools[secondIdx] = true
		} else {
			bools[firstIdx] = true
		}
	}

	for _, v := range bools {
		if v {
			out.WriteString("A")
		} else {
			out.WriteString("B")
		}
	}

	out.WriteString("\n")

}

func Max(sum int, sum2 int) int {
	if sum > sum2 {
		return sum
	}
	return sum2

}

func Min(sum int, sum2 int) int {
	if sum < sum2 {
		return sum
	}
	return sum2
}

func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readLine(in *bufio.Reader) string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	return line
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

package main

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

const MOD int64 = 1000000007

var n, m int

var a[]int

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

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

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &n, &m)

		a = make([]int, n)

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

		fmt.Println(solve())
	}
}

type pair struct {
	v int
	idx []int
}

func solve() string {
	bts := make([]byte, m)

	seen := make([]bool, m)

	for i := 0; i < n; i++ {
		aa := a[i] - 1
		bb := m - a[i]

		if aa <= bb {
			if seen[aa] {
				bts[bb] = 'A'
				seen[bb] = true
			} else {
				bts[aa] = 'A'
				seen[aa] = true
			}

		} else {
			if seen[bb] {
				bts[aa] = 'A'
				seen[aa] = true
			} else {
				bts[bb] = 'A'
				seen[bb] = true
			}
		}
	}

	for i := 0; i < m; i++ {
		if bts[i] == 0 {
			bts[i] = 'B'
		}
	}

	return string(bts)
}

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

package main

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

var cf = true

func solve() {
	var n, m int
	fmt.Fscan(in, &n, &m)
	ans := make([]byte, m)
	for i := range ans {
		ans[i] = 'B'
	}
	var ind int
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &ind)
		ind1 := ind - 1
		ind2 := m - ind
		if ind1 > ind2 {
			ind1, ind2 = ind2, ind1
		}
		if ans[ind1] == 'B' {
			ans[ind1] = 'A'
		} else {
			ans[ind2] = 'A'
		}
	}
	fmt.Fprintf(out, "%s\n", string(ans))
}

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

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

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

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

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

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

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

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

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

var exists = struct{}{}

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

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

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

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

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

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

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

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

package main

import (
	"fmt"
)

func main() {
	times := 0
	fmt.Scan(&times)
	for i := 0; i < times; i++ {
		n, m, poss := 0, 0, []int{}
		fmt.Scan(&n, &m)
		for j := 0; j < n; j++ {
			tmpNum := 0
			fmt.Scan(&tmpNum)
			poss = append(poss, tmpNum)
		}
		ans := solve(m ,poss)
		fmt.Println(ans)
	}
}

func solve(l int, poss []int) string {
	m := make(map[int]bool)
	for _, pos := range poss {
		if pos > (l + 1) / 2 {
			pos = l + 1 - pos
		}
		if _, ok := m[pos]; !ok {
			m[pos] = false
		} else {
			m[pos] = true
		}
	}
	//fmt.Println(m)
	ans := []byte{}
	for i := 0; i < l; i++ {
		ans = append(ans, 'B')
	}
	for pos, flag := range m {
		if !flag {
			ans[pos - 1] = 'A'
		} else {
			ans[pos - 1] = 'A'
			ans[l - pos] = 'A'
		}
	}
	return string(ans)
}

package main

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

func main() {
    in := bufio.NewReader(os.Stdin)
    tc := readInt(in)
    for tc > 0 {
        f := readArrInt(in)
        n := f[0]
        m := f[1]
        ops := readArrInt(in)
        var res []rune
        for i:=0; i<m; i++ {
            res = append(res, 'B')
        }

        for i:=0; i<n; i++ {
            curId := ops[i]
            nextId := m+1-curId

            if nextId < curId {
                curId, nextId = nextId, curId
            }

            if curId-1 >= 0 && curId-1 < m && res[curId-1] == 'B' {
                res[curId-1] = 'A'
            } else if nextId-1 >= 0 && nextId-1 < m {
                res[nextId-1] = 'A'
            }
        }
        fmt.Println(string(res))
        tc--
    }
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

package main

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

func solve() {
	n := get()
	m := get()
	a := geta(n)
	for i := range a {
		a[i]--
	}

	s := []rune(strings.Repeat("B", m))

	for _, i := range a {
		if m-i-1 < i {
			i = m - i - 1
		}
		if s[i] == 'B' {
			s[i] = 'A'
			continue
		}
		s[m-i-1] = 'A'
	}

	putsln(string(s))
}

const (
	once       = false
	maxBufSize = 10000000
)

var (
	splitFunc = bufio.ScanWords
)

func main() {
	in = bufio.NewScanner(bufio.NewReader(os.Stdin))
	in.Split(splitFunc)
	in.Buffer(make([]byte, maxBufSize), maxBufSize)

	out = bufio.NewWriter(os.Stdout)
	defer out.Flush()

	if once {
		solve()
		return
	}

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

var (
	in  *bufio.Scanner
	out *bufio.Writer
)

func get() int {
	x, _ := strconv.Atoi(gets())
	return x
}

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

func get64() int64 {
	x, _ := strconv.ParseInt(gets(), 10, 64)
	return x
}

func get64a(n int) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = get64()
	}
	return a
}

func getf() float64 {
	x, _ := strconv.ParseFloat(gets(), 64)
	return x
}

func getfa(n int) []float64 {
	a := make([]float64, n)
	for i := range a {
		a[i] = getf()
	}
	return a
}

func gets() string {
	scan()
	return in.Text()
}

func scanN(n int) {
	for n > 0 {
		scan()
		n--
	}
}

func scan() {
	in.Scan()
}

func putc(c rune) {
	out.WriteRune(c)
}

func put(x int) {
	out.WriteString(strconv.Itoa(x))
}

func putln(i int) {
	put(i)
	line()
}

func puta(a []int) {
	for _, v := range a {
		put(v)
		space()
	}
	line()
}

func put64(x int64) {
	out.WriteString(strconv.FormatInt(x, 10))
}

func put64ln(x int64) {
	put64(x)
	line()
}

func put64a(a []int64) {
	for _, v := range a {
		put64(v)
		space()
	}
	line()
}

func puts(s string) {
	out.WriteString(s)
}

func putsln(s string) {
	puts(s)
	line()
}

func yn(y bool) {
	if y {
		yes()
		return
	}
	no()
}

func yes() {
	puts("YES\n")
}

func no() {
	puts("NO\n")
}

func putf(x float64) {
	out.WriteString(strconv.FormatFloat(x, 'f', -1, 64))
}

func putfln(x float64) {
	putf(x)
	line()
}

func putfa(a []float64) {
	for _, v := range a {
		putf(v)
		space()
	}
	line()
}

func line() {
	out.WriteRune('\n')
}

func space() {
	out.WriteRune(' ')
}

package main

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

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

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n, m int
		fmt.Fscan(in, &n, &m)
		s := bytes.Repeat([]byte{'B'}, m)
		for i := 0; i < n; i++ {
			var v int
			fmt.Fscan(in, &v)

			d := min(v-1, m-v)
			if s[d] == 'B' {
				s[d] = byte('A')
			} else {
				s[max(v-1, m-v)] = byte('A')
			}
		}
		fmt.Fprintln(out, string(s))
	}
}

package main

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	var ntests int
	fmt.Fscan(scanner, &ntests)
	for iter := 0; iter < ntests; iter++ {
		var n, m int
		fmt.Fscan(scanner, &n, &m)
		slice := make([]rune, m)
		for i := 0; i < m; i++ {
			slice[i] = 'B'
		}
		for i := 0; i < n; i++ {
			var num int
			fmt.Fscan(scanner, &num)
			num = num - 1
			if m-num-1 < num {
				num = m - num - 1
			}
			if slice[num] != 'A' {
				slice[num] = 'A'
			} else {
				slice[m-num-1] = 'A'
			}
		}
		for i := 0; i < m; i++ {
			fmt.Printf("%c", slice[i])
		}
		fmt.Println()
	}
}

package main

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

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

func a1706(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T int
	var n int
	var m int
	var x int

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		Fscan(in, &m)
		r := make([]int, n)
		for i := 0; i < n; i++ {
			Fscan(in, &x)
			r[i] = x
		}
		ans := make([]byte, m)
		for i := 0; i < m; i++ {
			ans[i] = 'B'
		}
		for _, v := range r {
			a, b := v-1, m-v
			if a > b {
				a, b = b, a
			}
			if ans[a] == 'A' {
				ans[b] = 'A'
			} else {
				ans[a] = 'A'
			}
		}

		Fprintln(out, string(ans))
	}
}

// 00
package main

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

func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var n, m, curr int
		fmt.Fscan(reader, &n, &m)
		bs := make([]byte, m)
		for i := 0; i < m; i++ {
			bs[i] = 'B'
		}
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &curr)
			first := curr - 1
			other := m - curr
			if first > other {
				first, other = other, first
			}
			if bs[first] == 'B' {
				bs[first] = 'A'
			} else {
				bs[other] = 'A'
			}
		}
		fmt.Println(string(bs))
	}
}

package main

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

func solve(n int, m int, a []int) string {
	res := make([]int, m)
	for i := 0; i < m; i++ {
		res[i] = 1
	}

	for i := 0; i < n; i++ {
		u := a[i] - 1
		v := m - a[i]
		if u > v {
			u, v = v, u
		}
		if res[u] == 1 {
			res[u] = 0
		} else {
			res[v] = 0
		}
	}

	s := ""
	for i := 0; i < m; i++ {
		if res[i] == 0 {
			s += "A"
		} else {
			s += "B"
		}
	}

	return s
}

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

	var test int
	fmt.Fscanln(inp, &test)

	for test > 0 {
		test--

		var n, m int
		fmt.Fscanln(inp, &n, &m)

		a := make([]int, n)
		for i := 0; i < n; i++ {
			if i == n-1 {
				fmt.Fscanln(inp, &a[i])
			} else {
				fmt.Fscan(inp, &a[i])
			}
		}

		fmt.Fprintln(out, solve(n, m, a))
	}

	out.Flush()
}

package main

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

var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

func slove() {
	var n, m int
	fmt.Fscan(rr, &n, &m)
	nums := make([]int, n)
	ans := make([]byte, m)
	for i := range ans {
		ans[i] = 'B'
	}
	for i:=0;i<len(nums);i++ {
		fmt.Fscan(rr, &nums[i])
		if ans[min(m-nums[i], nums[i]-1)] == 'B' {
			ans[min(m-nums[i], nums[i]-1)] = 'A'
		} else {
			ans[max(m-nums[i], nums[i]-1)] = 'A'
		}
	}
	fmt.Fprintln(ww, string(ans))
}

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

func main() {
	defer ww.Flush()
	var n int
	fmt.Fscan(rr, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

package main

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

func main() {
	CF1706A(os.Stdin, os.Stdout)
}
func CF1706A(in io.Reader, out io.Writer) {
	r := bufio.NewReader(in)
	w := bufio.NewWriter(out)
	defer w.Flush()

	var T int64
	fmt.Fscan(r, &T)
	for ; T > 0; T-- {
		var n, m int
		fmt.Fscan(r, &n, &m)
		s := bytes.Repeat([]byte("B"), m)
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &arr[i])
		}
		for _, v := range arr {
			left, right := v-1, m-v
			if s[left] == 'A' {
				s[right] = 'A'
			} else {
				s[left] = 'A'
			}
		}
		fmt.Fprintln(w, string(s))
	}
}

package main

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

var reader *bufio.Reader

func main() {
	var (
		t int
		n int
		m int
	)

	reader = bufio.NewReader(os.Stdin)

	_, _ = fmt.Fscanln(reader, &t)

	for i := 0; i < t; i++ {
		_, _ = fmt.Fscanln(reader, &n, &m)

		solve(n, m)
	}
}

func solve(n, m int) {
	count := make(map[int]int)

	for n > 0 {
		n--

		var v int
		_, _ = fmt.Fscan(reader, &v)

		count[v-1]++
	}
	_, _ = fmt.Fscanln(reader)

	// true if A placed in ind position
	var answer = make([]bool, m)
	for k, counted := range count {
		if counted >= 2 {
			answer[k] = true
			answer[m-k-1] = true
		} else {
			if k < m-k-1 {
				answer[k] = true
			} else {
				answer[m-k-1] = true
			}
		}
	}

	var result strings.Builder
	for _, a := range answer {
		if a {
			result.WriteString("A")
		} else {
			result.WriteString("B")
		}
	}

	fmt.Println(result.String())
}


This problem is a version of problem D from the same contest with some additional constraints and tasks.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \le a_i \le n$$$). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad).It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.You really like some of the candies and don't want to include them into the gift, but you want to eat them yourself instead. For each candy, a number $$$f_i$$$ is given, which is equal to $$$0$$$ if you really want to keep $$$i$$$-th candy for yourself, or $$$1$$$ if you don't mind including it into your gift. It is possible that two candies of the same type have different values of $$$f_i$$$.You want your gift to be as large as possible, but you don't want to include too many of the candies you want to eat into the gift. So, you want to calculate the maximum possible number of candies that can be included into a gift, and among all ways to choose maximum number of candies, you want to maximize the number of candies having $$$f_i = 1$$$ in your gift.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. Then $$$n$$$ lines follow, each containing two integers $$$a_i$$$ and $$$f_i$$$ ($$$1 \le a_i \le n$$$, $$$0 \le f_i \le 1$$$), where $$$a_i$$$ is the type of the $$$i$$$-th candy, and $$$f_i$$$ denotes whether you want to keep the $$$i$$$-th candy for yourself ($$$0$$$ if you want to keep it, $$$1$$$ if you don't mind giving it away). It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For each query print two integers:   the maximum number of candies in a gift you can compose, according to the constraints in the statement;  the maximum number of candies having $$$f_i = 1$$$ in a gift you can compose that contains the maximum possible number of candies.

NoteIn the first query, you can include two candies of type $$$4$$$ and one candy of type $$$5$$$. All of them have $$$f_i = 1$$$ and you don't mind giving them away as part of the gift.

package main

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

type hp struct{ sort.IntSlice }

func (h hp) Less(i, j int) bool  { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() (v interface{}) {
	n := len(h.IntSlice)
	h.IntSlice, v = h.IntSlice[:n-1], h.IntSlice[n-1]
	return
}

// github.com/EndlessCheng/codeforces-go
func CF1183G(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}

	var t, n, tp, f int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		types := make([][2]int, n+1)
		for i := 0; i < n; i++ {
			Fscan(in, &tp, &f)
			types[tp][f]++
		}
		cnts := make([][]int, n+1)
		for _, t := range types {
			s := t[0] + t[1]
			cnts[s] = append(cnts[s], t[1])
		}
		h := &hp{}
		sum, sumF1 := 0, 0
		for i := n; i > 0; i-- {
			for _, f1 := range cnts[i] {
				Push(h, f1)
			}
			if len(h.IntSlice) > 0 {
				sum += i
				sumF1 += min(Pop(h).(int), i)
			}
		}
		Fprintln(out, sum, sumF1)
	}
}

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


You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x < m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a < m \le 10^{10}$$$).

Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.

NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.

package main

import (
	"fmt"
)

func GetPrimeList(n int) []int {
	vis := make([]bool, n)
	primeList := []int{}

	for i := 2; i < n; i++ {
		if !vis[i] {
			primeList = append(primeList, i)
			for j := 2 * i; j < n; j += i {
				vis[j] = true
			}
		}
	}

	return primeList
}

func Gcd(a int64, b int64) int64 {
	if a == 0 {
		return b
	}
	return Gcd(b % a, a)
}

const (
	MAXN = 100005
)

func solve(primeList []int64, m int64) int64 {
	var ans int64
	n := len(primeList)
	for mask := 0; mask < (1 << uint(n)); mask++ {
		cur := int64(1)
		sgn := int64(1)
		for idx, val := range primeList {
			if (mask >> uint(idx) & 1) == 1 {
				cur *= val
				sgn = -sgn
			}
		}
		ans += sgn * (m / cur)
	}
	return ans
}

func main() {
	primeList := GetPrimeList(MAXN)

	var t int
	fmt.Scan(&t)
	for ; t > 0; t-- {
		var a, m int64
		fmt.Scan(&a, &m)

		g := Gcd(a, m)
		mDivG := m / g

		curPrimeList := []int64{}
		for _, pri := range primeList {
			if mDivG % int64(pri) == 0 {
				curPrimeList = append(curPrimeList, int64(pri))
				for mDivG % int64(pri) == 0 {
					mDivG /= int64(pri)
				}
			}
		}
		if mDivG != 1 {
			curPrimeList = append(curPrimeList, mDivG)
		}
		fmt.Println(solve(curPrimeList, (a + m - 1) / g) - solve(curPrimeList, (a - 1) / g))
	}
}

/*
URL:
https://codeforces.com/contest/1295/problem/D
*/

package main

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

var (
	t int

	a, m int64
)

func main() {
	defer stdout.Flush()

	t = readi()
	for i := 0; i < t; i++ {
		a, m = readll2()

		solve()
	}
}

func solve() {
	d := Gcd(a, m)
	_, q := a/d, m/d

	memo := TrialDivision(q)

	// ans := q
	// for e := range memo {
	// 	y := e - (p % e)
	// 	if y <= q-1 {
	// 		n := (q - y - 1) / e
	// 		num := maxll(n+1, 0)
	// 		ans -= num
	// 	}
	// }

	// オイラー関数を使ってみる
	ans := EulerPhi(q, memo)

	printf("%d\n", ans)
}

func EulerPhi(n int64, P map[int64]int64) int64 {
	res := n

	for p := range P {
		res /= p
		res *= (p - 1)
	}

	return res
}

// TrialDivision returns the result of prime factorization of integer N.
func TrialDivision(n int64) map[int64]int64 {
	var i, exp int64
	p := map[int64]int64{}

	if n <= 1 {
		panic(errors.New("[argument error]: TrialDivision only accepts a NATURAL number"))
	}

	for i = 2; i*i <= n; i++ {
		exp = 0
		for n%i == 0 {
			exp++
			n /= i
		}

		if exp == 0 {
			continue
		}
		p[i] = exp
	}
	if n > 1 {
		p[n] = 1
	}

	return p
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int64) int64 {
	if a < 0 || b < 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	if a == 0 {
		return b
	}
	if b == 0 {
		return a
	}

	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int64) int64 {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

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

// modi can calculate a right residual whether value is positive or negative.
func modi(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// modll can calculate a right residual whether value is positive or negative.
func modll(val, m int64) int64 {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

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

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

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

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

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

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

// chmaxi 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 chmaxi(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// chmaxll 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 chmaxll(updatedValue *int64, target int64) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

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

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

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

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

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

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  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()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

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

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

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

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

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

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

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

// 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)
}

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

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

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

// 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
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"sync"
)
const maxn int = 1e7 + 1
var pri, mu, vis [maxn]int
var cnt int
func Init(n int) {
	mu[1] = 1
	for i := 2; i <= n; i++ {
		if vis[i] == 0 {
			cnt++
			pri[cnt] = i
			mu[i] = -1
		}
		for j := 1; j <= cnt && pri[j] * i <= n; j++ {
			vis[pri[j] * i] = 1
			if i % pri[j] != 0 {
				mu[i * pri[j]] = -mu[i]
			} else {
				break
			}
		}
	}
}
func GetPhi(n int64) int64 {
	m := n
	for j := int64(2); j * j <= m; j++ {
		if m % j == 0 {
			n = n / j * (j - 1)
			for ; m % j == 0; {
				m /= j
			}
		}
	}
	if m != 1 {
		n = n / m * (m - 1)
	}
	return n
}
func GetMu(n int64) int64 {
	cat := 0
	for j := int64(2); j * j <= n; j++ {
		if n % j == 0 {
			cat++
			sum := 0
			for ; n % j == 0; {
				n /= j
				sum++
			}
			if sum > 1 {
				return 0
			}
		}
	}
	if n > 1 {
		cat++
	}
	if cat % 2 == 1 {
		return -1
	} else {
		return 1
	}
}
func __gcd(a, b int64) int64 {
	if a % b == 0 {
		return b
	}
	return __gcd(b, a % b)
}
func solve() {
	n, m := ReadInt(), ReadInt()
	//fmt.Println(n)
	gcd := int64(__gcd(n, m))
	n /= gcd
	m /= gcd
	ans := GetPhi(m)
	fmt.Println(ans)
}
func main() {
	Init(1e7)
	for T := ReadInt(); T > 0; T-- {
		solve()
	}
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
var out chan string
var in *bufio.Scanner
var outWg *sync.WaitGroup
func ReadString() string {
	in.Scan()
	return in.Text()
}
func ReadStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ReadString()
	}
	return s
}
func ReadInt() int64 {
	intStr := ReadString()
	i, _ := strconv.ParseInt(intStr, 10, 64)
	return int64(i)
}
func ReadIntSlice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ReadInt()
	}
	return arr
}
func init() {
	//set input
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(2e+5))
	in.Split(bufio.ScanWords)

	//set output
	out = make(chan string, 16)
	outWg = &sync.WaitGroup{}
	outWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(2e+5))
	go func(write *bufio.Writer) {
		defer outWg.Done()
		defer write.Flush()

		for line := range out {
			write.WriteString(line + "\n")
		}
	}(writer)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1295D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	calcGCD := func(a, b int64) int64 {
		for b != 0 {
			a, b = b, a%b
		}
		return a
	}
	calcPhi := func(n int64) int64 {
		ans := n
		for i := int64(2); i*i <= n; i++ {
			if n%i == 0 {
				ans = ans / i * (i - 1)
				for ; n%i == 0; n /= i {
				}
			}
		}
		if n > 1 {
			ans = ans / n * (n - 1)
		}
		return ans
	}

	var t int
	for Fscan(in, &t); t > 0; t-- {
		var a, m int64
		Fscan(in, &a, &m)
		Fprintln(out, calcPhi(m/calcGCD(a, m)))
	}
}

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

/*
URL:
https://codeforces.com/contest/1295/problem/D
*/

package main

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

var (
	t int

	a, m int64
)

func main() {
	defer stdout.Flush()

	t = readi()
	for i := 0; i < t; i++ {
		a, m = readll2()

		solve()
	}
}

func solve() {
	d := Gcd(a, m)
	p, q := a/d, m/d

	memo := TrialDivision(q)

	ans := q
	for e := range memo {
		y := e - (p % e)
		if y <= q-1 {
			n := (q - y - 1) / e
			num := maxll(n+1, 0)
			ans -= num
		}
	}

	printf("%d\n", ans)
}

// TrialDivision returns the result of prime factorization of integer N.
func TrialDivision(n int64) map[int64]int64 {
	var i, exp int64
	p := map[int64]int64{}

	if n <= 1 {
		panic(errors.New("[argument error]: TrialDivision only accepts a NATURAL number"))
	}

	for i = 2; i*i <= n; i++ {
		exp = 0
		for n%i == 0 {
			exp++
			n /= i
		}

		if exp == 0 {
			continue
		}
		p[i] = exp
	}
	if n > 1 {
		p[n] = 1
	}

	return p
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int64) int64 {
	if a < 0 || b < 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	if a == 0 {
		return b
	}
	if b == 0 {
		return a
	}

	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int64) int64 {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

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

// modi can calculate a right residual whether value is positive or negative.
func modi(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// modll can calculate a right residual whether value is positive or negative.
func modll(val, m int64) int64 {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

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

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

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

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

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

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

// chmaxi 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 chmaxi(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// chmaxll 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 chmaxll(updatedValue *int64, target int64) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

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

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

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

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

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

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  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()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

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

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

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

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

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

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

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

// 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)
}

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

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

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

// 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
}

/*
URL:
https://codeforces.com/contest/1295/problem/D
*/

package main

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

var (
	t int

	a, m int64
)

func main() {
	defer stdout.Flush()

	t = readi()
	for i := 0; i < t; i++ {
		a, m = readll2()

		solve()
	}
}

func solve() {
	d := Gcd(a, m)
	p, q := a/d, m/d

	memo := TrialDivision(q)

	ans := q
	for e := range memo {
		y := e - (p % e)
		n := (q - y - 1) / e

		num := maxll(n+1, 0)
		ans -= num
	}

	printf("%d\n", ans)
}

// TrialDivision returns the result of prime factorization of integer N.
func TrialDivision(n int64) map[int64]int64 {
	var i, exp int64
	p := map[int64]int64{}

	if n <= 1 {
		panic(errors.New("[argument error]: TrialDivision only accepts a NATURAL number"))
	}

	for i = 2; i*i <= n; i++ {
		exp = 0
		for n%i == 0 {
			exp++
			n /= i
		}

		if exp == 0 {
			continue
		}
		p[i] = exp
	}
	if n > 1 {
		p[n] = 1
	}

	return p
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int64) int64 {
	if a < 0 || b < 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	if a == 0 {
		return b
	}
	if b == 0 {
		return a
	}

	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int64) int64 {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

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

// modi can calculate a right residual whether value is positive or negative.
func modi(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// modll can calculate a right residual whether value is positive or negative.
func modll(val, m int64) int64 {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

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

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

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

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

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

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

// chmaxi 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 chmaxi(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// chmaxll 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 chmaxll(updatedValue *int64, target int64) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

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

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

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

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

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

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  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()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

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

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

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

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

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

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

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

// 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)
}

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

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

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

// 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
}