It is never too late to play the fancy "Binary Cards" game!There is an infinite amount of cards of positive and negative ranks that are used in the game. The absolute value of any card rank is a power of two, i.e. each card has a rank of either 2k or  - 2k for some integer k ≥ 0. There is an infinite amount of cards of any valid rank.At the beginning of the game player forms his deck that is some multiset (possibly empty) of cards. It is allowed to pick any number of cards of any rank but the small deck is considered to be a skill indicator. Game consists of n rounds. In the i-th round jury tells the player an integer ai. After that the player is obligated to draw such a subset of his deck that the sum of ranks of the chosen cards is equal to ai (it is allowed to not draw any cards, in which case the sum is considered to be equal to zero). If player fails to do so, he loses and the game is over. Otherwise, player takes back all of his cards into his deck and the game proceeds to the next round. Player is considered a winner if he is able to draw the suitable set of cards in each of the rounds.Somebody told you which numbers ai the jury is going to tell you in each round. Now you want to pick a deck consisting of the minimum number of cards that allows you to win the "Binary Cards" game.

The first line of input contains an integer n (1 ≤ n ≤ 100 000), the number of rounds in the game. The second line of input contains n integers a1, a2, ..., an ( - 100 000 ≤ ai ≤ 100 000), the numbers that jury is going to tell in each round.

In the first line print the integer k (0 ≤ k ≤ 100 000), the minimum number of cards you have to pick in your deck in ordered to win the "Binary Cards". In the second line print k integers b1, b2, ..., bk ( - 220 ≤ bi ≤ 220, |bi| is a power of two), the ranks of the cards in your deck. You may output ranks in any order. If there are several optimum decks, you are allowed to print any of them. It is guaranteed that there exists a deck of minimum size satisfying all the requirements above.

NoteIn the first sample there is the only round in the game, in which you may simply draw both your cards. Note that this sample test is the only one satisfying the first test group constraints.In the second sample you may draw the only card  - 1 in the first round, cards 4 and  - 1 in the second round, nothing in the third round, the only card 4 in the fourth round and the whole deck in the fifth round.

package main
import	(
		"fmt"
		"bufio"
		"os"
		"strconv"
		"sort"
		_"math/rand"
		)
var answer []int
func main() {
	init_scanner()
	n := readInt()
	M := make([]int,n)
	for i := 0;i < n;i++ {
		M[i] = readInt()
	}
	sort.Ints(M)
	get(1,M,make([]int,0))
	fmt.Println(len(answer))
	for _,v := range(answer) {
		fmt.Printf("%d ",v)
	}
	fmt.Println()
}
func get(p2 int,M []int,cur[]int) {
	if p2 > (1 << 18) {
		return
	}
	if len(M) == 1 && M[0] == 0 {
		if len(answer) == 0 || len(cur) < len(answer) {
			answer = cur
		}
	} else {
		ok := true
		for _,v := range(M) {
			if (v & 1) == 1 {
				ok = false
			}
		}
		cur1 := make([]int,len(cur))
		cur2 := make([]int,len(cur))
		for i := 0;i < len(cur);i++ {
			cur1[i] = cur[i]
			cur2[i] = cur[i]
		}
		if ok == false {
			cur1 = append(cur1,-p2)
			cur2 = append(cur2,p2)
		}
		sz := len(M)
		sz1,sz2 := 0,0
		for i := 0;i < sz; {
			j := i
			for ;j < sz && g1(M[i]) == g1(M[j]);j++ {

			}
			sz1++
			i = j
		}
		M1 := make([]int,sz1)
		sz1 = -1
		for i := 0;i < sz; {
			j := i
			for ;j < sz && g1(M[i]) == g1(M[j]);j++ {

			}
			sz1++
			M1[sz1] = g1(M[i])
			i = j
		}
		for i := 0;i < sz; {
			j := i
			for ;j < sz && g2(M[i]) == g2(M[j]);j++ {

			}
			sz2++
			i = j
		}
		M2 := make([]int,sz2)
		sz2 = -1
		for i := 0;i < sz; {
			j := i
			for ;j < sz && g2(M[i]) == g2(M[j]);j++ {

			}
			sz2++
			M2[sz2] = g2(M[i])
			i = j
		}
		get(p2 * 2,M1,cur1)
		get(p2 * 2,M2,cur2)
	}
}
func g1(x int) int {
	if (x & 1) == 0 {
		return x / 2
	} else {
		return (x + 1) / 2
	}
}
func g2(x int) int {
	if (x & 1) == 0 {
		return x / 2
	} else {
		return (x - 1) / 2
	}
}
func abs(x int) int {
	if x < 0 {
		return -x
	} else {
		return x
	}
}
func max(x,y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

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

var scanner *bufio.Scanner

func init_scanner() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024*1024*20
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
}

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

package main
import	(
		"fmt"
		"bufio"
		"os"
		"strconv"
		_"math/rand"
		)
var answer []int
func main() {
	init_scanner()
	n := readInt()
	M := make(map[int]bool,0)
	for ;n > 0;n-- {
		v := readInt()
		M[v] = true
	}
	get(1,M,make([]int,0))
	fmt.Println(len(answer))
	for _,v := range(answer) {
		fmt.Printf("%d ",v)
	}
	fmt.Println()
}
func get(p2 int,M map[int]bool,cur[]int) {
	if p2 > (1 << 18) {
		return
	}
	if len(M) == 1 && M[0] == true {
		if len(answer) == 0 || len(cur) < len(answer) {
			answer = cur
		}
	} else {
		ok := true
		for v,_ := range(M) {
			if (v & 1) == 1 {
				ok = false
			}
		}
		M1,M2 := make(map[int]bool,0),make(map[int]bool,0)
		ncur := cur
		if ok == false {
			ncur = append(ncur,-p2)
		}
		for v,_ := range(M) {
			if (v & 1) == 1 {
				M1[(v + 1) / 2] = true
				M2[(v - 1) / 2] = true
			} else {
				M1[v / 2] = true
				M2[v / 2] = true
			}
		}
		get(p2 * 2,M1,ncur)
		if ok == false {
			ncur[len(ncur) - 1] *= -1
		}
		get(p2 * 2,M2,ncur)
	}
}
func abs(x int) int {
	if x < 0 {
		return -x
	} else {
		return x
	}
}
func max(x,y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

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

var scanner *bufio.Scanner

func init_scanner() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024*1024*20
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
}

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

package main
import	(
		"fmt"
		"bufio"
		"os"
		"strconv"
		_"math/rand"
		)
var answer []int
func main() {
	init_scanner()
	n := readInt()
	M := make(map[int]bool,0)
	for ;n > 0;n-- {
		v := readInt()
		M[v] = true
	}
	get(1,M,make([]int,0))
	fmt.Println(len(answer))
	for _,v := range(answer) {
		fmt.Printf("%d ",v)
	}
	fmt.Println()
}
func get(p2 int,M map[int]bool,cur[]int) {
	if p2 > (1 << 18) {
		return
	}
	if len(M) == 1 && M[0] == true {
		if len(answer) == 0 || len(cur) < len(answer) {
			answer = cur
		}
	} else {
		ok := true
		for v,_ := range(M) {
			if (v & 1) == 1 {
				ok = false
			}
		}
		M1,M2 := make(map[int]bool,0),make(map[int]bool,0)
		cur1,cur2 := cur,cur
		if ok == false {
			cur1 = append(cur1,-p2)
			cur2 = append(cur2,p2)
		}
		for v,_ := range(M) {
			if (v & 1) == 1 {
				M1[(v + 1) / 2] = true
				M2[(v - 1) / 2] = true
			} else {
				M1[v / 2] = true
				M2[v / 2] = true
			}
		}
		get(p2 * 2,M1,cur1)
		get(p2 * 2,M2,cur2)
	}
}
func abs(x int) int {
	if x < 0 {
		return -x
	} else {
		return x
	}
}
func max(x,y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

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

var scanner *bufio.Scanner

func init_scanner() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024*1024*20
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
}

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


Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

