```go
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"sort"
)
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var buf bytes.Buffer
func scanf(f string, a ...interface{}) { fmt.Fscan(reader, a...) }
func print(a ...interface{}) { fmt.Fprint(&buf, a...) }
func main() {
var s string
scanf("%s", &s)
var q int
scanf("%d", &q)
positions := make(map[string][]int)
n := len(s)
for l := 1; l <= 4; l++ {
for i := 0; i <= n-l; i++ {
sub := s[i:i+l]
positions[sub] = append(positions[sub], i)
}
}
for _, list := range positions {
sort.Ints(list)
}
for _i := 0; _i < q; _i++ {
var ai, bi string
scanf("%s%s", &ai, &bi)
val := process(ai, bi, positions)
print(val, "\n")
}
os.Stdout.Write(buf.Bytes())
}
func process(ai, bi string, positions map[string][]int) int {
posA, ok := positions[ai]
if !ok || len(posA) == 0 {
return -1
}
posB, ok := positions[bi]
if !ok || len(posB) == 0 {
return -1
}
lenA := len(ai)
lenB := len(bi)
LA := lenA - 1
LB := lenB - 1
m := len(posA)
n := len(posB)
posA = posA[:]
posB = posB[:]
if m > n {
posA, posB = posB, posA
LA, LB = LB, LA
lenA, lenB = lenB, lenA
m, n = n, m
}
maxInter := 0
j := 0
for i := 0; i < m; i++ {
startA := posA[i]
endA := startA + lenA - 1
minB := startA - LB
for ; j < n && posB[j] < minB; j++ {
}
k := j
for ; k < n && posB[k] <= endA; k++ {
startB := posB[k]
endB := startB + lenB - 1
inter := min(endA, endB) - max(startA, startB) + 1
if inter > 0 {
maxInter = max(maxInter, inter)
}
}
}
if maxInter > 0 {
return lenA + lenB - maxInter
}
const INF = 1000000000
minGap1 := INF
j1 := 0
for i := 0; i < m; i++ {
endA := posA[i] + LA
for ; j1 < n && posB[j1] <= endA; j1++ {
}
if j1 < n {
gap := posB[j1] - endA - 1
minGap1 = min(minGap1, gap)
}
}
minGap2 := INF
j2 := 0
for i := 0; i < m; i++ {
startA := posA[i]
limit := startA - LB
for ; j2 < n && posB[j2] < limit; j2++ {
}
if j2-1 >= 0 {
endB := posB[j2-1] + LB
gap := startA - endB - 1
if gap >= 0 {
minGap2 = min(minGap2, gap)
}
}
}
minGap := min(minGap1, minGap2)
if minGap == INF {
return -1
}
return lenA + lenB + minGap
}
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
}
```