A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a, b] covers segment [c, d], if they meet this condition a ≤ c ≤ d ≤ b.

The first line contains integer n (1 ≤ n ≤ 105) — the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ 109) — the borders of the i-th segment. It is guaranteed that no two segments coincide.

Print a single integer — the number of the segment that covers all other segments in the set. If there's no solution, print -1. The segments are numbered starting from 1 in the order in which they appear in the input.

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	var l, r int
	fmt.Fscanf(reader, "%d\n", &n)
	min := math.MaxInt32
	max := math.MinInt32
	c := make(map[int]map[int]int)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &l, &r)
		if min > l {
			min = l
		}
		if max < r {
			max = r
		}
		m, ok := c[l]
		if ok {
			m[r] = i
		} else {
			c[l] = map[int]int{r: i}
		}
	}
	v, ok := c[min][max]
	if ok {
		fmt.Fprint(os.Stdout, v+1)
	} else {
		fmt.Fprint(os.Stdout, -1)
	}
}

package main

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

func main() {
	var n int
	flag:=false
	input := bufio.NewScanner(os.Stdin)
    	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	l:=make([]int,100005)
	r:=make([]int,100005)
	y:=-1
	x:=1000000007
	for i:=1;i<=n;i++ {
		input.Scan()
		aa, _ := strconv.Atoi(input.Text())
		l[i]=aa
		input.Scan()
		bb, _ := strconv.Atoi(input.Text())
		r[i]=bb
		if x>l[i] {
			x=l[i]
		}
		if y<r[i] {
			y=r[i]
		}
	}
	for i:=1;i<=n;i++ {
		if l[i]==x && r[i]==y {
			fmt.Println(i)
			flag=true
			break
		}
	}
	if flag==false {
		fmt.Println(-1)
	}

}

package main

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

func main() {

	var totalCoordinate int
	var segments [][]string
	line := -1

	scanner := bufio.NewScanner(os.Stdin)

	var minL int
	var maxR int
	var bestIndex = 0
	for scanner.Scan() {
		line += 1
		if line == 0 {
			totalCoordinate, _ = strconv.Atoi(scanner.Text())
		} else {
			value := strings.Split(scanner.Text(), " ")
			segments = append(segments, value)
			if line == totalCoordinate {
				break
			}
		}
	}

	for i, v := range segments {
		l, _ := strconv.Atoi(v[0])
		r, _ := strconv.Atoi(v[1])
		if i == 0 {
			minL = l
			maxR = r
			continue
		}
		if l <= minL {
			minL = l
		}
		if r >= maxR {
			maxR = r
		}
		if l <= minL && r >= maxR {
			bestIndex = i
			continue
		}
		if bestIndex == 0 && (l < minL || r > maxR) {
			bestIndex = -1
			continue
		}
	}

	var bestSegment []string
	var l, r int
	if bestIndex == -1 {
		fmt.Println(-1)
	} else {
		bestSegment = segments[bestIndex]
		l, _ = strconv.Atoi(bestSegment[0])
		r, _ = strconv.Atoi(bestSegment[1])
		if l == minL && r == maxR {
			fmt.Println(bestIndex + 1)
		} else {
			fmt.Println(-1)
		}
	}
}

package main

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

func main() {

	var totalCoordinate int
	var segments [][]string
	line := -1

	scanner := bufio.NewScanner(os.Stdin)

	var minL int
	var maxR int
	var bestIndex = 0
	for scanner.Scan() {
		line += 1
		if line == 0 {
			totalCoordinate, _ = strconv.Atoi(scanner.Text())
		} else {
			value := strings.Split(scanner.Text(), " ")
			segments = append(segments, value)
			if line == totalCoordinate {
				break
			}
		}
	}

	for i, v := range segments {
		l, _ := strconv.Atoi(v[0])
		r, _ := strconv.Atoi(v[1])
		if i == 0 {
			minL = l
			maxR = r
			continue
		}
		if l <= minL {
			minL = l
		}
		if r >= maxR {
			maxR = r
		}
		if l <= minL && r >= maxR {
			bestIndex = i
			continue
		}
		if bestIndex == 0 && (l < minL || r > maxR) {
			bestIndex = -1
			continue
		}
	}

	if bestIndex == -1 {
		fmt.Println(-1)
	} else {
		bestSegment := segments[bestIndex]
		l, _ := strconv.Atoi(bestSegment[0])
		r, _ := strconv.Atoi(bestSegment[1])
		if l == minL && r == maxR {
			fmt.Println(bestIndex + 1)
		} else {
			fmt.Println(-1)
		}
	}
}

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

func getMinMax(arr [][]string)(int, int){
	min,_ := strconv.Atoi(arr[0][0])
	max := 0
	for i :=0; i < len(arr); i++{
		left,_ := strconv.Atoi(arr[i][0])
		right,_ := strconv.Atoi(arr[i][1])
		if min > left{
			min = left
		}
		if max < right{
			max = right
		}
	}
	return min,max
}

func main(){
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	sum := scanner.Text()
	intsum,_ := strconv.Atoi(sum)
	var arr [][]string
	for i :=0; i < intsum; i++{
		scanner.Scan()
		a := scanner.Text()
		b := strings.Split(a," ")
		arr = append(arr,b)
	}
	min,max := getMinMax(arr)
	linhCanh := 1
	for i := 0; i < intsum; i++{
		left,_ := strconv.Atoi(arr[i][0])
		right,_ := strconv.Atoi(arr[i][1])
		if min == left{
			if max == right{
				fmt.Println(i+1)
				linhCanh = 0
				break
			}
		}
	}
	if linhCanh == 1{
		fmt.Println(-1)
	}

}

package main

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

type Segment struct {
    l,r int
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    var n int
    fmt.Scan(&n)
    s := make([]Segment,n)
    left, right := 1000000001, 0
    for i := 0; i < n; i++ {
        scanner.Scan()
        s[i].l, _ = strconv.Atoi(scanner.Text())
        scanner.Scan()
        s[i].r, _ = strconv.Atoi(scanner.Text())
        if left > s[i].l { left = s[i].l }
        if right < s[i].r { right = s[i].r }
    }
    ans := -1
    for i := 0; i < n; i++ {
        if (s[i].l == left) && (s[i].r == right) {
            ans = i+1
            break
        }
    }
    fmt.Println(ans)
}

package main

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

func solve(n int, arr [][]int) int {
	min, max := arr[0][0], 0

	for i := range arr {
		if arr[i][0] < min {
			min = arr[i][0]
		}
		if arr[i][1] > max {
			max = arr[i][1]
		}
	}

	for i := range arr {
		if arr[i][0] == min && arr[i][1]== max {
			return i + 1
		}
	}
	return -1
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(r, "%d\n", &n)
	arr := make([][]int, n)

	for i := range arr {
		arr[i] = make([]int, 2)
		fmt.Fscanf(r, "%d %d\n", &arr[i][0], &arr[i][1])
	}

	fmt.Fprintf(os.Stdout, "%d\n", solve(n, arr))
}

package main

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

func main() {
	reader := NewStdReader(os.Stdin)
	n := reader.ReadInt()

	c := -1
	min := 1000000000
	max := 0

	for i := 1; i <= n; i++ {
		L, R := reader.ReadInt(), reader.ReadInt()
		if L <= min && R >= max {
			c = i
			min = L
			max = R
		} else if L < min {
			c = -1
			min = L
		} else if R > max {
			c = -1
			max = R
		}
	}

	fmt.Print(c)
}

type StdReader struct {
	buf *bufio.Reader
}

func NewStdReader(reader io.Reader) *StdReader {
	return &StdReader{bufio.NewReaderSize(reader, 2*1024*1024)}
}