package main

import (
	"fmt"
)

func main() {
	var word string
	var k int

	fmt.Scan(&word,&k)

	if len(word) < k {
		fmt.Println("impossible")
		return
	}

	chs := make(map[rune]int,0)

	for _,ch := range word {
		chs[ch]++
	}

	out := k - len(chs)
	if out < 0 {
		out = 0
	}
    fmt.Println(out)
}

package main

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

func main() {
	var (
		s string
		k int
	)

	stdin := bufio.NewReader(os.Stdin)
	fmt.Fscanf(stdin, "%s\n%d", &s, &k)
	m := make(map[string]bool)
	for _, c := range s {
		m[string(c)] = true
	}

	nUnique := len(m)
	nChange := int(math.Max(float64(k-nUnique), 0.0))
	if nUnique+nChange > len(s) {
		fmt.Println("impossible")
	} else {
		fmt.Println(nChange)
	}
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var (
		s string
		k int
	)
	fmt.Scanf("%s\n%d", &s, &k)
	m := make(map[string]bool)
	for _, c := range s {
		m[string(c)] = true
	}

	nUnique := len(m)
	nChange := int(math.Max(float64(k-nUnique), 0.0))
	if nUnique+nChange > len(s) {
		fmt.Println("impossible")
	} else {
		fmt.Println(nChange)
	}
}

package main

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

func solve() {
	s := readString()
	k := readInt()
	m := map[rune]int{}
	for _, v := range s {
		m[v]++
	}
	if len(m) >= k {
		fmt.Println(0)
		return
	}
	cur := len(m)
	res := 0
	for _, cnt := range m {
		for i := 1; i < cnt; i++ {
			cur++
			res++
			if cur >= k {
				fmt.Println(res)
				return
			}
			if cur > 26 {
				fmt.Println("impossible")
				return
			}
		}
	}
	fmt.Println("impossible")
}

var scanner *bufio.Scanner

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

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

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

// IO

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

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

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

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

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

package main

import (
	"fmt"
)

func main() {
	var word string
	var k int

	fmt.Scan(&word,&k)

	if len(word) < k {
		fmt.Println("impossible")
		return
	}

	var chs map[rune]int = make(map[rune]int,0)

	for _,ch := range word {
		chs[ch]++
	}

	var countRep = 0
	for _,num := range chs {
		countRep += num - 1
	}

    fmt.Println(countRep)
}

package main

import (
    "fmt"
    "math"
)

func main() {
    var (
        s string
        k int
    )
    fmt.Scanf("%s\n%d", &s, &k)
    m := make(map[string]bool)

    if k > len(s) {
        fmt.Println("impossible")
        return
    }
    for _, c := range s {
        m[string(c)] = true
    }
    fmt.Println(int(math.Min(float64(len(s) - len(m)), float64(k -len(m)))))
}

package main

import (
    "fmt"
)

func main() {
    var (
        s string
        k int
    )
    fmt.Scanf("%s\n%d", &s, &k)
    m := make(map[string]bool)

    if k > len(s) {
        fmt.Println("impossible")
        return
    }
    for _, c := range s {
        m[string(c)] = true
    }
    fmt.Println(len(s) - len(m))
}


Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allowed.Help Arkady to find two fountains with maximum total beauty so that he can buy both at the same time.

The first line contains three integers n, c and d (2 ≤ n ≤ 100 000, 0 ≤ c, d ≤ 100 000) — the number of fountains, the number of coins and diamonds Arkady has. The next n lines describe fountains. Each of these lines contain two integers bi and pi (1 ≤ bi, pi ≤ 100 000) — the beauty and the cost of the i-th fountain, and then a letter "C" or "D", describing in which type of money is the cost of fountain i: in coins or in diamonds, respectively.

Print the maximum total beauty of exactly two fountains Arkady can build. If he can't build two fountains, print 0.

NoteIn the first example Arkady should build the second fountain with beauty 4, which costs 3 coins. The first fountain he can't build because he don't have enough coins. Also Arkady should build the third fountain with beauty 5 which costs 6 diamonds. Thus the total beauty of built fountains is 9.In the second example there are two fountains, but Arkady can't build both of them, because he needs 5 coins for the first fountain, and Arkady has only 4 coins.

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

func readString() string {
	if !in.Scan() {
		panic(in.Err())
	}
	return in.Text()
}

func update(pair *[2]int, b int) {
	if pair[0] <= b {
		pair[1] = pair[0]
		pair[0] = b
	} else if pair[1] < b {
		pair[1] = b
	}
}

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	budget := [2]int{readInt(), readInt()}
	var maxB [2]int
	var best [2][][2]int
	for i, budget := range budget {
		best[i] = make([][2]int, budget+1)
	}
	for i := 0; i < n; i++ {
		b := readInt()
		p := readInt()
		typ := readString()[0] - 'C'
		if budget[typ] < p {
			continue
		}
		if maxB[typ] < b {
			maxB[typ] = b
		}
		update(&best[typ][p], b)
	}

	res := 0
	if maxB[0] > 0 && maxB[1] > 0 {
		res = maxB[0] + maxB[1]
	}
	for typ, budget := range budget {
		pref := make([][2]int, budget+1)
		for p := 1; p <= budget; p++ {
			pref[p] = pref[p-1]
			update(&pref[p], best[typ][p][0])
			update(&pref[p], best[typ][p][1])
		}
		if mid := pref[budget/2][0] + pref[budget/2][1]; res < mid && pref[budget/2][1] > 0 {
			res = mid
		}
		for i := 0; i < budget-i; i++ {
			j := budget - i
			if pref[i][0] == 0 || pref[j][1] == 0 {
				continue
			}
			cur := pref[i][0]
			if pref[j][0] == cur {
				cur += pref[j][1]
			} else {
				cur += pref[j][0]
			}
			if res < cur {
				res = cur
			}
		}
	}
	fmt.Println(res)
}

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

func readString() string {
	if !in.Scan() {
		panic(in.Err())
	}
	return in.Text()
}

func update(pair *[2]int, b int) {
	if pair[0] <= b {
		pair[1] = pair[0]
		pair[0] = b
	} else if pair[1] < b {
		pair[1] = b
	}
}

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	budget := [2]int{readInt(), readInt()}
	var maxB [2]int
	var best [2][][2]int
	for i, budget := range budget {
		best[i] = make([][2]int, budget+1)
	}
	for i := 0; i < n; i++ {
		b := readInt()
		p := readInt()
		typ := readString()[0] - 'C'
		if budget[typ] < p {
			continue
		}
		if maxB[typ] < b {
			maxB[typ] = b
		}
		update(&best[typ][p], b)
	}

	res := 0
	if maxB[0] > 0 && maxB[1] > 0 {
		res = maxB[0] + maxB[1]
	}
	for typ, budget := range budget {
		pref := make([][2]int, len(best[typ]))
		for p := 1; p <= budget; p++ {
			pref[p] = pref[p-1]
			update(&pref[p], best[typ][p][0])
			update(&pref[p], best[typ][p][1])
		}
		if mid := pref[budget/2][0] + pref[budget/2][1]; res < mid && pref[budget/2][1] > 0 {
			res = mid
		}
		for i := 0; i < len(pref)-i; i++ {
			j := len(pref) - i
			if pref[i][0] == 0 || pref[j][1] == 0 {
				continue
			}
			cur := pref[i][0]
			if pref[j][0] == cur {
				cur += pref[j][1]
			} else {
				cur += pref[j][0]
			}
			if res < cur {
				res = cur
			}
		}
	}
	fmt.Println(res)
}


