You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive.  All the written labels are distinct.  The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.

The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.

Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).

package main

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

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') {
			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 fillNNums(bs []byte, n int, res []int) {
	x := 0
	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])
	}
}

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

	n := readNum(reader)
	E := make([][]int, n-1)
	for i := 0; i < n-1; i++ {
		E[i] = readNNums(reader, 2)
	}
	res := solve(n, E)

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

func solve(n int, E [][]int) []int {
	degree := make([]int, n)
	pivot := -1
	for _, e := range E {
		u, v := e[0]-1, e[1]-1
		degree[u]++
		degree[v]++
		if degree[u] > 2 {
			pivot = u
		}
		if degree[v] > 2 {
			pivot = v
		}
	}
	ans := make([]int, len(E))
	for i := 0; i < len(ans); i++ {
		ans[i] = -1
	}

	var from int

	if pivot > 0 {
		for i := 0; i < len(E) && from < 3; i++ {
			u, v := E[i][0]-1, E[i][1]-1
			if u == pivot || v == pivot {
				ans[i] = from
				from++
			}
		}
	}

	for i := 0; i < len(E); i++ {
		if ans[i] < 0 {
			ans[i] = from
			from++
		}
	}

	return ans
}

package main

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

var reader io.Reader
var scanner *bufio.Scanner

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

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

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

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

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

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

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

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

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

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

type Graph struct {
	n     int
	m     int
	edges int
	fst   []int
	nxt   []int
	end   []int
	mark  []int
}

func (g *Graph) Add(a, b int) {
	g.nxt[g.edges] = g.fst[a]
	g.fst[a] = g.edges
	g.end[g.edges] = b
	g.edges++
}

func (g *Graph) Adjacent(a int, fn func(u, to int)) {
	for u := g.fst[a]; u != -1; u = g.nxt[u] {
		fn(u>>1, g.end[u])
	}
}

func NewGraph(n, m int) *Graph {
	mark := make([]int, m)
	for i := 0; i < m; i++ {
		mark[i] = -1
	}
	g := &Graph{n, m, 0, make([]int, n), make([]int, m), make([]int, m), mark}
	for i := 0; i < n; i++ {
		g.fst[i] = -1
	}
	return g
}

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

	n := NextInt()
	g := NewGraph(n, 2*n)
	parent := make([][2]int, n)
	used := make([]bool, n-1)
	color := make([]int, n-1)
	for i := 0; i < n-1; i++ {
		color[i] = -1
		u, v := NextInt()-1, NextInt()-1
		g.Add(u, v)
		g.Add(v, u)
	}

	if n <= 3 {
		for i := 0; i < n-1; i++ {
			fmt.Fprintln(out, i)
		}
		return
	}

	var dfs func(v int, paru, par, h int) (int, int)
	dfs = func(v int, paru, par, h int) (int, int) {
		parent[v][0] = par
		parent[v][1] = paru
		deepest := v
		height := h
		g.Adjacent(v, func(u, to int) {
			if to == par {
				return
			}
			leaf, leafheight := dfs(to, u, v, h+1)
			if leafheight > height {
				deepest = leaf
				height = leafheight
			}
		})
		return deepest, height
	}

	root, _ := dfs(0, -1, -1, 0)
	leaf, _ := dfs(root, -1, -1, 0)
	// stderr("root", root, "leaf", leaf)

	switched := false
	for t, c := leaf, 2; t != root; t, c = parent[t][0], c+1 {
		u := parent[t][1]
		if !switched && (c == n-1 || parent[t][0] == root) {
			c = 0
			switched = true
		}
		used[c] = true
		color[u] = c
	}

	for u, c := 0, 0; u < n-1; u++ {
		if color[u] != -1 {
			continue
		}
		for c < n-1 && used[c] {
			c++
		}
		if c == n-1 {
			panic("WTF!")
		}
		color[u] = c
		used[c] = true
	}

	for i := 0; i < n-1; i++ {
		fmt.Fprintln(out, color[i])
	}
}

package main

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

type Edge struct {
	to int
	w  int
}

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

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

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

	for i := 1; i < n; i++ {
		var f, t int
		fmt.Fscan(r, &f, &t)
		G[f] = append(G[f], Edge{t, i})
		G[t] = append(G[t], Edge{f, i})
	}

	cnt := 1
	res := make([]int, n+1)
	for i := 1; i < n; i++ {
		if len(G[i]) > 2 {
			for _, v := range G[i] {
				res[v.w] = cnt
				cnt++
			}
			break
		}
	}
	for i := 1; i < n; i++ {
		if res[i] == 0 {
			res[i] = cnt
			cnt++
		}
		fmt.Fprint(w, res[i]-1, "\n")
	}

}

/*
URL:
https://codeforces.com/problemset/problem/1325/C
*/

package main

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

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

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

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

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

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

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

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

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

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

var (
	n int

	deg    [200000 + 50]int
	U, V   [200000 + 50]int
	labels [200000 + 50]int
)

func main() {
	n = ReadInt()
	for i := 0; i < n-1; i++ {
		u, v := ReadInt2()
		deg[u]++
		deg[v]++
		U[i], V[i] = u, v
	}

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

	flag := true
	for i := 1; i <= n; i++ {
		if deg[i] > 2 {
			flag = false

			// iから伸びるエッジに0, 1, 2のラベルを貼る
			color := 0
			for j := 0; j < n-1; j++ {
				u, v := U[j], V[j]
				if u == i || v == i {
					labels[j] = color
					color++
					if color >= 3 {
						break
					}
				}
			}

			break
		}
	}

	if flag {
		for i := 0; i < n-1; i++ {
			fmt.Println(i)
		}
		return
	}

	color := 3
	for i := 0; i < n-1; i++ {
		if labels[i] < 0 {
			labels[i] = color
			color++
		}
	}

	for i := 0; i < n-1; i++ {
		fmt.Println(labels[i])
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

package main

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

const N = int64(2e5)

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

	var n int
	fmt.Fscanf(r, "%d\n", &n)

	edgeToIdx := make(map[int64]int)
	val := make([]int, n-1)
	g := make(map[int][]int)
	for i := 0; i < n-1; i++ {
		var u, v int
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		val[i] = -1
		g[u] = append(g[u], v)
		g[v] = append(g[v], u)
		edgeToIdx[Hash(u, v)] = i
		edgeToIdx[Hash(v, u)] = i
	}

	used := make(map[int]bool)
	for u := 1; u <= n; u++ {
		deg := len(g[u])
		if deg >= 3 {
			for i, v := range g[u] {
				idx, ok := edgeToIdx[Hash(u, v)]
				if !ok {
					panic("Impossible")
				}
				val[idx] = i
				used[i] = true
			}
			break
		}
	}

	nxt := 0
	for i := 0; i < n-1; i++ {
		if val[i] >= 0 {
			continue
		}
		for used[nxt] {
			nxt++
		}
		used[nxt] = true
		val[i] = nxt
	}

	for i := 0; i < n-1; i++ {
		fmt.Fprintf(w, "%d\n", val[i])
	}
}

func Hash(u, v int) int64 {
	return int64(u)*N + int64(v)
}

package main

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

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

	var n, v, w int
	Fscan(in, &n)
	if n == 2 {
		Fprint(out, 0)
		return
	}
	g := make([][]int, n)
	edgeI := make([]int, n)
	for i := 0; i < n-1; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
		edgeI[v] = i
		edgeI[w] = i
	}
	ans := make([]int, n-1)
	label := 1
	for v, vs := range g {
		if len(vs) == 1 {
			ans[edgeI[v]] = label
			label++
		}
	}
	for i, v := range ans {
		if v == 0 {
			ans[i] = label
			label++
		}
	}
	for _, v := range ans {
		Fprintln(out, v-1)
	}
}

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