func (std *StdReader) ReadInt() int {

	r := 0
	sign := 1
	ok := false

	for {
		b, e := std.buf.ReadByte()

		if e != nil {
			break
		}
		if b >= '0' && b <= '9' {
			r = r*10 + int(b-'0')
			ok = true
		} else {
			if ok {
				break
			} else {
				if b == '-' {
					sign = -sign
				}
			}
		}
	}

	return sign * r
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	var l, r int
	fmt.Fscanf(reader, "%d\n", &n)
	min := math.MaxInt32
	max := math.MinInt32
	c := make(map[int]map[int]int)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &l, &r)
		if min > l {
			min = l
		}
		if max < r {
			max = r
		}
		m, ok := c[l]
		if ok {
			m[r] = i
		} else {
			c[l] = map[int]int{r: i}
		}
	}
	v, ok := c[min][max]
	if ok {
		fmt.Fprint(os.Stdout, v)
	} else {
		fmt.Fprint(os.Stdout, -1)
	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	var l, r int
	fmt.Fscanf(reader, "%d\n", &n)
	min := math.MaxInt32
	max := math.MinInt32
	c := make(map[int]map[int]int)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &l, &r)
		if min > l {
			min = l
		}
		if max < r {
			max = r
		}
		m, ok := c[l]
		if ok {
			m[r] = i
		} else {
			c[l] = map[int]int{r: i}
		}
	}
	v, ok := c[min][max]
	if ok {
		fmt.Fprint(os.Stdout, -1)
	} else {
		fmt.Fprint(os.Stdout, v)
	}
}

package main

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

func main() {
	var n int
	flag:=false
	input := bufio.NewScanner(os.Stdin)
    	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	l:=make([]int,n+1)
	r:=make([]int,n+1)
	y:=-1
	x:=10000007
	for i:=1;i<=n;i++ {
		input.Scan()
		aa, _ := strconv.Atoi(input.Text())
		l[i]=aa
		input.Scan()
		bb, _ := strconv.Atoi(input.Text())
		r[i]=bb
		if x>l[i] {
			x=l[i]
		}
		if y<r[i] {
			y=r[i]
		}
	}
	for i:=1;i<=n;i++ {
		if l[i]==x && r[i]==y {
			fmt.Println(i)
			flag=true
			break
		}
	}
	if flag==false {
		fmt.Println(-1)
	}

}

package main

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

func main() {
	var n int
	flag:=false
	input := bufio.NewScanner(os.Stdin)
    	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	l:=make([]int,n+1)
	r:=make([]int,n+1)
	y:=-1
	x:=100000001
	for i:=1;i<=n;i++ {
		input.Scan()
		aa, _ := strconv.Atoi(input.Text())
		l[i]=aa
		input.Scan()
		bb, _ := strconv.Atoi(input.Text())
		r[i]=bb
		if x>l[i] {
			x=l[i]
		}
		if y<r[i] {
			y=r[i]
		}
	}
	for i:=1;i<=n;i++ {
		if l[i]==x && r[i]==y {
			fmt.Println(i)
			flag=true
			break
		}
	}
	if flag==false {
		fmt.Println(-1)
	}

}

package main

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

func main() {
	var n int
	flag:=false
	input := bufio.NewScanner(os.Stdin)
    	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	l:=make([]int,n+1)
	r:=make([]int,n+1)
	y:=-1
	x:=100000007
	for i:=1;i<=n;i++ {
		input.Scan()
		aa, _ := strconv.Atoi(input.Text())
		l[i]=aa
		input.Scan()
		bb, _ := strconv.Atoi(input.Text())
		r[i]=bb
		if x>l[i] {
			x=l[i]
		}
		if y<r[i] {
			y=r[i]
		}
	}
	for i:=1;i<=n;i++ {
		if l[i]==x && r[i]==y {
			fmt.Println(i)
			flag=true
			break
		}
	}
	if flag==false {
		fmt.Println(-1)
	}

}

package main

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

func main() {

	var totalCoordinate int
	var segments [][]string
	line := -1

	scanner := bufio.NewScanner(os.Stdin)

	var bestResult [2]int
	var bestIndex = 0
	for scanner.Scan() {
		line += 1
		if line == 0 {
			totalCoordinate, _ = strconv.Atoi(scanner.Text())
		} else {
			value := strings.Split(scanner.Text(), " ")
			segments = append(segments, value)
			if line == totalCoordinate {
				break
			}
		}
	}

	for i, v := range segments {
		l, _ := strconv.Atoi(v[0])
		r, _ := strconv.Atoi(v[1])
		if i == 0 {
			bestResult[0] = l
			bestResult[1] = r
			continue
		}
		if l <= bestResult[0] && r >= bestResult[1] {
			bestResult[0] = l
			bestResult[1] = r
			bestIndex = i
			continue
		}
		if bestIndex == 0 && (l > bestResult[0] || r < bestResult[1]) {
			bestIndex = -1
			continue
		}
	}

	if bestIndex == -1 {
		fmt.Println(-1)
	} else {
		fmt.Println(bestIndex + 1)
	}
}

package main

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

func main() {

	var totalCoordinate int
	var segments [][]string
	line := -1

	scanner := bufio.NewScanner(os.Stdin)

	var minL int
	var maxR int
	var bestIndex = 0
	for scanner.Scan() {
		line += 1
		if line == 0 {
			totalCoordinate, _ = strconv.Atoi(scanner.Text())
		} else {
			value := strings.Split(scanner.Text(), " ")
			segments = append(segments, value)
			if line == totalCoordinate {
				break
			}
		}
	}

	for i, v := range segments {
		l, _ := strconv.Atoi(v[0])
		r, _ := strconv.Atoi(v[1])
		if i == 0 {
			minL = l
			maxR = r
			continue
		}
		if l <= minL {
			minL = l
		}
		if r >= maxR {
			maxR = r
		}
		if l <= minL && r >= maxR {
			bestIndex = i
			continue
		}
		if bestIndex == 0 && (l < minL || r > maxR) {
			bestIndex = -1
			continue
		}
	}

	if bestIndex == 0 {
		segmentZero := segments[0]
		l, _ := strconv.Atoi(segmentZero[0])
		r, _ := strconv.Atoi(segmentZero[1])
		if l == minL && r == maxR {
			fmt.Println(0)
		} else {
			fmt.Println(-1)
		}
	} else {
		if bestIndex == -1 {
			fmt.Println(-1)
		} else {
			fmt.Println(bestIndex + 1)
		}
	}
}

package main

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

func main() {

	var totalCoordinate int
	var segments [][]string
	line := -1

	scanner := bufio.NewScanner(os.Stdin)

	var minL int
	var maxR int
	var bestIndex = 0
	for scanner.Scan() {
		line += 1
		if line == 0 {
			totalCoordinate, _ = strconv.Atoi(scanner.Text())
		} else {
			value := strings.Split(scanner.Text(), " ")
			segments = append(segments, value)
			if line == totalCoordinate {
				break
			}
		}
	}

	for i, v := range segments {
		l, _ := strconv.Atoi(v[0])
		r, _ := strconv.Atoi(v[1])
		if i == 0 {
			minL = l
			maxR = r
			continue
		}
		if l <= minL {
			minL = l
		}
		if r >= maxR {
			maxR = r
		}
		if l <= minL && r >= maxR {
			bestIndex = i
			continue
		}
		if bestIndex == 0 && (l < minL || r > maxR) {
			bestIndex = -1
			continue
		}
	}

	if bestIndex == 0 {
		segmentZero := segments[0]
		l, _ := strconv.Atoi(segmentZero[0])
		r, _ := strconv.Atoi(segmentZero[1])
		if l == minL && r == maxR {
			fmt.Println(1)
		} else {
			fmt.Println(-1)
		}
	} else {
		if bestIndex == -1 {
			fmt.Println(-1)
		} else {
			fmt.Println(bestIndex + 1)
		}
	}
}