Many years have passed, and n friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo.Simply speaking, the process of photographing can be described as follows. Each friend occupies a rectangle of pixels on the photo: the i-th of them in a standing state occupies a wi pixels wide and a hi pixels high rectangle. But also, each person can lie down for the photo, and then he will occupy a hi pixels wide and a wi pixels high rectangle.The total photo will have size W × H, where W is the total width of all the people rectangles, and H is the maximum of the heights. The friends want to determine what minimum area the group photo can they obtain if no more than n / 2 of them can lie on the ground (it would be strange if more than n / 2 gentlemen lie on the ground together, isn't it?..)Help them to achieve this goal.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of friends. The next n lines have two integers wi, hi (1 ≤ wi, hi ≤ 1000) each, representing the size of the rectangle, corresponding to the i-th friend.

Print a single integer equal to the minimum possible area of the photo containing all friends if no more than n / 2 of them can lie on the ground.

package main

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

const (
	maxN = 1000
	inf = 2000000000
)

func getString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getInt64(scanner *bufio.Scanner) int64 {
	x, _ := strconv.ParseInt(getString(scanner), 10, 64)
	return x
}

func getInt(scanner *bufio.Scanner) int {
	x, _ := strconv.ParseInt(getString(scanner), 10, 32)
	return int(x)
}

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

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	n := getInt(scanner)
	w := make([]int, maxN + 5)
	h := make([]int, maxN + 5)
	start := 1
	for i := 0; i < n; i++ {
		w[i] = getInt(scanner)
		h[i] = getInt(scanner)
		start = maxInt(start, minInt(w[i], h[i]))
	}
	ans := inf
	for ht := start; ht <= maxN; ht++ {
		ext := []int{}
		taken := 0
		sum := 0
		for i := 0; i < n; i++ {
			if h[i] <= ht {
				if w[i] <= ht {
					ext = append(ext, w[i] - h[i])
				}
				sum += w[i]
			} else {
				taken++
				sum += h[i]
			}
		}
		if taken > n / 2 {
			continue
		}
		sort.Sort(sort.Reverse(sort.IntSlice(ext)))
		for i := 0; i < len(ext) && i < n / 2 - taken && ext[i] > 0; i++ {
			sum -= ext[i];
		}
		ans = minInt(ans, ht * sum)
	}
	fmt.Printf("%d\n", ans)
}

package main

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

const (
	maxN = 1000
)

func getString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getInt64(scanner *bufio.Scanner) int64 {
	x, _ := strconv.ParseInt(getString(scanner), 10, 64)
	return x
}

func getInt(scanner *bufio.Scanner) int {
	x, _ := strconv.ParseInt(getString(scanner), 10, 32)
	return int(x)
}

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

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

func minInt64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	n := getInt(scanner)
	w := make([]int, maxN + 5)
	h := make([]int, maxN + 5)
	start := 1
	for i := 0; i < n; i++ {
		w[i] = getInt(scanner)
		h[i] = getInt(scanner)
		start = maxInt(start, minInt(w[i], h[i]))
	}
	var ans int64
	for ht := start; ht <= maxN; ht++ {
		ext := []int{}
		taken := 0
		sum := 0
		for i := 0; i < n; i++ {
			if h[i] <= ht {
				if w[i] <= ht {
					ext = append(ext, w[i] - h[i])
				}
				sum += w[i]
			} else {
				taken++
				sum += h[i]
			}
		}
		sort.Sort(sort.Reverse(sort.IntSlice(ext)))
		for i := 0; i < len(ext) && i < n / 2 - taken && ext[i] > 0; i++ {
			sum -= ext[i];
		}
		if ht == start {
			ans = int64(ht) * int64(sum)
		} else {
			ans = minInt64(ans, int64(ht) * int64(sum))
		}
	}
	fmt.Printf("%d\n", ans)
}

package main

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

const (
	maxN = 1000
)

func getString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getInt64(scanner *bufio.Scanner) int64 {
	x, _ := strconv.ParseInt(getString(scanner), 10, 64)
	return x
}

func getInt(scanner *bufio.Scanner) int {
	x, _ := strconv.ParseInt(getString(scanner), 10, 32)
	return int(x)
}

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

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	n := getInt(scanner)
	w := make([]int, maxN + 5)
	h := make([]int, maxN + 5)
	start := 1
	for i := 0; i < n; i++ {
		w[i] = getInt(scanner)
		h[i] = getInt(scanner)
		start = maxInt(start, minInt(w[i], h[i]))
	}
	var ans int
	for ht := start; ht <= maxN; ht++ {
		ext := []int{}
		taken := 0
		sum := 0
		for i := 0; i < n; i++ {
			if h[i] <= ht {
				if w[i] <= ht {
					ext = append(ext, w[i] - h[i])
				}
				sum += w[i]
			} else {
				taken++
				sum += h[i]
			}
		}
		sort.Sort(sort.Reverse(sort.IntSlice(ext)))
		for i := 0; i < len(ext) && i < n / 2 - taken && ext[i] > 0; i++ {
			sum -= ext[i];
		}
		if ht == start {
			ans = ht * sum
		} else {
			ans = minInt(ans, ht * sum)
		}
	}
	fmt.Printf("%d\n", ans)
}


Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times:   Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible.

First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$  — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.

Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible.

NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially.

package main

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

var checked []bool
var edges [][]int
var cnt int
var a, b, c, d, e, f []int
var children [][]int

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := int64(1)
	//fmt.Fscanf(in, "%d\n", &t)
	for tt := int64(0); tt < t; tt++ {
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		a, b, c, d, e, f = make([]int, n), make([]int, n), make([]int, n), make([]int, n), make([]int, n), make([]int, n)
		haveOne := 0
		needOne := 0
		//fmt.Println(n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d %d %d\n", &a[i], &b[i], &c[i])
			haveOne += b[i]
			needOne += c[i]
			//fmt.Println(a[i], b[i], c[i])
		}
		edges = make([][]int, n)
		for i := 0; i < n-1; i++ {
			o, p := 0, 0
			fmt.Fscanf(in, "%d %d\n", &o, &p)
			o--
			p--
			edges[o] = append(edges[o], p)
			edges[p] = append(edges[p], o)
		}
		if haveOne != needOne {
			fmt.Fprintf(out, "-1\n")
			continue
		}
		d[0] = haveOne
		f[0] = needOne
		e[0] = n
		children = make([][]int, n)
		children[0] = edges[0]
		checked = make([]bool, n)
		checked[0] = true
		for _, v := range edges[0] {
			countOne(v)
		}
		fmt.Fprintf(out, "%d\n", solve(0, a[0]))
	}
	return
}