package main

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

func main() {
	n := nextInt()
	d, e := make([]int, n + 1), make([]int, n + 1)
	for i := 0; i < n - 1; i++ {
		x, y := nextInt(), nextInt()
		d[x]++
		d[y]++
		e[x], e[y] = i, i
	}
	if n == 2 {
		print(0, NL)
	} else {
		a, l := make([]int, n - 1), 0
		for i := 1; i <= n; i++ {
			if d[i] == 1 {
				l++
				a[e[i]] = l
			}
		}
		for i := 0; i < n - 1; i++ {
			if a[i] == 0 {
				print(l, NL)
				l++
			} else {
				print(a[i] - 1, NL)
			}
		}
	}
	writer.Flush()
}

var NL string = "\n"
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

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

func nextInt() int {
	var n int
	fmt.Fscan(reader, &n)
	return n
}

package main

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

const N  = 100100

type EdgeInfo struct {
	nxt int
	edgeId int
}

var adj [][]EdgeInfo

var res [N] int
var deg [N] int

func main()  {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var n int
	fmt.Fscanf(reader,"%d\n", &n)

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

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

	var provider = 1
	for i := 1; i <= n; i++ {
		for _, element := range adj[i] {
			if deg[element.nxt] == 1 && res[element.edgeId] == 0 {
				res[element.edgeId] = provider
				provider++
			}
		}
	}

	provider = n - 1
	for i := 1; i < n; i++ {
		if res[i] == 0 {
			res[i] = provider
			provider--
		}
		fmt.Fprintf(writer,"%d\n", res[i] - 1)
	}
}

package main

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

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

type wordScannerImpl struct {
	*bufio.Scanner
}

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

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

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

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

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

type writerImpl struct {
	*bufio.Writer
}

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

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

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

type edge struct {
	a int64
	b int64
}

type counter struct {
	low  int64
	high int64
}

func (c *counter) popHigh() int64 {
	ret := c.high
	c.high--
	return ret
}

func (c *counter) popLow() int64 {
	ret := c.low
	c.low++
	return ret
}

func main() {
	reader := NewWordScanner(os.Stdin)
	writer := NewWriter(os.Stdout)
	defer writer.Flush()
	n := reader.NextInt64()
	ctr := &counter{0, n - 2}
	edges := []edge{}
	counts := map[int64]int64{}
	for i := int64(0); i < n-1; i++ {
		a := reader.NextInt64()
		b := reader.NextInt64()
		edges = append(edges, edge{a, b})
		counts[a]++
		counts[b]++
	}
	for _, e := range edges {
		if counts[e.a] == 1 || counts[e.b] == 1 {
			writer.Printf("%d\n", ctr.popLow())
		} else {
			writer.Printf("%d\n", ctr.popHigh())
		}
	}
}

package main

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

var reader io.Reader
var scanner *bufio.Scanner

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

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

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

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

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

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

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

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

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

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

type Graph struct {
	n     int
	m     int
	edges int
	fst   []int
	nxt   []int
	end   []int
	mark  []int
}

func (g *Graph) Add(a, b int) {
	g.nxt[g.edges] = g.fst[a]
	g.fst[a] = g.edges
	g.end[g.edges] = b
	g.edges++
}

func (g *Graph) Adjacent(a int, fn func(u, to int)) {
	for u := g.fst[a]; u != -1; u = g.nxt[u] {
		fn(u>>1, g.end[u])
	}
}

func NewGraph(n, m int) *Graph {
	mark := make([]int, m)
	for i := 0; i < m; i++ {
		mark[i] = -1
	}
	g := &Graph{n, m, 0, make([]int, n), make([]int, m), make([]int, m), mark}
	for i := 0; i < n; i++ {
		g.fst[i] = -1
	}
	return g
}

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

	n := NextInt()
	g := NewGraph(n, 2*n)
	parent := make([][2]int, n)
	used := make([]bool, n-1)
	color := make([]int, n-1)
	for i := 0; i < n-1; i++ {
		color[i] = -1
		u, v := NextInt()-1, NextInt()-1
		g.Add(u, v)
		g.Add(v, u)
	}
	var dfs func(v int, paru, par, h int) (int, int)
	dfs = func(v int, paru, par, h int) (int, int) {
		parent[v][0] = par
		parent[v][1] = paru
		deepest := v
		height := h
		g.Adjacent(v, func(u, to int) {
			if to == par {
				return
			}
			leaf, leafheight := dfs(to, u, v, h+1)
			if leafheight > height {
				deepest = leaf
				height = leafheight
			}
		})
		return deepest, height
	}

	root, _ := dfs(0, -1, -1, 0)
	leaf, _ := dfs(root, -1, -1, 0)
	// stderr("root", root, "leaf", leaf)

	for t, c := leaf, 2%(n-1); t != root; t, c = parent[t][0], c+1 {
		u := parent[t][1]
		if c == n-1 {
			c = 0
		}
		used[c] = true
		color[u] = c
	}

	for u, c := 0, 0; u < n-1; u++ {
		if color[u] != -1 {
			continue
		}
		for c < n-1 && used[c] {
			c++
		}
		if c == n-1 {
			panic("WTF!")
		}
		color[u] = c
	}

	for i := 0; i < n-1; i++ {
		fmt.Fprintln(out, color[i])
	}
}

package main

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