package main

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

func main() {

	var totalCoordinate int
	var segments [][]string
	line := -1

	scanner := bufio.NewScanner(os.Stdin)

	var minL int
	var maxR int
	var bestIndex = 0
	for scanner.Scan() {
		line += 1
		if line == 0 {
			totalCoordinate, _ = strconv.Atoi(scanner.Text())
		} else {
			value := strings.Split(scanner.Text(), " ")
			segments = append(segments, value)
			if line == totalCoordinate {
				break
			}
		}
	}

	for i, v := range segments {
		l, _ := strconv.Atoi(v[0])
		r, _ := strconv.Atoi(v[1])
		if i == 0 {
			minL = l
			maxR = r
			continue
		}
		if l <= minL {
			minL = l
		}
		if r >= maxR {
			maxR = r
		}
		if l <= minL && r >= maxR {
			bestIndex = i
			continue
		}
		if bestIndex == 0 && (l < minL || r > maxR) {
			bestIndex = -1
			continue
		}
	}

	if bestIndex == -1 {
		fmt.Println(-1)
	} else {
		fmt.Println(bestIndex + 1)
	}
}

package main

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

func main() {

	var totalCoordinate int
	var segments [][]string
	line := -1

	scanner := bufio.NewScanner(os.Stdin)

	var bestResult [2]int
	var bestIndex = 0
	for scanner.Scan() {
		line += 1
		if line == 0 {
			totalCoordinate, _ = strconv.Atoi(scanner.Text())
		} else {
			value := strings.Split(scanner.Text(), " ")
			segments = append(segments, value)
			if line == totalCoordinate {
				break
			}
		}
	}

	for i, v := range segments {
		l, _ := strconv.Atoi(v[0])
		r, _ := strconv.Atoi(v[1])
		if i == 0 {
			bestResult[0] = l
			bestResult[1] = r
			continue
		}
		if l <= bestResult[0] && r >= bestResult[1] {
			bestResult[0] = l
			bestResult[1] = r
			bestIndex = i
			continue
		}
		if bestIndex == 0 && (l < bestResult[0] || r > bestResult[1]) {
			bestIndex = -1
			continue
		}
	}

	if bestIndex == -1 {
		fmt.Println(-1)
	} else {
		fmt.Println(bestIndex + 1)
	}
}


Polycarpus is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array a for all indexes in the segment [l, r]. In other words, this function does the following: function rangeIncrement(l, r)    for i := l .. r do        a[i] = a[i] + 1Polycarpus knows the state of the array a after a series of function calls. He wants to determine the minimum number of function calls that lead to such state. In addition, he wants to find what function calls are needed in this case. It is guaranteed that the required number of calls does not exceed 105.Before calls of function rangeIncrement(l, r) all array elements equal zero.

The first input line contains a single integer n (1 ≤ n ≤ 105) — the length of the array a[1... n].  The second line contains its integer space-separated elements, a[1], a[2], ..., a[n] (0 ≤ a[i] ≤ 105) after some series of function calls rangeIncrement(l, r).  It is guaranteed that at least one element of the array is positive. It is guaranteed that the answer contains no more than 105 calls of function rangeIncrement(l, r).

Print on the first line t — the minimum number of calls of function rangeIncrement(l, r), that lead to the array from the input data. It is guaranteed that this number will turn out not more than 105. Then print t lines — the descriptions of function calls, one per line. Each line should contain two integers li, ri (1 ≤ li ≤ ri ≤ n) — the arguments of the i-th call rangeIncrement(l, r). Calls can be applied in any order. If there are multiple solutions, you are allowed to print any of them.

NoteThe first sample requires a call for the entire array, and four additional calls:  one for the segment [2,2] (i.e. the second element of the array),  three for the segment [5,5] (i.e. the fifth element of the array).

package main

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

const N = 100010
var n int
var x int

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

	var workers = make([]int, N)
	var from = make([]int, 0)
	var to = make([]int, 0)

	for i := 1; i <= n; i++ {
		fmt.Fscanf(reader, "%d", &x)

		if x > cur {
			tot += x - cur
			// new
			for j := 0; j < x - cur; j++ {
				from = append(from, i)
				to = append(to, 0) // not end yet
				workers[cur + j] = len(from) - 1
			}
		} else {
			// remove
			var out = cur - x

			for j := 0; j < out; j++ {
				to[workers[cur - 1 - j]] = i - 1
			}
		}
		cur = x
	}

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

	fmt.Fprintf(writer, "%d\n", tot)

	for i := 0; i < tot; i++{
		fmt.Fprintf(writer, "%d %d\n", from[i], to[i])
	}
}

// Author: sighduck
// URL: https://codeforces.com/contest/174/problem/C

package main

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

type Call struct {
	L int
	R int
}

func Solve(n int, a []int) []Call {
	left := []int{}
	calls := []Call{}
	for i := 1; i <= n+1; i++ {
		for j := 0; j < a[i]-a[i-1]; j++ {
			left = append(left, i)
		}
		for j := 0; j < a[i-1]-a[i]; j++ {
			calls = append(calls, Call{L: left[len(left)-1], R: i - 1})
			left = left[:len(left)-1]
		}
	}
	return calls
}

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

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

	calls := Solve(n, a)
	fmt.Fprintf(writer, "%d\n", len(calls))
	for i := 0; i < len(calls); i++ {
		fmt.Fprintf(writer, "%d %d\n", calls[i].L, calls[i].R)
	}
}


One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows:  two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$;  two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:  admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";  admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.

The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters.

In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.

NoteIn the second example hacker need to use any of the passwords to access the system.

package main

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

type Node struct {
	neighs []string
}

var m map[string]*Node
var st map[string]bool

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

func dfs(curr string, m map[string]*Node) {

	_, ok := st[curr]
	if ok {
		return
	}

	st[curr] = true
	for _, neigh := range m[curr].neighs {
		dfs(neigh, m)
	}
}

func main() {
	defer writer.Flush()
	m = make(map[string]*Node)
	st = make(map[string]bool)
	var ls []string
	var n int
	scanf("%d\n", &n)
	for i := 0; i < n; i++ {
		var input string
		scanf("%s\n", &input)

		ls = append(ls, input)
		_, inside := m[input]
		if !inside {
			m[input] = &Node{}
		}

		for _, c := range input {
			target := string(c)
			_, inside := m[target]
			if !inside {
				m[target] = &Node{}
			}

			m[input].neighs = append(m[input].neighs, target)
			m[target].neighs = append(m[target].neighs, input)
		}
	}

	ans := 0
	for _, inp := range ls {
		_, inside := st[inp]
		if !inside {
			dfs(inp, m)
			ans += 1
		}
	}

	printf("%d\n", ans)

}

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

	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
}

/*********** DP sub-functions ***********/

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

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

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

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

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

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// 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 int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	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 int) int {
	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
}

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

/********** 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 MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n int
var S [][]rune

var memo [30][]int

func main() {
	n = ReadInt()
	S = make([][]rune, n)
	for i := 0; i < n; i++ {
		S[i] = ReadRuneSlice()
	}

	for i := 0; i < n; i++ {
		for _, r := range S[i] {
			tmp := r - 'a'
			memo[tmp] = append(memo[tmp], i)
		}
	}

	uf := NewUnionFind(n)

	for i := 0; i < ALPHABET_NUM; i++ {
		if len(memo[i]) == 0 {
			continue
		}

		top := memo[i][0]
		for j := 1; j < len(memo[i]); j++ {
			uf.Unite(top, memo[i][j])
		}
	}

	fmt.Println(uf.CcNum())
}

// UnionFind provides disjoint set algorithm.
// It accepts both 0-based and 1-based setting.
type UnionFind struct {
	parents []int
}

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

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

	return uf
}

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

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

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

	if xp == yp {
		return false
	}

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

	return true
}

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

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

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

/*
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
*/

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

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

	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
}