func solve(cur int, best int) int64 {
	neededOne := 0
	neededZero := 0
	if b[cur] == 0 && c[cur] == 1 {
		neededOne++
	} else if b[cur] == 1 && c[cur] == 0 {
		neededZero++
	}
	for _, child := range children[cur] {
		if f[child] > d[child] {
			neededOne += f[child] - d[child]
		} else {
			neededZero += d[child] - f[child]
		}
	}
	ans := int64(0)
	ans += int64(min(a[cur], best)) * int64(min(neededOne, neededZero)) * int64(2)
	for _, child := range children[cur] {
		ans += solve(child, min(best, a[cur]))
	}
	return ans
}

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

func countOne(cur int) {
	checked[cur] = true
	d[cur] = b[cur]
	e[cur] = 1
	f[cur] = c[cur]
	for _, v := range edges[cur] {
		if !checked[v] {
			countOne(v)
			d[cur] += d[v]
			e[cur] += e[v]
			f[cur] += f[v]
			children[cur] = append(children[cur], v)
		}
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1363E(_r io.Reader, out io.Writer) {
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			_r.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	r1 := func() (x int8) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		return int8(b & 15)
	}
	type node struct {
		c int
		d int8
	}

	n := r()
	a := make([]node, n)
	d := 0
	for i := range a {
		a[i].c = r()
		if v, w := r1(), r1(); v != w {
			a[i].d = v
			d += int(v - w)
		} else {
			a[i].d = -1
		}
	}
	if d != 0 {
		Fprint(out, -1)
		return
	}
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		v, w := r()-1, r()-1
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	ans := int64(0)
	var f func(v, fa, c int) [2]int
	f = func(v, fa, c int) (cnt [2]int) {
		if d := a[v].d; d >= 0 {
			cnt[d]++
		}
		for _, w := range g[v] {
			if w != fa {
				_c := a[w].c
				if c < _c {
					_c = c
				}
				cc := f(w, v, _c)
				cnt[0] += cc[0]
				cnt[1] += cc[1]
			}
		}
		md := cnt[0]
		if cnt[1] < md {
			md = cnt[1]
		}
		cnt[0] -= md
		cnt[1] -= md
		ans += int64(c) * int64(2*md)
		return
	}
	f(0, -1, a[0].c)
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1363E(_r io.Reader, out io.Writer) {
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			_r.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b || b > '9'; b = rc() {
		}
		for ; '0' <= b && b <= '9'; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	type node struct{ c, d int }
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}

	n := r()
	a := make([]node, n)
	d := 0
	for i := range a {
		a[i].c = r()
		if v, w := r(), r(); v != w {
			a[i].d = v
			d += v - w
		} else {
			a[i].d = -1
		}
	}
	if d != 0 {
		Fprint(out, -1)
		return
	}
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		v, w := r()-1, r()-1
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	ans := int64(0)
	var f func(v, fa, c int) [2]int
	f = func(v, fa, c int) (cnt [2]int) {
		if d := a[v].d; d >= 0 {
			cnt[d]++
		}
		for _, w := range g[v] {
			if w != fa {
				cc := f(w, v, min(c, a[w].c))
				cnt[0] += cc[0]
				cnt[1] += cc[1]
			}
		}
		md := min(cnt[0], cnt[1])
		cnt[0] -= md
		cnt[1] -= md
		ans += int64(c) * int64(2*md)
		return
	}
	f(0, -1, a[0].c)
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1363E(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	type node struct{ c, d int }
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}

	var n, v, w, d int
	Fscan(in, &n)
	a := make([]node, n)
	for i := range a {
		Fscan(in, &a[i].c, &v, &w)
		if v != w {
			a[i].d = v
			d += v - w
		} else {
			a[i].d = 2
		}
	}
	if d != 0 {
		Fprint(out, -1)
		return
	}
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	ans := int64(0)
	var f func(v, fa, c int) [3]int
	f = func(v, fa, c int) (cnt [3]int) {
		cnt[a[v].d]++
		for _, w := range g[v] {
			if w != fa {
				cc := f(w, v, min(c, a[w].c))
				cnt[0] += cc[0]
				cnt[1] += cc[1]
			}
		}
		md := min(cnt[0], cnt[1])
		ans += int64(c) * int64(2*md)
		cnt[0] -= md
		cnt[1] -= md
		return
	}
	f(0, -1, a[0].c)
	Fprint(out, ans)
}

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

package main

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

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

func main() {
	defer out.Flush()
	inn.Buffer([]byte{}, 10000000)
	inn.Split(bufio.ScanWords)

	n := rd()
	G := make([][]int, n+1)
	a := make([]int64, n+1)
	b := make([]int, n+1)
	a[0] = int64(1e9)
	var ans int64
	for i := 1; i <= n; i++ {
		a[i] = rdll()
		y, z := rd(), rd()
		b[i] = y - z
	}
	for i := 0; i < n-1; i++ {
		x, y := rd(), rd()
		G[x] = append(G[x], y)
		G[y] = append(G[y], x)
	}
	var dfs func(u, fa int) int
	dfs = func(u, fa int) int {
		a[u] = min64(a[u], a[fa])
		var pos, neg int
		if b[u] == 1 {
			pos++
		} else if b[u] == -1 {
			neg++
		}
		for _, to := range G[u] {
			if to != fa {
				res := dfs(to, u)
				if res > 0 {
					pos += res
				} else {
					neg -= res
				}
			}
		}
		ans += int64(2*min(pos, neg)) * a[u]
		return pos - neg
	}
	if dfs(1, 0) != 0 {
		Fprint(out, -1)
	} else {
		Fprint(out, ans)
	}
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func min64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func rd() (x int) {
	inn.Scan()
	data := inn.Bytes()
	x, _ = strconv.Atoi(string(data))
	return x
}
func rdll() (x int64) {
	inn.Scan()
	data := inn.Bytes()
	x, _ = strconv.ParseInt(string(data), 10, 64)
	return x
}
func rds() string {
	inn.Scan()
	return string(inn.Bytes())
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"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') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

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

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

	return i
}

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

	n := readNum(reader)

	X := make([][]int, n)
	for i := 0; i < n; i++ {
		X[i] = readNNums(reader, 3)
	}
	E := make([][]int, n-1)
	for i := 0; i < n-1; i++ {
		E[i] = readNNums(reader, 2)
	}
	fmt.Println(solve(n, X, E))
}

func solve(n int, X [][]int, E [][]int) int64 {
	adj := getAdj(n, E)
	has := make([][]int, n)
	need := make([][]int, n)
	for i := 0; i < n; i++ {
		has[i] = make([]int, 2)
		need[i] = make([]int, 2)
	}

	var dfs1 func(p, u int)
	dfs1 = func(p, u int) {

		if X[u][1] < X[u][2] {
			has[u][0]++
			need[u][1]++
		} else if X[u][1] > X[u][2] {
			has[u][1]++
			need[u][0]++
		}

		for _, v := range adj[u] {
			if p == v {
				continue
			}
			dfs1(u, v)
			for j := 0; j <= 1; j++ {
				has[u][j] += has[v][j]
				need[u][j] += need[v][j]
			}
		}
	}

	dfs1(-1, 0)

	if has[0][0] != need[0][0] || has[0][1] != need[0][1] {
		return -1
	}

	var res int64
	var dfs2 func(p, u, x int) int

	dfs2 = func(p, u, x int) int {
		var handled int
		for _, v := range adj[u] {
			if p == v {
				continue
			}
			handled += dfs2(u, v, min(x, X[u][0]))
		}
		if X[u][0] < x {
			// 当前节点是最小的cost，把剩余没有处理的节点处理掉
			// has[0], has[1], need[0], need[1]
			// min(has[0], need[0]) + min(has[1], need[1])
			y := min(has[u][0], need[u][0]) + min(has[u][1], need[u][1]) - handled
			res += int64(y) * int64(X[u][0])
			handled += y
		}
		return handled
	}

	dfs2(-1, 0, math.MaxInt32)

	return res
}

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

func getAdj(n int, E [][]int) [][]int {
	degree := make([]int, n)
	for _, e := range E {
		u, v := e[0]-1, e[1]-1
		degree[u]++
		degree[v]++
	}

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

	for _, e := range E {
		u, v := e[0]-1, e[1]-1
		adj[u] = append(adj[u], v)
		adj[v] = append(adj[v], u)
	}
	return adj
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"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') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

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

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

	return i
}

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

	n := readNum(reader)

	X := make([][]int, n)
	for i := 0; i < n; i++ {
		X[i] = readNNums(reader, 3)
	}
	E := make([][]int, n-1)
	for i := 0; i < n-1; i++ {
		E[i] = readNNums(reader, 2)
	}
	fmt.Println(solve(n, X, E))
}