type Edge struct {
	to int
	w  int
}

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

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

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

	for i := 1; i < n; i++ {
		var f, t int
		fmt.Fscan(r, &f, &t)
		G[f] = append(G[f], Edge{t, i})
		G[t] = append(G[t], Edge{f, i})
	}

	cnt := 1
	res := make([]int, n+1)
	for i := 1; i < n; i++ {
		if len(G[i]) > 2 {
			for _, v := range G[i] {
				res[v.w] = cnt
				cnt++
			}
		}
	}
	for i := 1; i < n; i++ {
		if res[i] == 0 {
			res[i] = cnt
			cnt++
		}
		fmt.Fprint(w, res[i]-1, "\n")
	}

}

package main

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

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

	var n, v, w int
	Fscan(in, &n)
	g := make([][]int, n)
	edgeI := make([]int, n)
	for i := 0; i < n-1; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
		edgeI[v] = i
		edgeI[w] = i
	}
	ans := make([]int, n-1)
	label := 1
	for v, vs := range g {
		if len(vs) == 1 {
			ans[edgeI[v]] = label
			label++
		}
	}
	for i, v := range ans {
		if v == 0 {
			ans[i] = label
			label++
		}
	}
	for _, v := range ans {
		Fprintln(out, v-1)
	}
}

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

package main

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

const N  = 100100

type EdgeInfo struct {
	nxt int
	edgeId int
}

var adj [][]EdgeInfo

var res [N] int
var deg [N] int

func main()  {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var n int
	fmt.Fscanf(reader,"%d\n", &n)

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

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

	var provider = 1
	for i := 1; i < n; i++ {
		for _, element := range adj[i] {
			if deg[element.nxt] == 1 && res[element.edgeId] == 0 {
				res[element.edgeId] = provider
				provider++
			}
		}
	}

	provider = n - 1
	for i := 1; i < n; i++ {
		if res[i] == 0 {
			res[i] = provider
			provider--
		}
		fmt.Fprintf(writer,"%d\n", res[i] - 1)
	}
}

package main

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

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

type wordScannerImpl struct {
	*bufio.Scanner
}

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

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

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

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

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

type writerImpl struct {
	*bufio.Writer
}

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

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

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

type edge struct {
	a int64
	b int64
}

type counter struct {
	low  int64
	high int64
}

func (c *counter) popHigh() int64 {
	ret := c.high
	c.high--
	return ret
}

func (c *counter) popLow() int64 {
	ret := c.low
	c.low++
	return ret
}

func main() {
	reader := NewWordScanner(os.Stdin)
	writer := NewWriter(os.Stdout)
	defer writer.Flush()
	n := reader.NextInt64()
	ctr := &counter{0, n - 2}
	edges := []edge{}
	counts := map[int64]int64{}
	for i := int64(0); i < n-1; i++ {
		a := reader.NextInt64()
		b := reader.NextInt64()
		edges = append(edges, edge{a, b})
		counts[a]++
		counts[b]++
	}
    writer.Printf("%v\n", counts)
	for _, e := range edges {
		if counts[e.a] == 1 || counts[e.b] == 1 {
			writer.Printf("%d\n", ctr.popLow())
		} else {
			writer.Printf("%d\n", ctr.popHigh())
		}
	}
}


The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect $$$k$$$-ary tree if each vertex is either a leaf (has no children) or has exactly $$$k$$$ children. Also, in perfect $$$k$$$-ary tree all leafs must have same depth.For example, the picture below illustrates perfect binary tree with $$$15$$$ vertices:There is a perfect $$$k$$$-ary tree with $$$n$$$ nodes. The nodes are labeled with distinct integers from $$$1$$$ to $$$n$$$, however you don't know how nodes are labelled. Still, you want to find the label of the root of the tree.You are allowed to make at most $$$60 \cdot n$$$ queries of the following type:  "? $$$a$$$ $$$b$$$ $$$c$$$", the query returns "Yes" if node with label $$$b$$$ lies on the path from $$$a$$$ to $$$c$$$ and "No" otherwise. Both $$$a$$$ and $$$c$$$ are considered to be lying on the path from $$$a$$$ to $$$c$$$.When you are ready to report the root of the tree, print   "! $$$s$$$", where $$$s$$$ is the label of the root of the tree. It is possible to report the root only once and this query is not counted towards limit of $$$60 \cdot n$$$ queries.

NoteThe tree in the example is as follows:The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity).The hack corresponding to the example would look like:3 22 3 1

package main

import (
	"fmt"
	"math/rand"
)

var mem = make(map[[3]int]bool)

func query(a, b, c int) bool {
	if a == b || b == c {
		return true
	}
	if a == c {
		return false
	}
	if a > c {
		a, c = c, a
	}
	key := [3]int{a, b, c}
	if r, ok := mem[key]; ok {
		return r
	}
	fmt.Println("?", a, b, c)
	var resp string
	fmt.Scan(&resp)
	res := resp == "Yes"
	mem[key] = res
	return res
}

var isLeaf = make(map[int]bool)

var n int

func checkLeaf(l int) bool {
	v := 1
	if l == 1 {
		v = 2
	}
	for i := 1; i <= n; i++ {
		if i == v || i == l {
			continue
		}
		if query(v, l, i) {
			return false
		}
	}
	return true
}

func between(a, c int) []int {
	var res []int
	for i := 1; i <= n; i++ {
		if i == a || i == c {
			continue
		}
		if query(a, i, c) {
			res = append(res, i)
		}
	}
	return res
}

func main() {
	var k int
	fmt.Scan(&n, &k)
	maxPathLen := 1
	for x := n; x > 1; maxPathLen += 2 {
		x = (x - 1) / k
	}
	var l1 int
	for !isLeaf[l1] {
		l1 = rand.Intn(n) + 1
		if _, ok := isLeaf[l1]; ok {
			continue
		}
		isLeaf[l1] = checkLeaf(l1)
	}

	var l2 int
	for {
		l2 = 0
		for !isLeaf[l2] {
			l2 = rand.Intn(n) + 1
			if _, ok := isLeaf[l2]; ok {
				continue
			}
			isLeaf[l2] = checkLeaf(l2)
		}
		if len(between(l1, l2))+2 != maxPathLen {
			continue
		}
		break
	}

	b := between(l1, l2)
	fmt.Println("!", findNth(b, l1, len(b)/2))
}