/*********** DP sub-functions ***********/

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

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

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

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

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

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// 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 int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	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 int) int {
	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
}

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

/********** 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 MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n int
var S [][]rune

var memo [30][]int

func main() {
	n = ReadInt()
	S = make([][]rune, n)
	for i := 0; i < n; i++ {
		S[i] = ReadRuneSlice()
	}

	for i := 0; i < n; i++ {
		for _, r := range S[i] {
			tmp := r - 'a'
			memo[tmp] = append(memo[tmp], i)
		}
	}

	uf := NewUnionFind(n)

	for i := 0; i < ALPHABET_NUM; i++ {
		if len(memo[i]) == 0 {
			continue
		}

		top := memo[i][0]
		for j := 1; j < len(memo[i]); j++ {
			uf.Unite(top, memo[i][j])
		}
	}

	fmt.Println(uf.CcNum())
}

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

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

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

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

	return uf
}

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

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

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

	if xp == yp {
		return false
	}

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

	return true
}

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

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

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

/*
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
*/

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1263D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	fa := [26]byte{}
	for i := range fa {
		fa[i] = byte(i)
	}
	var find func(byte) byte
	find = func(x byte) byte {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(from, to byte) { fa[find(from)] = find(to) }

	var n, cnt int
	var s []byte
	shown := [26]bool{}
	for Fscan(in, &n); n > 0; n-- {
		Fscan(in, &s)
		h := s[0] - 'a'
		shown[h] = true
		for _, b := range s[1:] {
			merge(b-'a', h)
		}
	}
	for i, b := range shown {
		if b && find(byte(i)) == byte(i) {
			cnt++
		}
	}
	Fprint(_w, cnt)
}

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

package main

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

const N = 200002

var n int
var lab [N]int
var last [33] int
var s string
var picked [33] bool

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

func union(r1, r2 int) {
	var x = lab[r1] + lab[r2]
	if lab[r1] < lab[r2] {
		lab[r1] = x
		lab[r2] = r1
	} else {
		lab[r2] = x
		lab[r1] = r2
	}
}

func get(x int) int {
	if lab[x] < 0 {
		return x
	}
	lab[x] = get(lab[x])
	return lab[x]
}

func main() {
	defer writer.Flush()

	fmt.Fscanf(reader, "%d\n", &n)

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

	for i:=0; i < 26; i++ {
		last[i] = -1
	}

	for i:=0; i < n; i++ {
		fmt.Fscanf(reader, "%s\n", &s)
		for j:=0; j < 26; j++ {
			picked[j] = false
		}

		var sz = len(s)
		for j:=0; j < sz; j++ {
			var pos = s[j] - 'a'
			if !picked[pos] {
				if last[pos] == -1 {
					last[pos] = i
				} else {
					var r1= get(last[pos])
					var r2= get(i)
					if r1 != r2 {
						union(r1, r2)
					}
				}
				picked[pos] = true
			}
		}
	}

	var unique_group = make(map[int] bool)
	for i:=0; i < n; i++ {
		unique_group[get(i)] = true
	}
	var tot = len(unique_group)
	fmt.Fprintf(writer, "%d\n", tot)
}

package main

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

const N = 200002

var n int
var lab [N]int
var last [33] int
var s string
var picked [33] bool

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

func union(r1, r2 int) {
	var x = lab[r1] + lab[r2]
	if lab[r1] < lab[r2] {
		lab[r1] = x
		lab[r2] = r1
	} else {
		lab[r2] = x
		lab[r1] = r2
	}
}

func get(x int) int {
	if lab[x] < 0 {
		return x
	}
	lab[x] = get(lab[x])
	return lab[x]
}

func main() {

	scanf("%d\n", &n)
	for i:=0; i < n; i++ {
		lab[i] = -1
	}

	for i:=0; i < 26; i++ {
		last[i] = -1
	}

	for i:=0; i < n; i++ {
		scanf("%s\n", &s)
		for j:=0; j < 26; j++ {
			picked[j] = false
		}

		var sz = len(s)
		for j:=0; j < sz; j++ {
			var pos = s[j] - 'a'
			if !picked[pos] {
				if last[pos] == -1 {
					last[pos] = i
				} else {
					var r1= get(last[pos])
					var r2= get(i)
					if r1 != r2 {
						union(r1, r2)
					}
				}
				picked[pos] = true
			}
		}
	}

	var unique_group = make(map[int] bool)
	for i:=0; i < n; i++ {
		unique_group[get(i)] = true
	}
	var tot = len(unique_group)
	fmt.Println(tot)
}

package main

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

type HSet map[rune]struct{}

func CreateHSetFromString(str string) HSet {
	s := make(HSet, 30)

	for _, r := range str {
		s[r] = struct{}{}
	}

	return s
}

func (s *HSet) HasIntersection(a HSet) bool {

	if len(*s) < len(a) {
		for k := range *s {
			if _, ok := a[k]; ok {
				return true
			}
		}
	} else {
		for k := range a {
			if _, ok := (*s)[k]; ok {
				return true
			}
		}
	}

	return false
}

func (s *HSet) Merge(a HSet) {
	for k := range a {
		(*s)[k] = struct{}{}
	}
}

type SliceHSet []HSet

func (r *SliceHSet) Optimize() {
	skip := map[int]struct{}{}

	for {
		for i := 0; i < len(*r)-1; i++ {
			for j := i + 1; j < len(*r); j++ {
				if (*r)[j].HasIntersection((*r)[i]) {
					skip[i] = struct{}{}
					(*r)[j].Merge((*r)[i])
					(*r)[i].Merge((*r)[j])
				}
			}
		}

		if len(skip) == 0 {
			break
		}

		tmp := make([]HSet, 0, len(*r)-len(skip))

		for i := range *r {
			if _, needSkip := skip[i]; needSkip {
				continue
			}

			tmp = append(tmp, (*r)[i])
		}

		*r = tmp

		for i := range skip {
			delete(skip, i)
		}
	}
}
func main() {
	var rows int
	in := bufio.NewReader(os.Stdin)

	fmt.Fscanln(in, &rows)

	e := make(map[rune]HSet, 30)

	scanner := bufio.NewScanner(in)
	for i := 0; i < rows; i++ {
		scanner.Scan()
		s := scanner.Text()
		h := CreateHSetFromString(s)
		k := rune(s[0])
		if v, ok := e[k]; ok {
			v.Merge(h)
		} else {
			e[k] = h
		}
	}

	r := make(SliceHSet, 0, len(e))
	for _, v := range e {
		r = append(r, v)
	}

	r.Optimize()

	fmt.Fprintln(os.Stdout, len(r))
}

package main

import "fmt"

type Node struct {
	neighs []string
}

var m map[string]*Node
var st map[string]bool

func dfs(curr string, m map[string]*Node) {

	_, ok := st[curr]
	if ok {
		return
	}

	st[curr] = true
	for _, neigh := range m[curr].neighs {
		dfs(neigh, m)
	}
}