func solve(n int, X [][]int, E [][]int) int64 {
	adj := getAdj(n, E)
	has := make([][]int, n)
	need := make([][]int, n)
	for i := 0; i < n; i++ {
		has[i] = make([]int, 2)
		need[i] = make([]int, 2)
	}

	var dfs1 func(p, u int)
	dfs1 = func(p, u int) {

		if X[u][1] < X[u][2] {
			has[u][0]++
			need[u][1]++
		} else if X[u][1] > X[u][2] {
			has[u][1]++
			need[u][0]++
		}

		for _, v := range adj[u] {
			if p == v {
				continue
			}
			dfs1(u, v)
			for j := 0; j <= 1; j++ {
				has[u][j] += has[v][j]
				need[u][j] += need[v][j]
			}
		}
	}

	dfs1(-1, 0)

	if has[0][0] != need[0][0] || has[0][1] != need[0][1] {
		return -1
	}

	var res int64
	var dfs2 func(p, u, x int) int

	dfs2 = func(p, u, x int) int {
		var handled int
		for _, v := range adj[u] {
			if p == v {
				continue
			}
			handled += dfs2(u, v, min(x, X[u][0]))
		}
		if X[u][0] < x {
			// 当前节点是最小的cost，把剩余没有处理的节点处理掉
			// has[0], has[1], need[0], need[1]
			// min(has[0], need[0]) + min(has[1], need[1])
			y := min(has[u][0], need[u][0]) + min(has[u][1], need[u][1]) - handled
			res += int64(y) * int64(X[u][0])
			handled = y
		}
		return handled
	}

	dfs2(-1, 0, math.MaxInt32)

	return res
}

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

func getAdj(n int, E [][]int) [][]int {
	degree := make([]int, n)
	for _, e := range E {
		u, v := e[0]-1, e[1]-1
		degree[u]++
		degree[v]++
	}

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

	for _, e := range E {
		u, v := e[0]-1, e[1]-1
		adj[u] = append(adj[u], v)
		adj[v] = append(adj[v], u)
	}
	return adj
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"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') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

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

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

	return i
}

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

	n := readNum(reader)

	X := make([][]int, n)
	for i := 0; i < n; i++ {
		X[i] = readNNums(reader, 3)
	}
	E := make([][]int, n-1)
	for i := 0; i < n-1; i++ {
		E[i] = readNNums(reader, 2)
	}
	fmt.Println(solve(n, X, E))
}

func solve(n int, X [][]int, E [][]int) int64 {
	adj := getAdj(n, E)
	cnt := make([]int, n)
	diff := make([]int, n)

	var dfs1 func(p, u int)
	dfs1 = func(p, u int) {
		if X[u][1] != X[u][2] {
			diff[u]++
		}

		cnt[u] += X[u][2] - X[u][1]
		for _, v := range adj[u] {
			if p == v {
				continue
			}
			dfs1(u, v)
			diff[u] += diff[v]
			cnt[u] += cnt[v]
		}
	}

	dfs1(-1, 0)

	if cnt[0] != 0 {
		return -1
	}

	var res int64
	var dfs2 func(p, u, x int) int

	dfs2 = func(p, u, x int) int {
		var handled int
		for _, v := range adj[u] {
			if p == v {
				continue
			}
			handled += dfs2(u, v, min(x, X[u][0]))
		}
		if cnt[u] == 0 {
			//can handle at node u
			if X[u][0] < x {
				// 当前节点是最小的cost，把剩余没有处理的节点处理掉
				tmp := diff[u] - handled
				res += int64(tmp) * int64(X[u][0])
				handled += tmp
			}
			// else 让更上层的节点处理剩余的部分
		}
		return handled
	}

	dfs2(-1, 0, math.MaxInt32)

	return res
}

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

func getAdj(n int, E [][]int) [][]int {
	degree := make([]int, n)
	for _, e := range E {
		u, v := e[0]-1, e[1]-1
		degree[u]++
		degree[v]++
	}

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

	for _, e := range E {
		u, v := e[0]-1, e[1]-1
		adj[u] = append(adj[u], v)
		adj[v] = append(adj[v], u)
	}
	return adj
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"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') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

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

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

	return i
}

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

	n := readNum(reader)

	X := make([][]int, n)
	for i := 0; i < n; i++ {
		X[i] = readNNums(reader, 3)
	}
	E := make([][]int, n-1)
	for i := 0; i < n-1; i++ {
		E[i] = readNNums(reader, 2)
	}
	fmt.Println(solve(n, X, E))
}

func solve(n int, X [][]int, E [][]int) int64 {
	adj := getAdj(n, E)
	cnt := make([]int, n)
	diff := make([]int, n)

	var dfs1 func(p, u int)
	dfs1 = func(p, u int) {
		if X[u][1] != X[u][2] {
			diff[u]++
		}

		cnt[u] += X[u][2] - X[u][1]
		for _, v := range adj[u] {
			if p == v {
				continue
			}
			dfs1(u, v)
			diff[u] += diff[v]
			cnt[u] += cnt[v]
		}
	}

	dfs1(-1, 0)

	if cnt[0] != 0 {
		return -1
	}

	var res int64
	var dfs2 func(p, u, x int) int

	dfs2 = func(p, u, x int) int {
		var handled int
		for _, v := range adj[u] {
			if p == v {
				continue
			}
			handled += dfs2(u, v, min(x, X[u][0]))
		}
		if cnt[u] == 0 {
			//can handle at node u
			if X[u][0] < x && diff[u] > 0 {
				// 当前节点是最小的cost，把剩余没有处理的节点处理掉
				tmp := diff[u] - handled
				res += int64(tmp) * int64(X[u][0])
				handled += tmp
			}
			// else 让更上层的节点处理剩余的部分
		}
		return handled
	}

	dfs2(-1, 0, math.MaxInt32)

	return res
}

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

func getAdj(n int, E [][]int) [][]int {
	degree := make([]int, n)
	for _, e := range E {
		u, v := e[0]-1, e[1]-1
		degree[u]++
		degree[v]++
	}

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

	for _, e := range E {
		u, v := e[0]-1, e[1]-1
		adj[u] = append(adj[u], v)
		adj[v] = append(adj[v], u)
	}
	return adj
}