func findNth(b []int, l, nth int) int {
	if len(b) == 1 {
		return b[0]
	}
	var tr, fl []int
	for _, v := range b[1:] {
		if query(l, b[0], v) {
			tr = append(tr, v)
		} else {
			fl = append(fl, v)
		}
	}
	if len(tr) == nth {
		return b[0]
	}
	if len(tr) < nth {
		return findNth(fl, l, nth-len(tr)-1)
	}
	return findNth(tr, l, nth)
}


Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened.Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door.There are $$$n$$$ lamps with Spirit Tree's light. Sein knows the time of turning on and off for the $$$i$$$-th lamp — $$$l_i$$$ and $$$r_i$$$ respectively. To open the door you have to choose $$$k$$$ lamps in such a way that there will be a moment of time when they all will be turned on.While Sein decides which of the $$$k$$$ lamps to pick, Ori is interested: how many ways there are to pick such $$$k$$$ lamps that the door will open? It may happen that Sein may be wrong and there are no such $$$k$$$ lamps. The answer might be large, so print it modulo $$$998\,244\,353$$$.

First line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 3 \cdot 10^5$$$, $$$1 \le k \le n$$$) — total number of lamps and the number of lamps that must be turned on simultaneously. Next $$$n$$$ lines contain two integers $$$l_i$$$ ans $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) — period of time when $$$i$$$-th lamp is turned on.

Print one integer — the answer to the task modulo $$$998\,244\,353$$$.

package main

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

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

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

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

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

var err error

func next() (n string) {
	scan(&n)
	return n
}

func nextInt() (n int) {
	scan(&n)
	return n
}

func nextLong() (n int64) {
	scan(&n)
	return n
}

func nextDouble() (n float64) {
	scan(&n)
	return n
}

func Max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

const mod = 998244353

func add(a, b int64) int64 {
	return (a + b) % mod
}

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

func mult(a, b int64) int64 {
	return (a * b) % mod
}

func pow(a, b int64) int64 {
	if b == 0 {
		return 1
	}
	res := pow(a, b>>1)
	res = mult(res, res)
	if b&1 == 1 {
		res = mult(res, a)
	}
	return res
}

var fact, invs []int64

func choose(n, k int) int64 {
	return mult(fact[n], mult(invs[k], invs[n-k]))
}

func solve() {
	n, k := nextInt(), nextInt()
	fact, invs = make([]int64, n+1), make([]int64, n+1)

	fact[0] = 1
	for i := 1; i <= n; i++ {
		fact[i] = mult(fact[i-1], int64(i))
	}
	invs[n] = pow(fact[n], mod-2)
	for i := n - 1; i >= 0; i-- {
		invs[i] = mult(invs[i+1], int64(i+1))
	}

	events := [][2]int{}
	for i := 0; i < n; i++ {
		events = append(events, [2]int{nextInt(), 1})
		events = append(events, [2]int{nextInt(), -1})
	}

	sort.Slice(events, func(a, b int) bool {
		return events[a][0] < events[b][0]
	})

	var res int64 = 0
	tot := 0

	for len(events) > 0 {
		a, b := 0, 0
		curr := events[0][0]
		for len(events) > 0 && events[0][0] == curr {
			if events[0][1] == 1 {
				b++
			} else {
				a++
			}
			events = events[1:]
		}
		if tot+b >= k {
			res = add(res, choose(tot+b, k))
		}
		if tot >= k {
			res = sub(res, choose(tot, k))
		}
		tot += b
		tot -= a
	}
	printf("%d\n", res)
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	if false {
		name := "in"
		file1, err := os.Open(name + ".in")
		if err != nil {
			log.Fatal(err)
		}
		file2, err := os.Create(name + ".out")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file1, 8192)
		out = bufio.NewWriterSize(file2, 8192)
	}
	defer out.Flush()
	// start := time.Now()

	// for t, i := nextInt(), 1; t > 0; t, i = t-1, i+1 {
	// printf("Case #%d:\n", i)
	solve()
	// }

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

package main

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

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

	n, k := readTwoNums(reader)

	lamps := make([][]int, n)

	for i := 0; i < n; i++ {
		lamps[i] = readNNums(reader, 2)
	}

	fmt.Println(solve(n, k, lamps))
}

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

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

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

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

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

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

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

	return i
}

const MOD = 998244353

const MAX_N = 300010

var fact []int64

var ifact []int64

func init() {
	fact = make([]int64, MAX_N+1)
	ifact = make([]int64, MAX_N+1)

	fact[0] = 1
	for i := 1; i <= MAX_N; i++ {
		fact[i] = (fact[i-1] * int64(i)) % MOD
	}

	ifact[MAX_N] = inverse(fact[MAX_N])

	for i := MAX_N; i > 0; i-- {
		ifact[i-1] = (int64(i) * ifact[i]) % MOD
	}
}

func nCr(n int, r int) int64 {
	res := (ifact[r] * ifact[n-r]) % MOD
	res *= fact[n]
	return res % MOD
}

func inverse(q int64) int64 {
	return pow(q, MOD-2)
}

func pow(a, b int64) int64 {
	r := int64(1)

	for b > 0 {
		if b&1 == 1 {
			r = (r * a) % MOD
		}
		a = (a * a) % MOD
		b >>= 1
	}
	return r
}

func solve(n, k int, lamps [][]int) int {
	pp := make([]int, 0, n*2)

	for _, lamp := range lamps {
		l, r := lamp[0], lamp[1]
		pp = append(pp, l)
		pp = append(pp, r)
	}
	sort.Ints(pp)
	ii := make(map[int]int)
	var p int
	for i := 0; i < len(pp); i++ {
		if _, found := ii[pp[i]]; !found {
			ii[pp[i]] = p
			p++
		}
	}
	ls := make([]Lamp, n)
	for i := 0; i < n; i++ {
		ls[i] = Lamp{ii[lamps[i][0]], ii[lamps[i][1]]}
	}

	sort.Sort(Lamps(ls))

	sum := make([]int, p+1)
	var res int64
	for i, j := 0, 0; i <= p && j < n; i++ {
		if i > 0 {
			sum[i] += sum[i-1]
		}
		if i < ls[j].on {
			continue
		}
		// i == ls[j].on
		for j < n && i == ls[j].on {
			sum[i]++
			sum[ls[j].off+1]--
			if sum[i] >= k {
				// take another k - 1 besides j
				res += nCr(sum[i]-1, k-1)
				res %= MOD
			}
			j++
		}
	}

	return int(res)
}

type Lamp struct {
	on  int
	off int
}

type Lamps []Lamp

func (ls Lamps) Len() int {
	return len(ls)
}

func (ls Lamps) Less(i, j int) bool {
	return ls[i].on < ls[j].on || ls[i].on == ls[j].on && ls[i].off > ls[j].off
}

func (ls Lamps) Swap(i, j int) {
	ls[i], ls[j] = ls[j], ls[i]
}

