← Home
package main

import (
	"io"
	"os"
)

var buf []byte
var bufIdx int

func nextInt() int {
	for bufIdx < len(buf) && (buf[bufIdx] < '0' || buf[bufIdx] > '9') {
		bufIdx++
	}
	if bufIdx >= len(buf) {
		return 0
	}
	res := 0
	for bufIdx < len(buf) && buf[bufIdx] >= '0' && buf[bufIdx] <= '9' {
		res = res*10 + int(buf[bufIdx]-'0')
		bufIdx++
	}
	return res
}

func nextString() string {
	for bufIdx < len(buf) && buf[bufIdx] <= ' ' {
		bufIdx++
	}
	if bufIdx >= len(buf) {
		return ""
	}
	start := bufIdx
	for bufIdx < len(buf) && buf[bufIdx] > ' ' {
		bufIdx++
	}
	return string(buf[start:bufIdx])
}

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

func main() {
	buf, _ = io.ReadAll(os.Stdin)

	s := nextString()
	if s == "" {
		return
	}
	m := nextInt()

	L := len(s)
	P := L - 1

	occurrences := make([][]int, 676)
	uniqueIDs := make([]int, 0, 676)
	present := make([]bool, 676)
	bigramAt := make([]int, P+1)

	for i := 1; i <= P; i++ {
		id := int(s[i-1]-'a')*26 + int(s[i]-'a')
		bigramAt[i] = id
		if !present[id] {
			present[id] = true
			uniqueIDs = append(uniqueIDs, id)
		}
		occurrences[id] = append(occurrences[id], i)
	}

	D := make([][]uint16, 676)
	queue := make([]int, 0, P)
	bigramVisited := make([]bool, 676)

	for _, id := range uniqueIDs {
		D[id] = make([]uint16, P+1)
		for i := 1; i <= P; i++ {
			D[id][i] = 65535
		}

		queue = queue[:0]
		for _, pos := range occurrences[id] {
			D[id][pos] = 0
			queue = append(queue, pos)
		}

		for i := 0; i < 676; i++ {
			bigramVisited[i] = false
		}
		bigramVisited[id] = true

		for len(queue) > 0 {
			curr := queue[0]
			queue = queue[1:]
			d := D[id][curr]

			if curr > 1 && D[id][curr-1] == 65535 {
				D[id][curr-1] = d + 1
				queue = append(queue, curr-1)
			}
			if curr < P && D[id][curr+1] == 65535 {
				D[id][curr+1] = d + 1
				queue = append(queue, curr+1)
			}
			b := bigramAt[curr]
			if !bigramVisited[b] {
				bigramVisited[b] = true
				for _, pos := range occurrences[b] {
					if D[id][pos] == 65535 {
						D[id][pos] = d + 1
						queue = append(queue, pos)
					}
				}
			}
		}
	}

	out := make([]byte, 0, m*10)
	for i := 0; i < m; i++ {
		f := nextInt()
		t := nextInt()

		ans := abs(f - t)
		for _, id := range uniqueIDs {
			cost := int(D[id][f]) + int(D[id][t]) + 1
			if cost < ans {
				ans = cost
			}
		}

		if ans == 0 {
			out = append(out, '0', '\n')
		} else {
			var temp [10]byte
			idx := 10
			for ans > 0 {
				idx--
				temp[idx] = byte('0' + ans%10)
				ans /= 10
			}
			out = append(out, temp[idx:]...)
			out = append(out, '\n')
		}
	}
	os.Stdout.Write(out)
}