This is the hard version of Problem F. The only difference between the easy version and the hard version is the constraints.We will call a non-empty string balanced if it contains the same number of plus and minus signs. For example: strings "+--+" and "++-+--" are balanced, and strings "+--", "--" and "" are not balanced.We will call a string promising if the string can be made balanced by several (possibly zero) uses of the following operation:  replace two adjacent minus signs with one plus sign. In particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced.For example, the string "-+---" is promising, because you can replace two adjacent minuses with plus and get a balanced string "-++-", or get another balanced string "-+-+".How many non-empty substrings of the given string $$$s$$$ are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string $$$s$$$.Recall that a substring is a sequence of consecutive characters of the string. For example, for string "+-+" its substring are: "+-", "-+", "+", "+-+" (the string is a substring of itself) and some others. But the following strings are not its substring: "--", "++", "-++".

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. Then the descriptions of test cases follow. Each test case of input data consists of two lines. The first line consists of the number $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$): the length of $$$s$$$. The second line of the test case contains the string $$$s$$$ of length $$$n$$$, consisting only of characters "+" and "-". It is guaranteed that the sum of values $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single number: the number of the promising non-empty substrings of string $$$s$$$. Each non-empty promising substring must be counted in the answer as many times as it occurs in string $$$s$$$.

package main
import("bufio";."fmt";"os")

// github.com/EndlessCheng/codeforces-go
func main(){
	in:=bufio.NewReader(os.Stdin)
	T,n,S:=0,0,""
	for Fscan(in,&T);T>0;T--{
		Fscan(in,&n,&S)
		s:=make([]int,n+1)
		for i,b:=range S{s[i+1]=s[i]+int(b&3)-2}
		t:=[3][]int{}
		for i:=range t{t[i]=make([]int,n*2+2)}
		ans:=int64(0)
		for i:=n;i>=0;i--{
			j,k:=(s[i]%3+3)%3,s[i]+n+1
			for k:=k;k>0;k&=k-1{ans+=int64(t[j][k])}
			for;k<n*2+2;k+=k&-k{t[j][k]++}
		}
		Println(ans)
	}
}

package main

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

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

	var T, n int
	var s string
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &s)
		sum := make([]int, n+1)
		for i, b := range s {
			sum[i+1] = sum[i] + int(b&3) - 2
		}
		ans := int64(0)
		t := [3][]int{}
		for i := range t {
			t[i] = make([]int, n*2+2)
		}
		for i := n; i >= 0; i-- {
			j, k := (sum[i]%3+3)%3, sum[i]+n+1
			for k := k; k > 0; k &= k - 1 {
				ans += int64(t[j][k])
			}
			for ; k < len(t[j]); k += k & -k {
				t[j][k]++
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

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

func solve() {
	var n int
	var s string
	Fscan(in, &n, &s)
	pref := make([]int, n+1)
	for i, c := range s {
		pref[i+1] = pref[i]
		if c == '+' {
			pref[i+1] += 1
		} else {
			pref[i+1] -= 1
		}
	}
	t := [3][]int{}
	for i := range t {
		t[i] = make([]int, 2*n+2)
	}
	offset := n + 1
	ans := int64(0)
	//matching boundaries to with %3 and greater than cur (fenwick tree) distributed on 0,1,2
	for i := 0; i <= n; i++ {
		rem, num := ((pref[i]%3)+3)%3, pref[i]+offset

		//accumulate in answer
		for j := num; j <= 2*n+1; j += (j & -j) {
			ans += int64(t[rem][j])
		}

		//update the tree backwards
		for j := num; j > 0; j -= (j & -j) {
			t[rem][j]++
		}
	}
	Fprintln(out, ans)

}
func main() {
	defer out.Flush()
	var t int
	Fscan(in, &t)
	for tt := 0; tt < t; tt++ {
		solve()
	}
}


Let's call a binary string $$$T$$$ of length $$$m$$$ indexed from $$$1$$$ to $$$m$$$ paranoid if we can obtain a string of length $$$1$$$ by performing the following two kinds of operations $$$m-1$$$ times in any order : Select any substring of $$$T$$$ that is equal to 01, and then replace it with 1. Select any substring of $$$T$$$ that is equal to 10, and then replace it with 0.For example, if $$$T = $$$ 001, we can select the substring $$$[T_2T_3]$$$ and perform the first operation. So we obtain $$$T = $$$ 01.You are given a binary string $$$S$$$ of length $$$n$$$ indexed from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ $$$1 \le l \le r \le n$$$ such that $$$S[l \ldots r]$$$ (the substring of $$$S$$$ from $$$l$$$ to $$$r$$$) is a paranoid string.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of $$$S$$$. The second line of each test case contains a binary string $$$S$$$ of $$$n$$$ characters $$$S_1S_2 \ldots S_n$$$. ($$$S_i = $$$ 0 or $$$S_i = $$$ 1 for each $$$1 \le i \le n$$$) It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, output the number of pairs of integers $$$(l, r)$$$ $$$1 \le l \le r \le n$$$ such that $$$S[l \ldots r]$$$ (the substring of $$$S$$$ from $$$l$$$ to $$$r$$$) is a paranoid string.

NoteIn the first sample, $$$S$$$ already has length $$$1$$$ and doesn't need any operations.In the second sample, all substrings of $$$S$$$ are paranoid. For the entire string, it's enough to perform the first operation.In the third sample, all substrings of $$$S$$$ are paranoid except $$$[S_2S_3]$$$, because we can't perform any operations on it, and $$$[S_1S_2S_3]$$$ (the entire string).

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		var s string
		fmt.Fscan(in, &n, &s)

		var tot int64
		tot += int64(n)
		for i := 1; i < n; i++ {
			if s[i] != s[i-1] {
				tot += int64(i)
			}
		}

		fmt.Fprintln(out, tot)
	}
}

package main

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