package main

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

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

	n, k := readTwoNums(reader)

	lamps := make([][]int, n)

	for i := 0; i < n; i++ {
		lamps[i] = readNNums(reader, 2)
	}

	fmt.Println(solve(n, k, lamps))
}

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

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

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

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

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

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

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

	return i
}

const MOD = 998244353

const MAX_N = 300010

var fact []int64

var ifact []int64

func init() {
	fact = make([]int64, MAX_N+1)
	ifact = make([]int64, MAX_N+1)

	fact[0] = 1
	for i := 1; i <= MAX_N; i++ {
		fact[i] = (fact[i-1] * int64(i)) % MOD
	}

	ifact[MAX_N] = inverse(fact[MAX_N])

	for i := MAX_N; i > 0; i-- {
		ifact[i-1] = (int64(i) * ifact[i]) % MOD
	}
}

func nCr(n int, r int) int64 {
	if n < r {
		return 0
	}
	res := (ifact[r] * ifact[n-r]) % MOD
	res *= fact[n]
	return res % MOD
}

func inverse(q int64) int64 {
	return pow(q, MOD-2)
}

func pow(a, b int64) int64 {
	r := int64(1)

	for b > 0 {
		if b&1 == 1 {
			r = (r * a) % MOD
		}
		a = (a * a) % MOD
		b >>= 1
	}
	return r
}

func solve(n, k int, lamps [][]int) int {
	events := make([]int, 0, 2*n)

	for i := 0; i < n; i++ {
		cur := lamps[i]
		events = append(events, cur[0]*2)
		events = append(events, cur[1]*2+1)
	}
	var res int64
	sort.Ints(events)
	var on int
	for i := 0; i < len(events); {
		j := i
		for i < len(events) && events[j] == events[i] {
			i++
		}
		added := i - j
		if events[j]%2 == 0 {
			// on events
			res += nCr(on+added, k)
			res %= MOD
			res += MOD - nCr(on, k)
			res %= MOD
			on += added
		} else {
			on -= added
		}
	}

	return int(res)
}

func solve1(n, k int, lamps [][]int) int {
	pp := make([]int, 0, n*2)

	for _, lamp := range lamps {
		l, r := lamp[0], lamp[1]
		pp = append(pp, l)
		pp = append(pp, r)
	}
	sort.Ints(pp)
	ii := make(map[int]int)
	var p int
	for i := 0; i < len(pp); i++ {
		if _, found := ii[pp[i]]; !found {
			ii[pp[i]] = p
			p++
		}
	}
	ls := make([]Lamp, n)
	for i := 0; i < n; i++ {
		ls[i] = Lamp{ii[lamps[i][0]], ii[lamps[i][1]]}
	}

	sort.Sort(Lamps(ls))

	sum := make([]int, p+1)
	var res int64
	for i, j := 0, 0; i <= p && j < n; i++ {
		if i > 0 {
			sum[i] += sum[i-1]
		}
		if i < ls[j].on {
			continue
		}
		// i == ls[j].on
		for j < n && i == ls[j].on {
			sum[i]++
			sum[ls[j].off+1]--
			if sum[i] >= k {
				// take another k - 1 besides j
				res += nCr(sum[i]-1, k-1)
				res %= MOD
			}
			j++
		}
	}

	return int(res)
}

type Lamp struct {
	on  int
	off int
}

type Lamps []Lamp

func (ls Lamps) Len() int {
	return len(ls)
}

func (ls Lamps) Less(i, j int) bool {
	return ls[i].on < ls[j].on || ls[i].on == ls[j].on && ls[i].off > ls[j].off
}

func (ls Lamps) Swap(i, j int) {
	ls[i], ls[j] = ls[j], ls[i]
}


Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are $$$n$$$ players arranged in a circle, so that for all $$$j$$$ such that $$$2 \leq j \leq n$$$, player $$$j - 1$$$ is to the left of the player $$$j$$$, and player $$$j$$$ is to the right of player $$$j - 1$$$. Additionally, player $$$n$$$ is to the left of player $$$1$$$, and player $$$1$$$ is to the right of player $$$n$$$.Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either $$$0$$$, $$$1$$$, or $$$2$$$ other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly $$$1$$$ other player, then they should logically attack that player in response. If instead a player is being attacked by $$$0$$$ or $$$2$$$ other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the $$$n$$$ players in the game to make them instead attack another player  — i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left. Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The descriptions of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$)  — the amount of players (and therefore beds) in this game of Bed Wars. The second line of each test case contains a string $$$s$$$ of length $$$n$$$. The $$$j$$$-th character of $$$s$$$ is equal to L if the $$$j$$$-th player is attacking the player to their left, and R if the $$$j$$$-th player is attacking the player to their right. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer: the minimum number of players Omkar needs to talk to to make it so that all players are acting logically according to Bed Wars strategy. It can be proven that it is always possible for Omkar to achieve this under the given constraints.

5
4
RLRL
6
LRRRRL
8
RLLRRRLL
12
LLLLRRLRRRLL
5
RRRRR

NoteIn the first test case, players $$$1$$$ and $$$2$$$ are attacking each other, and players $$$3$$$ and $$$4$$$ are attacking each other. Each player is being attacked by exactly $$$1$$$ other player, and each player is attacking the player that is attacking them, so all players are already being logical according to Bed Wars strategy and Omkar does not need to talk to any of them, making the answer $$$0$$$.In the second test case, not every player acts logically: for example, player $$$3$$$ is attacked only by player $$$2$$$, but doesn't attack him in response. Omkar can talk to player $$$3$$$ to convert the attack arrangement to LRLRRL, in which you can see that all players are being logical according to Bed Wars strategy, making the answer $$$1$$$.

package main

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

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

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

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

var err error

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

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

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

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

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

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

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

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

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

const (
	oo  = 1000000
	mod = 1000000007
)

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

var (
	adj   [][]int
	depth []int
)

func pow(a, b int64) int64 {
	if b == 0 {
		return 1
	}
	res := pow(a, b/2)
	res = mult(res, res)
	if b%2 == 1 {
		res = mult(res, a)
	}
	return res
}