func main() {
	m = make(map[string]*Node)
	st = make(map[string]bool)
	var ls []string
	var n int
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		var input string
		fmt.Scanf("%s", &input)

		ls = append(ls, input)
		_, ok := m[input]
		if !ok {
			m[input] = &Node{}
		}

		for _, c := range input {
			target := string(c)
			_, ok := m[target]
			if !ok {
				m[target] = &Node{}
			}

			m[input].neighs = append(m[input].neighs, target)
			m[target].neighs = append(m[target].neighs, input)
		}
	}

	ans := 0
	for _, inp := range ls {
		_, inside := st[inp]
		if !inside {
			dfs(inp, m)
			ans += 1
		}
	}

	fmt.Println(ans)

}

package main

import "fmt"

type Node struct {
	neighs []string
}

var m map[string]*Node
var st map[string]bool

func dfs(curr string, m map[string]*Node) {

	_, ok := st[curr]
	if ok {
		return
	}

	st[curr] = true
	for _, neigh := range m[curr].neighs {
		dfs(neigh, m)
	}
}

func main() {
	m = make(map[string]*Node)
	st = make(map[string]bool)
	var ls []string
	var n int
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		var input string
		fmt.Scanf("%s\n", &input)

		ls = append(ls, input)
		_, ok := m[input]
		if !ok {
			m[input] = &Node{}
		}

		for _, c := range input {
			target := string(c)
			_, ok := m[target]
			if !ok {
				m[target] = &Node{}
			}

			m[input].neighs = append(m[input].neighs, target)
			m[target].neighs = append(m[target].neighs, input)
		}
	}

	ans := 0
	for _, inp := range ls {
		_, inside := st[inp]
		if !inside {
			dfs(inp, m)
			ans += 1
		}
	}

	fmt.Println(ans)

}

package main

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

const N = 200002

var n int
var lab [N]int
var last [33] int
var s string
var picked [33] bool

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

func union(r1, r2 int) {
	var x = lab[r1] + lab[r2]
	if lab[r1] < lab[r2] {
		lab[r1] = x
		lab[r2] = r1
	} else {
		lab[r2] = x
		lab[r1] = r2
	}
}

func get(x int) int {
	if lab[x] < 0 {
		return x
	}
	lab[x] = get(lab[x])
	return lab[x]
}

func main() {

	scanf("%d\n", &n)
	for i:=0; i < n; i++ {
		lab[i] = -1
	}

	for i:=0; i < 26; i++ {
		last[i] = -1
	}

	for i:=0; i < n; i++ {
		scanf("%s\n", &s)
		for j:=0; j < 26; j++ {
			picked[j] = false
		}

		var sz = len(s)
		for j:=0; j < sz; j++ {
			var pos = s[j] - 'a'
			if !picked[pos] {
				if last[pos] == -1 {
					last[pos] = i
				} else {

						var r1= get(last[pos])
						var r2= get(i)
						if r1 != r2 {
							union(r1, r2)
						}

				}
				picked[pos] = true
			}
		}
	}

	var unique_group = make(map[int] bool)
	for i:=0; i < n; i++ {
		unique_group[get(i)] = true
	}
	print(len(unique_group))
}

package main

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

const N = 200002

var n int
var lab [N]int
var last [33] int
var s string
var picked [33] bool

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

func union(r1, r2 int) {
	var x = lab[r1] + lab[r2]
	if lab[r1] < lab[r2] {
		lab[r1] = x
		lab[r2] = r1
	} else {
		lab[r2] = x
		lab[r1] = r2
	}
}

func get(x int) int {
	if lab[x] < 0 {
		return x
	}
	lab[x] = get(lab[x])
	return lab[x]
}

func main() {

	scanf("%d\n", &n)
	for i:=0; i < n; i++ {
		lab[i] = -1
	}

	for i:=0; i < 26; i++ {
		last[i] = -1
	}

	for i:=0; i < n; i++ {
		scanf("%s\n", &s)
		for j:=0; j < 26; j++ {
			picked[j] = false
		}

		var sz = len(s)
		for j:=0; j < sz; j++ {
			var pos = s[j] - 'a'
			if !picked[pos] {
				if last[pos] == -1 {
					last[pos] = i
				} else {
					if n < 200000 {
						var r1= get(last[pos])
						var r2= get(i)
						if r1 != r2 {
							union(r1, r2)
						}
					}
				}
				picked[pos] = true
			}
		}
	}

	var unique_group = make(map[int] bool)
	for i:=0; i < n; i++ {
		unique_group[get(i)] = true
	}
	var tot = len(unique_group)
	fmt.Println(tot)
}

package main

import (
	"fmt"
	"os"
)

const N = 200002

var n int
var lab [N]int
var gr [33][] int // array of slice
var s string
var picked [33] bool

func union(r1, r2 int) {
	var x = lab[r1] + lab[r2]
	if lab[r1] < lab[r2] {
		lab[r1] = x
		lab[r2] = r1
	} else {
		lab[r2] = x
		lab[r1] = r2
	}
}

func get(x int) int {
	if lab[x] < 0 {
		return x
	}
	lab[x] = get(lab[x])
	return lab[x]
}

func main() {
	fmt.Fscanln(os.Stdin, &n)
	for i:=0; i < n; i++ {
		lab[i] = -1
	}

	for i:=0; i < 26; i++ {
		gr[i] = make([]int, 0)
	}

	for i:=0; i < n; i++ {
		fmt.Fscanln(os.Stdin, &s)
		for j:=0; j < 26; j++ {
			picked[i] = false
		}

		var sz = len(s)
		for j:=0; j < sz; j++ {
			var pos = s[j] - 'a'
			if !picked[pos] {
				gr[pos] = append(gr[pos], i)
				picked[pos] = true
			}
		}
	}

	for i:=0; i < 26; i++ {
		var sz = len(gr[i])
		for j:=0; j < sz - 1; j++ {
			var r1 = get(gr[i][j])
			var r2 = get(gr[i][j + 1])
			if r1 != r2 {
				union(r1, r2)
			}
		}
	}

	var unique_group = make(map[int] bool)
	for i:=0; i < n; i++ {
		unique_group[get(i)] = true
	}

	fmt.Println(len(unique_group))
}

package main

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

const N = 200002

var n int
var lab [N]int
var last [33] int
var s string
var picked [33] bool

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

func union(r1, r2 int) {
	var x = lab[r1] + lab[r2]
	if lab[r1] < lab[r2] {
		lab[r1] = x
		lab[r2] = r1
	} else {
		lab[r2] = x
		lab[r1] = r2
	}
}

func get(x int) int {
	if lab[x] < 0 {
		return x
	}
	lab[x] = get(lab[x])
	return lab[x]
}

func main() {

	scanf("%d", &n)
	for i:=0; i < n; i++ {
		lab[i] = -1
	}

	for i:=0; i < 26; i++ {
		last[i] = -1
	}

	for i:=0; i < n; i++ {
		scanf("%s", &s)
		for j:=0; j < 26; j++ {
			picked[j] = false
		}

		var sz = len(s)
		for j:=0; j < sz; j++ {
			var pos = s[j] - 'a'
			if !picked[pos] {
				if last[pos] == -1 {
					last[pos] = i
				} else {
					if n < 200000 {
						var r1= get(last[pos])
						var r2= get(i)
						if r1 != r2 {
							union(r1, r2)
						}
					}
				}
				picked[pos] = true
			}
		}
	}

	var unique_group = make(map[int] bool)
	for i:=0; i < n; i++ {
		unique_group[get(i)] = true
	}

	printf("%d", len(unique_group))
}

package main

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

const N = 200002

var n int
var lab [N]int
var last [33] int
var s string
var picked [33] bool

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

func union(r1, r2 int) {
	var x = lab[r1] + lab[r2]
	if lab[r1] < lab[r2] {
		lab[r1] = x
		lab[r2] = r1
	} else {
		lab[r2] = x
		lab[r1] = r2
	}
}