/*
3
6
011010
5
01111
4
1000
---
19
6
4
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n int64
	var s string
	scanf("%d\n%s\n", &n, &s)

	ans := n

	for i := range s {
		if i != 0 && s[i-1] != s[i] {
			ans += int64(i)
		}
	}

	fmt.Fprintln(writer, ans)
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func sum(nums ...int) (sum int) {
	for _, num := range nums {
		sum += num
	}
	return
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int64) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := int64(5); i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int64) []int64 {
	factors := make([]int64, 0)

	for ftr := int64(2); ftr*ftr <= num; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > 1 {
		factors = append(factors, num)
	}

	return factors
}

package main

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var ntests int
	fmt.Fscan(scanner, &ntests)
	for iter := 0; iter < ntests; iter++ {
		var n int
		fmt.Fscan(scanner, &n)
		var s string
		fmt.Fscan(scanner, &s)
		res := int64(0)
		prev := ' '
		for i, r := range s {
			if prev == r {
				res++
			} else {
				res = res + int64(i) + 1
			}
			prev = r
		}
		fmt.Fprintln(writer, res)
	}
}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func solve() {
	var n int64
	var s string
	fmt.Fscan(r, &n)
	fmt.Fscan(r, &s)
	dp := make([]int64,n)
	dp[0] = 1
	var i int64
	for i = 1; i < n; i++ {
		if s[i] == s[i-1] {
			dp[i] = dp[i-1]+1
		} else {
			dp[i] = dp[i-1] + 1 + i
		}
	}
	fmt.Fprintln(w,dp[n-1])

}
func main() {
	defer w.Flush()
	var T int
	fmt.Fscan(r, &T)
	for i := 0; i < T ;i++ {
		solve()
	}
}

package main

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

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

func scan(a ...interface{}) {
	fmt.Fscan(in, a...)
}
func printf(f string, a ...interface{}) {
	fmt.Fprintf(out, f, a...)
}
func solve() {
	var n int64
	scan(&n)
	result := n * (n + 1) / 2
	var s string
	scan(&s)
	for i := 1; i < int(n); i++ {
		if s[i] == s[i-1] {
			result -= int64(i)
		}
	}
	printf("%d\n", result)
}
func main() {
	defer out.Flush()
	n := 0
	scan(&n)
	for i := 0; i < n; i++ {
		solve()
	}
}

package main

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

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

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

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n int
		var s string
		fmt.Fscan(r, &n, &s)
		w1 := do(n, s)
		fmt.Fprintln(w, w1)
	}
}

func do(n int, s string) int64 {
	if n == 1 {
		return 1
	}
	var ans int64
	for i := range s {
		ans += 1
		if i > 0 && s[i] != s[i-1] {
			ans += int64(i)
		}
	}
	return ans
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	for k := 0; k < n; k++ {
		var a int64
		var s string
		fmt.Scan(&a)
		fmt.Scan(&s)
		var count int64 = 1
		for i := 1; int64(i) < a; i++ {
			if s[i] != s[i-1] {
				count += int64(i) + 1
			} else {
				count++
			}
		}
		fmt.Println(count)
	}
}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func solve() {
	var (
		n int
		s string
	)
	fmt.Fscan(r, &n, &s)
	var ans int64 = 1
	for i := 1; i < n; i++ {
		ans++
		if s[i] != s[i-1] {
			ans += int64(i)
		}
	}
	fmt.Fprintln(w, ans)
}
func main() {
	defer w.Flush()
	var t int
	fmt.Fscan(r, &t)
	for ; t > 0; t-- {
		solve()
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gi2() (int,int) { return gi(),gi() }
func gi3() (int,int,int) { return gi(),gi(),gi() }
func gi4() (int,int,int,int) { return gi(),gi(),gi(),gi() }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func gf() float64 { f,e := strconv.ParseFloat(gs(),64); if e != nil {panic(e)}; return f }
func gbs() []byte { return []byte(gs()) }
func gfs(n int) []float64  { res := make([]float64,n); for i:=0;i<n;i++ { res[i] = gf() }; return res }
func gss(n int) []string  { res := make([]string,n); for i:=0;i<n;i++ { res[i] = gs() }; return res }
func ia(m int) []int { return make([]int,m) }
func iai(m int,v int) []int { a := make([]int,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi(n int,m int,v int) [][]int {
	r := make([][]int,n); for i:=0;i<n;i++ { x := make([]int,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill2(m int) ([]int,[]int) { a,b := ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i] = gi(),gi()}; return a,b }
func fill3(m int) ([]int,[]int,[]int) { a,b,c := ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi(),gi(),gi()}; return a,b,c }
func fill4(m int) ([]int,[]int,[]int,[]int) { a,b,c,d := ia(m),ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi(),gi(),gi(),gi()}; return a,b,c,d }
func abs(a int) int { if a < 0 { return -a }; return a }
func rev(a []int) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max(a,b int) int { if a > b { return a }; return b }
func min(a,b int) int { if a > b { return b }; return a }
func tern(cond bool, a int, b int) int { if cond { return a }; return b }
func terns(cond bool, a string, b string) string { if cond { return a }; return b }
func maxarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr(a []int) int { ans := 0; for _,aa := range(a) { ans += aa }; return ans }
func zeroarr(a []int) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod(a,e,mod int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint(a,e int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd(a,b int) int { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended(a,b int) (int,int,int) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv(a,m int) (int,bool) { g,x,_ := gcdExtended(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func makefact(n int,mod int) ([]int,[]int) {
	fact,factinv := make([]int,n+1),make([]int,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * i % mod }
	factinv[n] = powmod(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * (i+1) % mod }
	return fact,factinv
}
func vecintstring(a []int) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.Itoa(a) }; return strings.Join(astr," ") }
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N := gi(); S := gs(); ans := int64(N)
		for i:=1;i<N;i++ {
			if S[i] != S[i-1] { ans += int64(i) }
		}
		fmt.Fprintln(wrtr,ans)
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		var s string
		fmt.Fscan(in, &n, &s)

		tot := n
		for i := 1; i < n; i++ {
			if s[i] != s[i-1] {
				tot += i
			}
		}

		fmt.Fprintln(out, tot)
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		var s string
		fmt.Fscan(in, &n, &s)

		var x, y int
		for i, ch := range s {
			if ch == '0' {
				x = i
			} else {
				y = i
			}
		}
		tot := n
		for i := 0; i < n-1; i++ {
			// if s[i] == '0' && s[i+1] == '1' && i < x || s[i] == '1' && s[i+1] == '0' && i < y {
			// 	tot++
			// }
			if s[i] == '0' && i < y {
				tot++
			} else if s[i] == '1' && i < x {
				tot++
			}
		}

		if n > 2 && s[n-1] != s[n-2] {
			tot++
		}

		fmt.Fprintln(out, tot)
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		var s string
		fmt.Fscan(in, &n, &s)

		tot := n
		var z int
		for i := 0; i < n-1; i++ {
			if s[i] == '0' && s[i+1] == '1' || s[i] == '1' && s[i+1] == '0' {
				z++
			}
		}

		tot += z * (z + 1) / 2
		for i := n - 1; i > 0; i-- {
			if s[i] == '1' {
				j := i - 1
				var c int
				for j >= 0 && s[j] == '0' {
					c++
					j--
				}
				if c > 0 {
					tot += c - 1
				}
				i = j + 1
			}
		}
		fmt.Fprintln(out, tot)
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		var s string
		fmt.Fscan(in, &n, &s)

		tot := n
		for i := 0; i < n-1; i++ {
			if s[i] == '1' {
				j := i + 1
				for j < n && s[j] != '1' {
					j++
				}
				if j < n {
					tot += j - i - 1
				} else {
					tot++
				}
				i = j
			}
		}

		for i := n - 1; i > 0; i-- {
			if s[i] == '1' {
				j := i - 1
				for j >= 0 && s[j] == '0' {
					tot++
					j--
				}
				i = j + 1
			}
		}
		fmt.Fprintln(out, tot)
	}
}

package main

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

/*
3
6
011010
5
01111
4
1000
---
20 == 6 + 4 + 1+1+1 + 1+1+1 + 1+1  +1?  011010
5
4

011010 -> 00

01->1   00001->1  01111 -> X
10->0   1000->X 1110 -> 0

*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n int64
	var s string
	scanf("%d\n%s\n", &n, &s)

	x := int64(0)

	curLen := int64(1)
	prev := '-'

	oneCnt := int64(0)

	for _, r := range s {
		if r == '1' {
			oneCnt++
		}

		if r == prev {
			curLen++
		} else if curLen > 1 {
			x += (curLen*(curLen+1))/2 - curLen + 1

			curLen = 1
		}

		prev = r
	}

	if (n > 2 && s[0] == '1' && oneCnt == 1) || (n > 2 && s[0] == '0' && oneCnt == n-1) {
		fmt.Fprintln(writer, n+1)
		return
	}

	if curLen > 1 {
		x += (curLen*(curLen+1))/2 - curLen + 1
		if curLen == n {
			x--
		}
		curLen = 1
	}

	ans := n*(n+1)/2 - x

	fmt.Fprintln(writer, ans)
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func sum(nums ...int) (sum int) {
	for _, num := range nums {
		sum += num
	}
	return
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int64) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := int64(5); i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int64) []int64 {
	factors := make([]int64, 0)

	for ftr := int64(2); ftr*ftr <= num; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > 1 {
		factors = append(factors, num)
	}

	return factors
}

package main

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

/*
1
6
011010
---
19 == 6 + 4 + 1+1+1 + 1+1+1 + 1+1  +1?  011010

011010 -> 00

01->1   00001->1  01111 -> X
10->0   1000->X 1110 -> 0

11111

16 - (16-1-5 ) = 16 - 10

1
5
11111

1
4
1001

1
3
100
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n int64
	var s string
	scanf("%d\n%s\n", &n, &s)

	x := int64(0)

	curLen := int64(1)
	prev := '-'

	for _, r := range s {
		if r == prev {
			curLen++
		} else if curLen > 1 {
			x += (curLen*(curLen+1))/2 - curLen + 1

			curLen = 1
		}

		prev = r
	}

	if curLen > 1 {
		x += (curLen*(curLen+1))/2 - curLen + 1
		if curLen == n {
			x--
		}
		curLen = 1
	}

	ans := n*(n+1)/2 - x

	fmt.Fprintln(writer, ans)
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func sum(nums ...int) (sum int) {
	for _, num := range nums {
		sum += num
	}
	return
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int64) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := int64(5); i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int64) []int64 {
	factors := make([]int64, 0)

	for ftr := int64(2); ftr*ftr <= num; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > 1 {
		factors = append(factors, num)
	}

	return factors
}

package main

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

/*
1
6
011010
---
19 == 6 + 4 + 1+1+1 + 1+1+1 + 1+1  +1?  011010

011010 -> 00

01->1   00001->1  01111 -> X
10->0   1000->X 1110 -> 0

11111

16 - (16-1-5 ) = 16 - 10

1
5
11111

1
4
1001

1
3
100
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n int64
	var s string
	scanf("%d\n%s\n", &n, &s)

	x := int64(0)

	curLen := int64(1)
	prev := '-'

	for _, r := range s {
		if r == prev {
			curLen++
		} else if curLen > 1 {
			x += (curLen*(curLen+1))/2 - curLen + 1
			if curLen == n {
				curLen--
			}

			curLen = 1
		}

		prev = r
	}

	if curLen > 1 {
		x += (curLen*(curLen+1))/2 - curLen + 1
		curLen = 1
	}

	ans := n*(n+1)/2 - x

	fmt.Fprintln(writer, ans)
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func sum(nums ...int) (sum int) {
	for _, num := range nums {
		sum += num
	}
	return
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int64) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := int64(5); i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int64) []int64 {
	factors := make([]int64, 0)

	for ftr := int64(2); ftr*ftr <= num; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > 1 {
		factors = append(factors, num)
	}

	return factors
}

package main

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var ntests int
	fmt.Fscan(scanner, &ntests)
	for iter := 0; iter < ntests; iter++ {
		var n int
		fmt.Fscan(scanner, &n)
		var s string
		fmt.Fscan(scanner, &s)
		res := 0
		prev := ' '
		for i, r := range s {
			if prev == r {
				res++
			} else {
				res = res + i + 1
			}
			prev = r
		}
		fmt.Fprintln(writer, res)
	}
}

package main

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var ntests int
	fmt.Fscan(scanner, &ntests)
	for iter := 0; iter < ntests; iter++ {
		var n int
		fmt.Fscan(scanner, &n)
		var s string
		fmt.Fscan(scanner, &s)
		res := 0
		prev := ' '
		for i, r := range s {
			fmt.Printf("%c_%c\n", prev, r)
			if prev == r {
				res++
			} else {
				res = res + i + 1
			}
			prev = r
		}
		fmt.Fprintln(writer, res)
	}
}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func solve() {
	var n int32
	var s string
	fmt.Fscan(r, &n)
	fmt.Fscan(r, &s)
	dp := make([]int32,n)
	dp[0] = 1
	var i int32
	for i = 1; i < n; i++ {
		if s[i] == s[i-1] {
			dp[i] = dp[i-1]+1
		} else {
			dp[i] = dp[i-1] + 1 + i
		}
	}
	fmt.Fprintln(w,dp[n-1])

}
func main() {
	defer w.Flush()
	var T int
	fmt.Fscan(r, &T)
	for i := 0; i < T ;i++ {
		solve()
	}
}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func solve() {
	var n int
	var s string
	fmt.Fscan(r, &n)
	fmt.Fscan(r, &s)
	dp := make([]int,n)
	dp[0] = 1
	for i := 1; i < n; i++ {
		if s[i] == s[i-1] {
			dp[i] = dp[i-1]+1
		} else {
			dp[i] = dp[i-1] + 1 + i
		}
	}
	fmt.Fprintln(w,dp[n-1])

}
func main() {
	defer w.Flush()
	var T int
	fmt.Fscan(r, &T)
	for i := 0; i < T ;i++ {
		solve()
	}
}

package main

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

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

func scan(a ...interface{}) {
	fmt.Fscan(in, a...)
}
func printf(f string, a ...interface{}) {
	fmt.Fprintf(out, f, a...)
}
func solve() {
	var n int
	scan(&n)
	result := n * (n + 1) / 2
	var s string
	scan(&s)
	for i := 1; i < n; i++ {
		if s[i] == s[i-1] {
			result -= i
		}
	}
	printf("%d\n", result)
}
func main() {
	defer out.Flush()
	n := 0
	scan(&n)
	for i := 0; i < n; i++ {
		solve()
	}
}

package main

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

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

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

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n int
		var s string
		fmt.Fscan(r, &n, &s)
		w1 := do(n, s)
		fmt.Fprintln(w, w1)
	}
}

func do(n int, s string) int64 {
	if n == 1 {
		return 1
	}
	d := make([][2]int64, n)
	for i, c := range s {
		c -= '0'
		d[i][c] += 1
		if i > 0 {
			d[i][c] += d[i-1][1-c]
		}
		if i > 1 && s[i] != s[i-1] {
			d[i][c] += d[i-2][1-c]
		}
	}
	// log.Print(d)
	var ans int64
	for _, v := range d {
		ans += v[0] + v[1]
	}
	return ans
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	for k := 0; k < n; k++ {
		var a int64
		var s string
		fmt.Scan(&a)
		fmt.Scan(&s)
		count := 1
		for i := 1; int64(i) < a; i++ {
			if s[i] != s[i-1] {
				count += i + 1
			} else {
				count++
			}
		}
		fmt.Println(count)
	}
}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func solve() {
	var (
		n int
		s string
	)
	fmt.Fscan(r, &n, &s)
	ans := 1
	for i := 1; i < n; i++ {
		ans++
		if s[i] != s[i-1] {
			ans += i
		}
	}
	fmt.Fprintln(w, ans)
}
func main() {
	defer w.Flush()
	var t int
	fmt.Fscan(r, &t)
	for ; t > 0; t-- {
		solve()
	}
}