func solve() {
	n := nextInt()
	arr := make([]int, n)
	{
		s := []byte(next())
		for i, v := range s {
			if v == 'R' {
				arr[i] = 1
			}
		}
	}
	dp := [2][2][2][2][]int{{{{make([]int, n), make([]int, n)}, {make([]int, n), make([]int, n)}},
		{{make([]int, n), make([]int, n)}, {make([]int, n), make([]int, n)}}},
		{{{make([]int, n), make([]int, n)}, {make([]int, n), make([]int, n)}},
			{{make([]int, n), make([]int, n)}, {make([]int, n), make([]int, n)}}}}
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			for k := 0; k < 2; k++ {
				for l := 0; l < 2; l++ {
					dp[i][j][k][l][n-1] = Min(valid(i, j, 0)+valid(j, 0, k)+valid(l, k, 0)+arr[n-1],
						valid(i, j, 1)+valid(j, 1, k)+valid(l, k, 1)+(1^arr[n-1]))
				}
			}
		}
	}

	for i := n - 2; i >= 0; i-- {
		for x := 0; x < 2; x++ {
			for y := 0; y < 2; y++ {
				for z := 0; z < 2; z++ {
					for w := 0; w < 2; w++ {
						dp[x][y][z][w][i] = Min(dp[y][0][z][w][i+1]+valid(x, y, 0)+arr[i],
							dp[y][1][z][w][i+1]+valid(x, y, 1)+(1^arr[i]))
					}
				}
			}
		}
	}

	res := n
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			res = Min(res, dp[i][j][i][j][2]+(i^arr[0])+(j^arr[1]))
		}
	}
	printf("%d\n", res)
}

func valid(a, b, c int) int {
	if a != c || a != b {
		return 0
	}
	return oo
}

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

	// start := time.Now()

	for t, i := nextInt(), 1; t > 0; t, i = t-1, i+1 {
		// printf("Case %d: ", i)
		solve()
	}

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

package main

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

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

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--
		n := readNum(reader)
		S, _ := reader.ReadString('\n')
		res := solve(n, S)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}
	fmt.Print(buf.String())
}

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

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

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

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

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

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

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

	return i
}

const INF = 1000000010

func solve(n int, S string) int {
	dp := make([][]int, n)
	for i := 0; i < n; i++ {
		dp[i] = make([]int, 8)
		for j := 0; j < 8; j++ {
			dp[i][j] = INF
		}
	}

	get := func(i int) int {
		if S[i] == 'L' {
			return 0
		}
		return 1
	}

	valid := func(arr []int) bool {
		for i := 1; i+1 < len(arr); i++ {
			var cnt int
			if arr[i-1] == 1 {
				cnt++
			}
			if arr[i+1] == 0 {
				cnt++
			}
			if cnt == 0 || cnt == 2 {
				continue
			}
			// cnt == 1
			if arr[i-1] == 1 {
				if arr[i] != 0 {
					return false
				}
			}
			if arr[i+1] == 0 {
				if arr[i] != 1 {
					return false
				}
			}
		}
		return true
	}

	valid1 := func(a, b, c int) bool {
		return valid([]int{a, b, c})
	}

	valid2 := func(a, b, c, d int) bool {
		// no RRR no LLL,
		arr := []int{a, b, c, d}
		return valid(arr)
	}

	var best = INF
	for j := 0; j < 8; j++ {
		a, b, c := (j>>2)&1, (j>>1)&1, j&1
		cnt := (a ^ get(0)) + (b ^ get(1)) + (c ^ get(2))

		if valid1(a, b, c) {
			dp[2][j] = cnt
		}
		best = min(best, dp[2][j])
	}

	if n == 3 {
		return best
	}

	best = INF

	for cur := 0; cur < 8; cur++ {
		d0, d1, d2 := (cur>>2)&1, (cur>>1)&1, cur&1
		if !valid1(d0, d1, d2) {
			continue
		}
		for i := 0; i < n; i++ {
			for j := 0; j < 8; j++ {
				dp[i][j] = INF
			}
		}
		cnt := (d0 ^ get(0)) + (d1 ^ get(1)) + (d2 ^ get(2))
		dp[2][cur] = cnt

		for i := 2; i < n-1; i++ {
			for j := 0; j < 8; j++ {
				if dp[i][j] == INF {
					continue
				}
				// valid
				a, b, c := (j>>2)&1, (j>>1)&1, j&1
				for d := 0; d < 2; d++ {
					jj := (j<<1)&7 + d
					if valid2(a, b, c, d) {
						dp[i+1][jj] = min(dp[i+1][jj], dp[i][j]+(get(i+1)^d))
					}
				}
			}
		}
		for j := 0; j < 8; j++ {
			a, b, c := (j>>2)&1, (j>>1)&1, j&1
			if valid2(a, b, c, d0) && valid2(b, c, d0, d1) && valid2(c, d0, d1, d2) {
				best = min(best, dp[n-1][j])
			}
		}
	}

	return best
}

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

package main

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

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

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--
		n := readNum(reader)
		S, _ := reader.ReadString('\n')
		res := solve(n, S)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}
	fmt.Print(buf.String())
}

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

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

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

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

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

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

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

	return i
}

const INF = 1000000010

func solve(n int, S string) int {
	var ok = true
	for i := 1; i < n; i++ {
		if S[i] != S[0] {
			ok = false
			break
		}
	}
	if ok {
		return (n + 2) / 3
	}

	buf := make([]byte, n)
	for i := 1; i < n; i++ {
		if S[i] != S[i-1] {
			copy(buf, S[i:])
			copy(buf[n-i:], S)
			break
		}
	}
	var res int
	var cnt = 1
	for i := 1; i <= n; i++ {
		if i == n || buf[i] != buf[i-1] {
			res += cnt / 3
			cnt = 0
		}
		cnt++
	}
	return res
}