func get(x int) int {
	if lab[x] < 0 {
		return x
	}
	lab[x] = get(lab[x])
	return lab[x]
}

func main() {

	fmt.Fscanf(reader, "%d\n", &n)

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

	for i:=0; i < 26; i++ {
		last[i] = -1
	}

	for i:=0; i < n; i++ {
		fmt.Fscanf(reader, "%s\n", &s)
		for j:=0; j < 26; j++ {
			picked[j] = false
		}

		var sz = len(s)
		for j:=0; j < sz; j++ {
			var pos = s[j] - 'a'
			if !picked[pos] {
				if last[pos] == -1 {
					last[pos] = i
				} else {
					var r1= get(last[pos])
					var r2= get(i)
					if r1 != r2 {
						union(r1, r2)
					}
				}
				picked[pos] = true
			}
		}
	}

	var unique_group = make(map[int] bool)
	for i:=0; i < n; i++ {
		unique_group[get(i)] = true
	}
	var tot = len(unique_group)
	fmt.Fprintf(writer, "%d\n", tot)
}


Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves:  D — move one cell down;  R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.

NoteIn the first testcase, it's enough to consider the following modified paths:   RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$;  RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$;  RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:

package main

import (
	"fmt"
)

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

func main() {
	var t int
	fmt.Scan(&t)
	for tt := 0; tt < t; tt++ {
		var (
			n, r, d int64
			s       string
		)
		fmt.Scan(&n, &s)
		m := int64(len(s))
		s = "a" + s + "a"

		for _, v := range s {
			if v == 'R' {
				r++
			} else if v == 'D' {
				d++
			}
		}
		if r == 0 || d == 0 {
			fmt.Println(n)
			continue
		}
		sum := int64(1)
		x, y := int64(1), int64(1)
		preD, preR := false, false
		for i := int64(1); i <= m; i++ {
			if s[i] == 'R' {
				preR = true
				if s[i+1] == 'R' {
					sum++
					if preD {
						sum += n - y - d
					}

					r--
					x++
				} else if s[i+1] == 'D' {
					sum += n - x - r + 1
					r--
					x++
				} else {
					sum += (n - x) * (n - y + 1)
				}
			} else {
				preD = true
				if s[i+1] == 'D' {
					sum++
					if preR {
						sum += n - x - r
					}

					d--
					y++
				} else if s[i+1] == 'R' {
					sum += n - y - d + 1
					d--
					y++
				} else {
					sum += (n - x + 1) * (n - y)
				}
			}

		}
		fmt.Println(sum)
	}
}

package main

import (
	"fmt"
)

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

func main() {
	var t int
	fmt.Scan(&t)
	for tt := 0; tt < t; tt++ {
		var (
			n, r, d int64
			s       string
		)
		fmt.Scan(&n, &s)
		m := int64(len(s))
		s += "a"

		for _, v := range s {
			if v == 'R' {
				r++
			} else if v == 'D' {
				d++
			}
		}
		if r == 0 || d == 0 {
			fmt.Println(n)
			continue
		}
		sum := int64(1)
		x, y := int64(1), int64(1)
		for i := int64(0); i < m; i++ {
			if s[i] == 'R' {
				if s[i+1] == 'R' {
					sum++
					sum += n - y - d
					r--
					x++
				} else if s[i+1] == 'D' {
					sum += n - x - r + 1
					r--
					x++
				} else {
					sum += (n - x) * (n - y + 1)
				}
			} else {
				if s[i+1] == 'D' {
					sum++
					sum += n - x - r
					d--
					y++
				} else if s[i+1] == 'R' {
					sum += n - y - d + 1
					d--
					y++
				} else {
					sum += (n - x + 1) * (n - y)
				}
			}
		}
		fmt.Println(sum)
	}
}

package main

import (
	"fmt"
)

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

func main() {
	var t int
	fmt.Scan(&t)
	for tt := 0; tt < t; tt++ {
		var (
			n, r, d int64
			s       string
		)
		fmt.Scan(&n, &s)
		for _, v := range s {
			if v == 'R' {
				r++
			} else if v == 'D' {
				d++
			}
		}
		if r == 0 || d == 0 {
			fmt.Println(n)
			continue
		}
		sum := int64(1)
		x, y := int64(1), int64(1)
		lstdn, lstrn := int64(0), int64(0)
		//flagR, flagD := false, false
		for i := int64(0); i < int64(len(s)); i++ {
			j := i
			for k := int64(i + 1); k < int64(len(s)); k++ {
				if s[k] == s[i] {
					j = k
				} else {
					break
				}
			}
			if s[i] == 'R' {
				rn := j - i + 1
				lstrn = rn
				r -= rn
				sum += n - x - r

				x += rn
				i = j
			} else {
				dn := j - i + 1
				lstdn = dn
				d -= dn
				sum += n - y - d

				y += dn
				i = j
			}
		}
		//fmt.Println(sum)
		if s[len(s)-1] == 'R' {
			sum += (n - x + lstrn) * (n - y)
		} else {
			sum += (n - x) * (n - y + lstdn)
		}

		//fmt.Println(x, y, (n-x)*(n-y))
		fmt.Println(sum)
	}
}

package main

import (
	"fmt"
)

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

func main() {
	var t int
	fmt.Scan(&t)
	for tt := 0; tt < t; tt++ {
		var (
			n, r, d int64
			s       string
		)
		fmt.Scan(&n, &s)
		for _, v := range s {
			if v == 'R' {
				r++
			} else if v == 'D' {
				d++
			}
		}
		if r == 0 || d == 0 {
			fmt.Println(n)
			continue
		}
		sum := int64(1)
		x, y := int64(1), int64(1)
		//flagR, flagD := false, false
		for i := int64(0); i < int64(len(s)); i++ {
			j := i
			for k := int64(i + 1); k < int64(len(s)); k++ {
				if s[k] == s[i] {
					j = k
				} else {
					break
				}
			}
			if s[i] == 'R' {
				rn := j - i + 1
				r -= rn
				sum += n - x - r

				x += rn
				i = j
			} else {
				dn := j - i + 1
				d -= dn
				sum += n - y - d

				y += dn
				i = j
			}
		}

		if s[len(s)-1] == 'R' {
			sum += (n - x + 1) * (n - y)
		} else {
			sum += (n - x) * (n - y + 1)
		}

		//fmt.Println(x, y, (n-x)*(n-y))
		fmt.Println(sum)
	}
}

package main

import (
	"fmt"
)

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

func main() {
	var t int
	fmt.Scan(&t)
	for tt := 0; tt < t; tt++ {
		var (
			n, r, d int64
			s       string
		)
		fmt.Scan(&n, &s)
		for _, v := range s {
			if v == 'R' {
				r++
			} else if v == 'D' {
				d++
			}
		}
		if r == 0 || d == 0 {
			fmt.Println(n)
			continue
		}
		sum := int64(1)
		x, y := int64(1), int64(1)
		flagR := false
		for i := int64(0); i < int64(len(s)); i++ {
			if s[i] == 'R' {
				j := i
				for k := int64(i + 1); k < int64(len(s)); k++ {
					if s[k] == s[i] {
						j = k
					} else {
						break
					}
				}
				rn := j - i + 1
				r -= rn
				sum += n - x - r

				x += rn
				i = j
				flagR = true
			} else {
				if flagR {
					sum += n - x - r
					sum++
					d--
					y++
				} else {
					d--
					y++
					sum++
				}
			}
		}

		sum += (n - x + 1) * (n - y)
		fmt.Println(sum)
	}
}


Fox Ciel has a board with n rows and n columns. So, the board consists of n × n cells. Each cell contains either a symbol '.', or a symbol '#'.A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.Please, tell Ciel if she can draw the crosses in the described way.

