← Home
```go
package main

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

type FastScanner struct {
	r *bufio.Reader
}

func NewFastScanner() *FastScanner {
	return &FastScanner{r: bufio.NewReaderSize(os.Stdin, 1<<20)}
}

func (fs *FastScanner) NextInt() int {
	sign := 1
	val := 0
	c, _ := fs.r.ReadByte()
	for (c < '0' || c > '9') && c != '-' {
		c, _ = fs.r.ReadByte()
	}
	if c == '-' {
		sign = -1
		c, _ = fs.r.ReadByte()
	}
	for c >= '0' && c <= '9' {
		val = val*10 + int(c-'0')
		c, _ = fs.r.ReadByte()
	}
	return sign * val
}

func main() {
	in := NewFastScanner()
	out := bufio.NewWriterSize(os.Stdout, 1<<20)
	defer out.Flush()

	t := in.NextInt()
	for ; t > 0; t-- {
		n := in.NextInt()
		p := make([]int, n+1)
		identity := true
		for i := 1; i <= n; i++ {
			p[i] = in.NextInt()
			if p[i] != i {
				identity = false
			}
		}
		twoN := 2 * n
		if identity {
			ans := int64(twoN) * int64(twoN+1) / 2
			fmt.Fprintln(out, ans)
			continue
		}

		dmin := n + 1
		dmax := 0
		sVal := -1
		ok := true
		for i := 1; i <= n; i++ {
			if p[i] != i {
				if i < dmin {
					dmin = i
				}
				if i > dmax {
					dmax = i
				}
				sum := i + p[i]
				if sVal == -1 {
					sVal = sum
				} else if sVal != sum {
					ok = false
				}
			}
		}

		width0 := int64(0)
		if ok {
			width0 = 1
		}

		Lmax := dmin + n
		if Lmax > twoN-1 {
			Lmax = twoN - 1
		}
		var width1 int64 = 0
		if Lmax >= 1 {
			R0 := dmax + 1
			// Part A: l in [1, min(Lmax, R0-2)]
			aCount := 0
			if R0-2 >= 1 {
				aCount = R0 - 2
				if aCount > Lmax {
					aCount = Lmax
				}
			}
			if aCount > 0 {
				width1 += int64(aCount) * int64(twoN-R0+1)
			}
			// Part B: l in [max(1, R0-1), Lmax]
			l0 := R0 - 1
			if l0 < 1 {
				l0 = 1
			}
			if Lmax >= l0 {
				bCount := Lmax - l0 + 1
				sumL := int64(l0+Lmax) * int64(bCount) / 2
				width1 += int64(bCount)*int64(twoN) - sumL
			}
		}

		fmt.Fprintln(out, width0+width1)
	}
}
```