func solve1(n int, S string) int {
	dp := make([][]int, n)
	for i := 0; i < n; i++ {
		dp[i] = make([]int, 8)
		for j := 0; j < 8; j++ {
			dp[i][j] = INF
		}
	}

	get := func(i int) int {
		if S[i] == 'L' {
			return 0
		}
		return 1
	}

	valid := func(arr []int) bool {
		for i := 1; i+1 < len(arr); i++ {
			var cnt int
			if arr[i-1] == 1 {
				cnt++
			}
			if arr[i+1] == 0 {
				cnt++
			}
			if cnt == 0 || cnt == 2 {
				continue
			}
			// cnt == 1
			if arr[i-1] == 1 {
				if arr[i] != 0 {
					return false
				}
			}
			if arr[i+1] == 0 {
				if arr[i] != 1 {
					return false
				}
			}
		}
		return true
	}

	valid1 := func(a, b, c int) bool {
		return valid([]int{a, b, c})
	}

	valid2 := func(a, b, c, d int) bool {
		// no RRR no LLL,
		arr := []int{a, b, c, d}
		return valid(arr)
	}

	var best = INF
	for j := 0; j < 8; j++ {
		a, b, c := (j>>2)&1, (j>>1)&1, j&1
		cnt := (a ^ get(0)) + (b ^ get(1)) + (c ^ get(2))

		if valid1(a, b, c) {
			dp[2][j] = cnt
		}
		best = min(best, dp[2][j])
	}

	if n == 3 {
		return best
	}

	best = INF

	for cur := 0; cur < 8; cur++ {
		d0, d1, d2 := (cur>>2)&1, (cur>>1)&1, cur&1
		if !valid1(d0, d1, d2) {
			continue
		}
		for i := 0; i < n; i++ {
			for j := 0; j < 8; j++ {
				dp[i][j] = INF
			}
		}
		cnt := (d0 ^ get(0)) + (d1 ^ get(1)) + (d2 ^ get(2))
		dp[2][cur] = cnt

		for i := 2; i < n-1; i++ {
			for j := 0; j < 8; j++ {
				if dp[i][j] == INF {
					continue
				}
				// valid
				a, b, c := (j>>2)&1, (j>>1)&1, j&1
				for d := 0; d < 2; d++ {
					jj := (j<<1)&7 + d
					if valid2(a, b, c, d) {
						dp[i+1][jj] = min(dp[i+1][jj], dp[i][j]+(get(i+1)^d))
					}
				}
			}
		}
		for j := 0; j < 8; j++ {
			a, b, c := (j>>2)&1, (j>>1)&1, j&1
			if valid2(a, b, c, d0) && valid2(b, c, d0, d1) && valid2(c, d0, d1, d2) {
				best = min(best, dp[n-1][j])
			}
		}
	}

	return best
}

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

package main

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

// func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
// func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func main() {
	var reader *bufio.Reader = bufio.NewReader(os.Stdin)
	var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var T int
	fmt.Scan(&T)
	var n int
	var s string
	for t := 0; t < T; t++ {
		fmt.Fscan(reader, &n)
		fmt.Fscan(reader, &s)
		start := 0
		for i := 1; i < n; i++ {
			if s[i] != s[i-1] {
				start = i
			}
		}
		ans := 0
		runlen := 1
		for i := 1; i < n; i++ {
			p := (start + i) % n
			prev := (p + n - 1) % n
			if s[p] == s[prev] {
				runlen++
			} else {
				ans += (runlen) / 3
				runlen = 1
			}
		}
		if runlen == n {
			ans += (runlen + 2) / 3
		} else {
			ans += (runlen) / 3
		}
		fmt.Fprintln(writer, ans)
	}
}

package main

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

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

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

	ins := func() []byte {
		sc.Scan()
		return sc.Bytes()
	}

	for t := ini(); t > 0; t-- {
		n := ini()
		s := ins()

		i := 0

		for i < n && s[i] == s[n-1] {
			i++
		}

		if i == n {
			fmt.Println((n + 2) / 3)
			continue
		}

		cnt := 0
		c := 0
		v := 0
		prev := s[i]

		for cnt != n {
			if s[i] == prev {
				v++
			} else {
				v /= 3
				c += v
				prev = s[i]
				v = 1
			}

			cnt++
			i++
			if i == n {
				i = 0
			}
		}
		v /= 3
		c += v

		fmt.Println(c)

	}
}

package main

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

func getLeft(str string, i int) byte {
	if i == 0 {
		return str[len(str)-1]
	}
	return str[i-1]
}

func getRight(str string, i int) byte {
	if i+1 >= len(str) {
		return str[0]
	}
	return str[i+1]
}

func main() {
	in := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var n int
		count := 0
		fmt.Fscan(in, &n)
		var str string
		a := make([]int, n)
		fmt.Fscan(in, &str)
		for j := 0; j < n; j++ {
			if getLeft(str, j) != str[j] || getRight(str, j) != str[j] {
				a[j] = 0
			} else {
				a[j] = 1
			}
		}

		//shift
		start := 0
		end := -1
		for j := 0; j < n; j++ {
			if a[j] == 1 {
				end = j
			} else {
				break
			}
		}
		if end != -1 && end-start+1 < n {
			aStart := a[start : end+1]
			a = a[end+1:]
			a = append(a, aStart...)
		}
		start = -1
		end = -1
		for j := 0; j < n; j++ {
			if a[j] == 1 {
				end = j
				if start == -1 {
					start = j
				}
			}
			if a[j] == 0 && start != -1 {
				amount := end - start + 1
				count += amount / 3
				if amount%3 != 0 {
					count++
				}
				start = -1
				end = -1
			}
		}
		if start != -1 {
			amount := end - start + 1
			count += amount / 3
			if amount%3 != 0 {
				count++
			}
		}
		fmt.Println(count)
	}
}

package main

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

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

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

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

var err error

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

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

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

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

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

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

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

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

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

const (
	oo  = 100000000
	mod = 1000000007
)

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

var (
	adj   [][]int
	depth []int
)

func pow(a, b int64) int64 {
	if b == 0 {
		return 1
	}
	res := pow(a, b/2)
	res = mult(res, res)
	if b%2 == 1 {
		res = mult(res, a)
	}
	return res
}

func solve() {
	n := nextInt()
	arr := make([]int, n)
	{
		s := []byte(next())
		for i, v := range s {
			if v == 'R' {
				arr[i] = 1
			}
		}
	}
	dp := [2][2][2][]int{{{make([]int, n), make([]int, n)}, {make([]int, n), make([]int, n)}},
		{{make([]int, n), make([]int, n)}, {make([]int, n), make([]int, n)}}}
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			for k := 0; k < 2; k++ {
				dp[i][j][k][n-1] = Min(valid(i, j, 0)+valid(j, 0, k)+arr[n-1],
					valid(i, j, 1)+valid(j, 1, k)+(1^arr[n-1]))
			}
		}
	}

	for i := n - 2; i >= 0; i-- {
		for x := 0; x < 2; x++ {
			for y := 0; y < 2; y++ {
				for z := 0; z < 2; z++ {
					dp[x][y][z][i] = Min(dp[y][0][z][i+1]+valid(x, y, 0)+arr[i],
						dp[y][1][z][i+1]+valid(x, y, 1)+(1^arr[i]))
				}
			}
		}
	}

	res := n
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			res = Min(res, dp[i][j][i][2]+(i^arr[0])+(j^arr[1]))
		}
	}
	printf("%d\n", res)
}

func valid(a, b, c int) int {
	if a != c || a != b {
		return 0
	}
	return oo
}

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

	// start := time.Now()

	for t, i := nextInt(), 1; t > 0; t, i = t-1, i+1 {
		// printf("Case %d: ", i)
		solve()
	}

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

package main

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

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

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

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

var err error

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

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

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

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

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

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

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

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

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