The first line contains an integer n (3 ≤ n ≤ 100) — the size of the board. Each of the next n lines describes one row of the board. The i-th line describes the i-th row of the board and consists of n characters. Each character is either a symbol '.', or a symbol '#'.

Output a single line with "YES" if Ciel can draw the crosses in the described way. Otherwise output a single line with "NO".

NoteIn example 1, you can draw two crosses. The picture below shows what they look like.In example 2, the board contains 16 cells with '#', but each cross contains 5. Since 16 is not a multiple of 5, so it's impossible to cover all.

package main

import (
	"fmt"
)

func main() {
	var n int
	var s string

	fmt.Scan(&n)

	m := make([][]bool, n)

	for i := range m {
		m[i] = make([]bool, n)
	}

	for i:=0; i<n; i++ {
		fmt.Scan(&s)
		for j, v := range s {
			if v == '#' {
				m[i][j] = true
			} else {
				m[i][j] = false
			}
		}
	}

	if check(m) {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

func check(m [][]bool) bool {
	length := len(m)

	for i := range m {
		for j := range m[i] {
			if m[i][j] == true {
				if i+1>=length || i+2>=length || j-1<0 || j+1>=length {
					// fmt.Println(i, j, "1")
					return false
				}
				if !m[i+1][j] || !m[i+1][j-1] || !m[i+1][j+1] || !m[i+2][j] {
					// fmt.Println(i, j)
					return false
				}
				m[i+1][j] = false
				m[i+1][j-1] = false
				m[i+1][j+1] = false
				m[i+2][j] = false
			}
		}
	}
	return true
}

package main

import "fmt"

func main() {
    var n int
    var s [105]string
    var f [105][105]bool
    fmt.Scan(&n)
    cnt := 0
    for i := 0; i < n; i++ {
        fmt.Scan(&s[i])
        for j, v := range s[i] {
            if v == '#' {
                cnt++
                f[i][j] = true
            }
        }
    }
    for i := 1; i < (n-1); i++ {
        for j := 1; j < (n-1); j++ {
            if f[i][j] {
                if f[i-1][j] && f[i+1][j] && f[i][j-1] && f[i][j+1] {
                    cnt -= 5
                    f[i][j] = false; f[i-1][j] = false; f[i+1][j] = false; f[i][j-1] = false; f[i][j+1] = false
                }
            }
        }
    }
    if cnt == 0 { fmt.Println("YES") } else { fmt.Println("NO") }
}


As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him.   Thus, he came up with a puzzle to tell his mom his coordinates. His coordinates are the answer to the following problem.A string consisting only of parentheses ('(' and ')') is called a bracket sequence. Some bracket sequence are called correct bracket sequences. More formally:  Empty string is a correct bracket sequence.  if s is a correct bracket sequence, then (s) is also a correct bracket sequence.  if s and t are correct bracket sequences, then st (concatenation of s and t) is also a correct bracket sequence. A string consisting of parentheses and question marks ('?') is called pretty if and only if there's a way to replace each question mark with either '(' or ')' such that the resulting string is a non-empty correct bracket sequence.Will gave his mom a string s consisting of parentheses and question marks (using Morse code through the lights) and his coordinates are the number of pairs of integers (l, r) such that 1 ≤ l ≤ r ≤ |s| and the string slsl + 1... sr is pretty, where si is i-th character of s.Joyce doesn't know anything about bracket sequences, so she asked for your help.

The first and only line of input contains string s, consisting only of characters '(', ')' and '?' (2 ≤ |s| ≤ 5000).

Print the answer to Will's puzzle in the first and only line of output.

NoteFor the first sample testcase, the pretty substrings of s are:  "(?" which can be transformed to "()".  "?)" which can be transformed to "()".  "((?)" which can be transformed to "(())".  "(?))" which can be transformed to "(())".  For the second sample testcase, the pretty substrings of s are:  "??" which can be transformed to "()".  "()".  "??()" which can be transformed to "()()".  "?()?" which can be transformed to "(())".  "??" which can be transformed to "()".  "()??" which can be transformed to "()()".  "??()??" which can be transformed to "()()()".

package main

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

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 toInt(buf []byte) (o int) {
	for _, v := range buf {
		o = o*10 + int(v-'0')
	}
	return
}

type pair struct {
	first int
	second uint8
}

type ll []int64

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

var ch string

func main() {
	in := bufio.NewReader(os.Stdin)
	//in, _ := os.Open("a.txt")
	fmt.Fscanf(in, "%s\n", &ch)
	n := len(ch)
	ans := 0
	for i := 0; i < n; i++ {
		opened := 0
		guaranteed := 0
		sum := 0
		for j := i; j < n; j++ {
			if ch[j] == ')' {
				if sum == 0 {
					break
				}
				sum--
				if guaranteed > 0{
					guaranteed--
				}
			}
			if ch[j] == '(' {
				opened++
				sum++
				guaranteed++
			}
			if ch[j] == '?' {
				sum++
				if guaranteed > 0 {
					guaranteed--
				}
			}
			if guaranteed == 0 && (i - j) % 2 != 0 {
				ans++
				//fmt.Println(i, j)
			}
		}
	}
	fmt.Println(ans)
}


You are given a chess board with $$$n$$$ rows and $$$n$$$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.A knight is a chess piece that can attack a piece in cell ($$$x_2$$$, $$$y_2$$$) from the cell ($$$x_1$$$, $$$y_1$$$) if one of the following conditions is met:  $$$|x_1 - x_2| = 2$$$ and $$$|y_1 - y_2| = 1$$$, or  $$$|x_1 - x_2| = 1$$$ and $$$|y_1 - y_2| = 2$$$. Here are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them).  A duel of knights is a pair of knights of different colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible.

The first line contains one integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of rows (and columns) in the board.

Print $$$n$$$ lines with $$$n$$$ characters in each line. The $$$j$$$-th character in the $$$i$$$-th line should be W, if the cell ($$$i$$$, $$$j$$$) contains a white knight, or B, if it contains a black knight. The number of duels should be maximum possible. If there are multiple optimal answers, print any of them.

NoteIn the first example, there are $$$8$$$ duels:  the white knight in ($$$1$$$, $$$1$$$) attacks the black knight in ($$$3$$$, $$$2$$$);  the white knight in ($$$1$$$, $$$1$$$) attacks the black knight in ($$$2$$$, $$$3$$$);  the white knight in ($$$1$$$, $$$3$$$) attacks the black knight in ($$$3$$$, $$$2$$$);  the white knight in ($$$1$$$, $$$3$$$) attacks the black knight in ($$$2$$$, $$$1$$$);  the white knight in ($$$3$$$, $$$1$$$) attacks the black knight in ($$$1$$$, $$$2$$$);  the white knight in ($$$3$$$, $$$1$$$) attacks the black knight in ($$$2$$$, $$$3$$$);  the white knight in ($$$3$$$, $$$3$$$) attacks the black knight in ($$$1$$$, $$$2$$$);  the white knight in ($$$3$$$, $$$3$$$) attacks the black knight in ($$$2$$$, $$$1$$$).

package main

import (
	"fmt"
)

func main() {
    var n int
    fmt.Scan(&n)
    for i:=0;i<n;i++{
        for j:=0;j<n;j++{
            if i%2==j%2{
                fmt.Print("B")
            }else{
                fmt.Print("W")
            }
        }
        fmt.Println()
    }

}

/*            {{range .Games}}
if ({{.Id}}===id) {
    infoEl.html("{{.White}} vs. {{.Black}}\n added by {{.AddedUser}}")
    game.load_pgn({{.Pgn}})

    toBegin()
    toEnd()

    ext_pgn = game.pgn()
    updateBoard(board,false)
}
{{end}}*/

package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"math/big"
	"os"
	"strconv"
)