const (
	oo  = 100000000
	mod = 1000000007
)

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

var (
	adj   [][]int
	depth []int
)

func pow(a, b int64) int64 {
	if b == 0 {
		return 1
	}
	res := pow(a, b/2)
	res = mult(res, res)
	if b%2 == 1 {
		res = mult(res, a)
	}
	return res
}

func solve() {
	n := nextInt()
	s := []byte(next())
	addL := make([]int, n)
	addR := make([]int, n)
	for i := range addL {
		if s[i] == 'L' {
			addR[i] = 1
		} else {
			addL[i] = 1
		}
	}
	dp := [2][2][]int{{make([]int, n), make([]int, n)}, {make([]int, n), make([]int, n)}}
	if s[n-1] == 'L' {
		dp[0][0][n-1] = 1
	} else {
		dp[1][1][n-1] = 1
	}
	if s[n-2] == 'L' {
		dp[0][0][n-2], dp[0][1][n-2], dp[1][0][n-2], dp[1][1][n-2] = dp[0][0][n-1], 0, dp[0][0][n-1], 0
	} else {
		dp[0][0][n-2], dp[0][1][n-2], dp[1][0][n-2], dp[1][1][n-2] = 0, dp[1][1][n-1], 0, dp[1][1][n-1]
	}
	for i := n - 3; i >= 0; i-- {
		add1, add2 := addL[i], addR[i]
		for j := 0; j < 2; j++ {
			dp[0][j][i] = Min(dp[1][j][i+2]+add1+addR[i+1], dp[1][j][i+1]+add2)
			dp[1][j][i] = Min(dp[0][j][i+1]+add1, dp[0][j][i+2]+add2+addL[i+1])
		}
	}
	printf("%d\n", Min(dp[0][0][1]+addL[0], dp[1][1][1]+addR[0]))
}

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

	// start := time.Now()

	for t, i := nextInt(), 1; t > 0; t, i = t-1, i+1 {
		// printf("Case %d: ", i)
		solve()
	}

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

package main

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

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

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

	ins := func() []byte {
		sc.Scan()
		return sc.Bytes()
	}

	for t := ini(); t > 0; t-- {
		n := ini()
		s := ins()

		c := 0

		for i := 0; i < n; i++ {
			l := i - 1
			r := i + 1

			if l < 0 {
				l = n - 1
			}

			if r == n {
				r = 0
			}

			if s[r] == s[l] && s[l] == s[i] {
				if s[r] == 'L' {
					s[i] = 'R'
				} else {
					s[i] = 'L'
				}
				c++
				i++
			}
		}

		fmt.Println(c)
	}
}

package main

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

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

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

	ins := func() string {
		sc.Scan()
		return sc.Text()
	}

	for t := ini(); t > 0; t-- {
		n := ini()
		s := ins()

		c := 0

		for i := 0; i < n-1; i++ {
			l := i - 1
			r := i + 1

			if l < 0 {
				l = n - 1
			}

			if r == n {
				r = 0
			}

			if s[r] == s[l] && s[l] == s[i] {
				c++
				i++
			}
		}

		fmt.Println(c)
	}
}

package main

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

func getLeft(str string, i int) byte {
	if i == 0 {
		return str[len(str)-1]
	}
	return str[i-1]
}

func getRight(str string, i int) byte {
	if i+1 >= len(str) {
		return str[0]
	}
	return str[i+1]
}

func main() {
	in := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var n int
		count := 0
		fmt.Fscan(in, &n)
		var str string
		a := make([]int, n)
		fmt.Fscan(in, &str)
		for j := 0; j < n; j++ {
			if getLeft(str, j) == 'R' && getRight(str, j) == 'L' {
				a[j] = 0
			} else if getLeft(str, j) == 'L' && getRight(str, j) == 'R' {
				a[j] = 0
			} else if getLeft(str, j) == 'R' && str[j] == 'L' {
				a[j] = 0
			} else if getRight(str, j) == 'L' && str[j] == 'R' {
				a[j] = 0
			} else {
				a[j] = 1
			}
		}

		start := 0
		end := -1
		for j := 0; j < n; j++ {
			if a[j] == 1 {
				end = j
			} else {
				break
			}
		}
		if end-start > 0 && end-start+1 < n {
			aStart := a[start : end+1]
			a = a[end+1:]
			a = append(a, aStart...)
		}

		start = -1
		end = -1
		for j := 0; j < n; j++ {
			if a[j] == 1 {
				end = j
				if start == -1 {
					start = j
				}
			}
			if a[j] == 0 && start != -1 {
				amount := end - start + 1
				if amount == 1 {
					count++
				} else {
					count += amount / 2
				}
				start = -1
				end = -1
			}
		}
		if start != -1 {
			amount := end - start + 1
			if amount == 1 {
				count++
			} else {
				count += amount / 2
			}
		}
		fmt.Println(count)
	}
}

package main

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

func getLeft(str string, i int) byte {
	if i == 0 {
		return str[len(str)-1]
	}
	return str[i-1]
}

func getRight(str string, i int) byte {
	if i+1 >= len(str) {
		return str[0]
	}
	return str[i+1]
}

func main() {
	in := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var n int
		count := 0
		fmt.Fscan(in, &n)
		var str string
		a := make([]int, n)
		fmt.Fscan(in, &str)
		for j := 0; j < n; j++ {
			if getLeft(str, j) == 'R' && getRight(str, j) == 'L' {
				a[j] = 0
			} else if getLeft(str, j) == 'L' && getRight(str, j) == 'R' {
				a[j] = 0
			} else if getLeft(str, j) == 'R' && str[j] == 'L' {
				a[j] = 0
			} else if getRight(str, j) == 'L' && str[j] == 'R' {
				a[j] = 0
			} else {
				a[j] = 1
			}
		}

		start := 0
		end := -1
		for j := 0; j < n; j++ {
			if a[j] == 1 {
				end = j
			} else {
				break
			}
		}
		if end != -1 && end-start+1 < n {
			aStart := a[start : end+1]
			a = a[end+1:]
			a = append(a, aStart...)
		}
		start = -1
		end = -1
		for j := 0; j < n; j++ {
			if a[j] == 1 {
				end = j
				if start == -1 {
					start = j
				}
			}
			if a[j] == 0 && start != -1 {
				amount := end - start + 1
				if amount == 1 {
					count++
				} else {
					count += amount / 2
				}
				start = -1
				end = -1
			}
		}
		if start != -1 {
			amount := end - start + 1
			if amount == 1 {
				count++
			} else {
				count += amount / 2
			}
		}
		fmt.Println(count)
	}
}