var scan *bufio.Scanner
var reader io.Reader
var writer io.Writer

func init() {
	scan = bufio.NewScanner(os.Stdin)
	reader = os.Stdin
	writer = os.Stdout
	scan.Split(bufio.ScanWords)
}

func main() {
	solve()
}

func solve() {
	n := nextInt()
	w := "W"
	b := "B"
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if (i+j)%2 == 0 {
				fmt.Fprint(writer, w)
			} else {
				fmt.Fprint(writer, b)
			}
		}
		fmt.Fprintln(writer)
	}
}

func nextWord() string {
	var s string
	fmt.Fscan(reader, &s)
	return s
}

func nextInt() int {
	i, e := strconv.Atoi(nextWord())
	if e != nil {
		panic(e)
	}
	return i
}

func max(x int, y ...int) int {
	res := float64(x)
	for _, z := range y {
		res = math.Max(res, float64(z))
	}
	return int(res)
}

func min(x int, y ...int) int {
	res := float64(x)
	for _, z := range y {
		res = math.Min(res, float64(z))
	}
	return int(res)
}

func abs(x int) int {
	return int(math.Abs(float64(x)))
}

func sqrt(x int) int {
	return int(math.Sqrt(float64(x)))
}

func int2Int(x int) big.Int {
	var res big.Int
	res.SetInt64(int64(x))
	return res
}

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	var (
		n int
	)
	_, _ = fmt.Fscan(input, &n)

	needW := true
	for i := 0; i < n; i++ {
		first := needW
		for j := 0; j < n; j++ {
			if needW {
				fmt.Print("W")
			} else {
				fmt.Print("B")
			}
			needW = !needW
		}
		if first == needW {
			needW = !needW
		}
		fmt.Println()
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if a[i][j] == 0 {
				dfs(n, i, j, a, 1)
			}
		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if a[i][j] == 1 {
				fmt.Fprintf(out, "B")
			} else {
				fmt.Fprintf(out, "W")
			}
		}
		fmt.Fprintf(out, "\n")
	}
	return
}

func dfs(n, x, y int, a [][]int, color int) {
	dx := []int{-1, 1, 2, 2, 1, -1, -2, -2}
	dy := []int{-2, -2, -1, 1, 2, 2, 1, -1}
	newcolor := 3 - color
	for q := 0; q < 8; q++ {
		nx := x + dx[q]
		ny := y + dy[q]
		if nx >= 0 && nx < n && ny >= 0 && ny < n {
			if a[nx][ny] == 0 {
				a[nx][ny] = color
				dfs(n, nx, ny, a, newcolor)
			}
		}
	}
}

package main

import (
	"fmt"
)

type pos struct {
	color    rune
	row, col int
}

func solve(n int) [][]rune {
	const B = 'B'
	const W = 'W'

	res := make([][]rune, n)
	for i := range res {
		res[i] = make([]rune, n)
	}

	for i := 0; i < n*n; i++ {
		r, c := i/n, i%n

		res[r][c] = B
		if r%2 == c%2 {
			res[r][c] = W
		}
	}

	return res
}

func main() {
	var n int

	fmt.Scan(&n)

	res := solve(n)
	for _, s := range res {
		fmt.Println(string(s))
	}
}

package main

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

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

	var x int
	_, err := fmt.Fscan(input, &x)
	if err != nil {
	}

	for i := 0; i < x; i++ {
		for j := 0; j < x; j++ {
			if (i+j)%2 == 0 {
				fmt.Print("W")
			} else {
				fmt.Print("B")
			}
		}
		fmt.Print("\n")
	}
}

package main

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

var scan *bufio.Scanner
var writer io.Writer

func init() {
	scan = bufio.NewScanner(os.Stdin)
	writer = os.Stdout
	scan.Split(bufio.ScanWords)
}

func nextWord() string {
	scan.Scan()
	str := scan.Text()
	return str
}

func nextInt() int {
	i, e := strconv.Atoi(nextWord())
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	n := nextInt()
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if i % 2 == 0 {
				if j % 2 == 0 {
					fmt.Fprint(writer, "W")
				} else {
					fmt.Fprint(writer, "B")
				}
			} else {
				if j % 2 == 1 {
					fmt.Fprint(writer, "W")
				} else {
					fmt.Fprint(writer, "B")
				}
			}
		}
		fmt.Fprintln(writer)
	}
}

package main

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

const INF  = 1000000001

type Pair struct {
	first, second int
}

func sort(arr []int) []int {
	if len(arr) < 2 {
		return arr
	}
	left := 0
	right := len(arr) - 1
	pivot := rand.Int() % len(arr)

	arr[pivot], arr[right] = arr[right], arr[pivot]

	for i := 0; i < len(arr); i++ {
		if arr[i] < arr[right] {
			arr[i], arr[left] = arr[left], arr[i]
			left++
		}
	}

	arr[left], arr[right] = arr[right], arr[left]

	sort(arr[:left])
	sort(arr[left+1:])
	return arr
}

func solution(reader io.Reader, writer io.Writer) {
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if (i + j) % 2 == 0 {
				fmt.Fprintf(writer, "W")
			} else {
				fmt.Fprintf(writer, "B")
			}
		}
		fmt.Fprintf(writer, "\n")
	}
}

func main() {

	//stdin, err := os.Open("file.in")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	//stdout, err := os.Create("file.out")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)
	defer writer.Flush()

	solution(reader, writer)
}

// Author: sighduck
// URL: https://codeforces.com/contest/1221/problem/B

package main

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

func createWhiteLine(n int) string {
	s := strings.Repeat("WB", n/2)
	if n%2 == 1 {
		return s + "W"
	}
	return s
}

func createBlackLine(n int) string {
	s := strings.Repeat("BW", n/2)
	if n%2 == 1 {
		return s + "B"
	}
	return s
}

func Solve(n int) []string {
	board := make([]string, n)
	for i := 0; i < n; i++ {
		if i%2 == 0 {
			board[i] = createWhiteLine(n)
		} else {
			board[i] = createBlackLine(n)
		}
	}
	return board
}

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

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

	for _, line := range Solve(n) {
		fmt.Fprintf(writer, "%s\n", line)
	}
}

package main

import (
	"fmt"
)

type pos struct {
	color    rune
	row, col int
}

func solve(n int) [][]rune {
	const empty = rune('!')

	ch := 'W'
	flipColor := func(ch rune) rune {
		if ch == 'W' {
			return 'B'
		}

		return 'W'
	}

	res := make([][]rune, n)
	for i := range res {
		res[i] = make([]rune, n)
		for j := range res[i] {
			res[i][j] = empty
		}
	}

	bfs := func(color rune, r, c int) {
		moves := []int{1, 2, 1, -2, -1, 2, -1, -2, 2, 1, 2, -1, -2, 1, -2, -1}

		q := []pos{{color, r, c}}

		for len(q) > 0 {
			next := q[0]
			q = q[1:]

			if res[next.row][next.col] != empty {
				break
			}
			res[next.row][next.col] = next.color

			for i := 0; i < len(moves); i += 2 {

				row := next.row + moves[i]
				col := next.col + moves[i+1]

				if row < 0 || col < 0 || row >= n || col >= n || res[row][col] != empty {
					continue
				}

				q = append(q, pos{flipColor(next.color), row, col})
			}
		}
	}

	for i := 0; i < n*n; i++ {
		r, c := i/n, i%n

		bfs(ch, r, c)

		ch = flipColor(ch)
	}

	return res
}

func main() {
	var n int

	fmt.Scan(&n)

	res := solve(n)
	for _, s := range res {
		fmt.Println(string(s))
	}
}