//! Generic utility for reading data from standard input, based on [voxl's
//! stdin wrapper](http://codeforces.com/contest/702/submission/19589375).
use std::io;
use std::str;

/// Reads white-space separated tokens one at a time.
pub struct Scanner<R> {
    reader: R,
    buffer: Vec<String>,
}

impl<R: io::BufRead> Scanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buffer: Vec::new(),
        }
    }

    /// Use "turbofish" syntax token::<T>() to select data type of next token.
    ///
    /// # Panics
    ///
    /// Panics if there's an I/O error or if the token cannot be parsed as T.
    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts
/// **REQUIRES** Rust 1.34 or higher
pub struct UnsafeScanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: str::SplitAsciiWhitespace<'static>,
}

impl<R: io::BufRead> UnsafeScanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buf_str: Vec::new(),
            buf_iter: "".split_ascii_whitespace(),
        }
    }

    /// This function should be marked unsafe, but noone has time for that in a
    /// programming contest. Use at your own risk!
    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse");
            }
            self.buf_str.clear();
            self.reader
                .read_until(b'\n', &mut self.buf_str)
                .expect("Failed read");
            self.buf_iter = unsafe {
                let slice = str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_ascii_whitespace())
            }
        }
    }
}

pub fn scanner_from_file(filename: &str) -> Scanner<io::BufReader<std::fs::File>> {
    let file = std::fs::File::open(filename).expect("Input file not found");
    Scanner::new(io::BufReader::new(file))
}

pub fn writer_to_file(filename: &str) -> io::BufWriter<std::fs::File> {
    let file = std::fs::File::create(filename).expect("Output file not found");
    io::BufWriter::new(file)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_in_memory_io() {
        let input = "50 8".as_bytes();
        let mut scan = Scanner::new(input);
        let mut out = String::new();
        use std::fmt::Write; // needed for writeln!()

        let x = scan.token::<i32>();
        let y = scan.token::<i32>();
        writeln!(out, "Test {}", x - y).ok();

        assert_eq!(out, "Test 42\n");
    }

    #[test]
    fn test_in_memory_unsafe() {
        let input = "50 8".as_bytes();
        let mut scan = UnsafeScanner::new(input);
        let mut out = String::new();
        use std::fmt::Write; // needed for writeln!()

        let x = scan.token::<i32>();
        let y = scan.token::<i32>();
        writeln!(out, "Test {}", x - y).ok();

        assert_eq!(out, "Test 42\n");
    }

    #[test]
    fn test_compile_stdio() {
        let (stdin, stdout) = (io::stdin(), io::stdout());
        let mut scan = Scanner::new(stdin.lock());
        let mut out = io::BufWriter::new(stdout.lock());
        use io::Write; // needed for writeln!()

        if false {
            let x = scan.token::<i32>();
            let y = scan.token::<i32>();
            writeln!(out, "Test {}", x - y).ok();
        }
    }

    #[test]
    #[should_panic(expected = "Input file not found")]
    fn test_panic_file() {
        let mut scan = scanner_from_file("input_file.txt");
        let mut out = writer_to_file("output_file.txt");
        use io::Write; // needed for writeln!()

        let x = scan.token::<i32>();
        let y = scan.token::<i32>();
        writeln!(out, "Test {}", x - y).ok();
    }
}

use std::collections::HashSet;

fn solve(n: usize, k: usize, s: String, keys: HashSet<char>) -> usize {
    let mut result = 0;

    let mut cnt = 0;
    for ch in s.chars() {
        if keys.contains(&ch) {
            cnt += 1;
        } else {
            result += cnt * (cnt + 1) / 2;
            cnt = 0;
        }
    }
    result += cnt * (cnt + 1) / 2;

    result
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    // let mut scan = scanner_from_file("input/1272c_yet_another_broken_keyboard.in");
    let mut out = io::BufWriter::new(stdout.lock());
    use io::Write;

    let n: usize = scan.token();
    let k: usize = scan.token();
    let s: String = scan.token();
    let mut keys: HashSet<char> = HashSet::new();
    for _ in 0..k {
        keys.insert(scan.token());
    }

    let result = solve(n, k, s, keys);
    writeln!(out, "{}", result);
}


struct Scan {
    buffer: std::collections::VecDeque<String>,
}

impl Scan {
    fn new() -> Scan {
        Scan {
            buffer: std::collections::VecDeque::new(),
        }
    }

    fn next_line(&self) -> String {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("Fail to read");
        line
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let line = self.next_line();
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }

    fn next_n<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.next::<T>()).collect()
    }
}

fn _main() {
    let mut scan = Scan::new();
    let n: usize = scan.next();
    let k: usize = scan.next();
    let input: String = scan.next_line().chars().take(n).collect();
    let x: std::collections::HashSet<char> = scan.next_n::<char>(k).into_iter().collect();
    let mut result = 0u64;
    let mut sublen = 0u64;
    for c in input.chars() {
        if x.contains(&c) {
            sublen += 1;
        } else {
            result += sublen * (sublen + 1) / 2;
            sublen = 0;
        }
    }
    result += sublen * (sublen + 1) / 2;
    println!("{}", result);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1 << 23)
        .spawn(_main)
        .unwrap()
        .join()
        .unwrap();
}


#[allow(unused_imports)]
use std::collections::*;
use std::io::prelude::*;

fn main() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut entries = buf.split_whitespace();
    let n: usize = entries.next().unwrap().parse().unwrap();
    let k: usize = entries.next().unwrap().parse().unwrap();
    let s: String = entries.next().unwrap().parse().unwrap();
    let mut letters = HashSet::new();
    for i in 0..k {
        let c: char = entries.next().unwrap().parse().unwrap();
        letters.insert(c);
    }
    println!("{}", solve(s.chars().collect(), letters))
}

fn solve(s: Vec<char>, l: HashSet<char>) -> u64 {
    let mut res = 0;
    let mut i = 0;
    while !l.contains(&s[i]) {
        i += 1;
        if i == s.len() {
            return 0;
        }
    }
    loop {
        let mut cur_tot = 0;
        while l.contains(&s[i]) {
            i += 1;
            cur_tot += 1;
            if i == s.len() {
                res += s1(cur_tot);
                return res;
            }
        }
        res += s1(cur_tot);
        while !l.contains(&s[i]) {
            i += 1;
            if i == s.len() {
                return res;
            }
        }
    }
    0
}

fn s1(n: u64) -> u64 {
    n * (n + 1) / 2
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test1() {}
}


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
}

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

// PrintDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

/********** 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, k int
var S []rune
var Avail []rune

func main() {
	n, k = ReadInt2()
	S = ReadRuneSlice()
	for i := 0; i < k; i++ {
		tmp := ReadRuneSlice()
		Avail = append(Avail, tmp[0])
	}

	memo := make([]int, n)
	for i := 0; i < n; i++ {
		if !isAvail(S[i]) {
			memo[i] = -1
		}
	}

	cur := int64(0)
	sums := make([]int64, n)
	for i := 0; i < n; i++ {
		if memo[i] == -1 {
			// アウトなのでリセット
			cur = 0
		} else {
			// 継続
			cur++
		}
		sums[i] = cur
	}

	ans := int64(0)
	for i := 0; i < n; i++ {
		ans += sums[i]
	}
	fmt.Println(ans)
}

func isAvail(r rune) bool {
	for i := 0; i < len(Avail); i++ {
		if Avail[i] == r {
			return true
		}
	}
	return false
}

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

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


package main

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

var inf int = 0x3f3f3f3f
var reader *bufio.Reader

func init() {
	stdin := os.Stdin
	// stdin, _ = os.Open("1.in")
	reader = bufio.NewReaderSize(stdin, 1<<20)
}

var n, m int
var s string

func main() {
	fmt.Fscan(reader, &n, &m, &s)
	mp := make(map[byte]int)
	for i := 0; i < m; i++ {
		var c string
		fmt.Fscan(reader, &c)
		mp[c[0]] = 1
	}
	var sum,ans int64
	for i := 0; i < n; i++ {
		if mp[s[i]] == 0 {
			ans += sum * (sum + 1) / 2
			sum = 0
		} else {
			sum++
		}
	}
	ans += sum * (sum + 1) / 2
	fmt.Println(ans)
}


package main

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

var inf int = 0x3f3f3f3f
var reader *bufio.Reader

func init() {
	stdin := os.Stdin
	// stdin, _ = os.Open("1.in")
	reader = bufio.NewReaderSize(stdin, 1<<20)
}

var n, m int
var s string

func main() {
	fmt.Fscan(reader, &n, &m, &s)
	mp := make(map[byte]int)
	for i := 0; i < m; i++ {
		var c string
		fmt.Fscan(reader, &c)
		mp[c[0]] = 1
	}
	sum := 0
	ans := 0
	for i := 0; i < n; i++ {
		if mp[s[i]] == 0 {
			ans += sum * (sum + 1) / 2
			sum = 0
		} else {
			sum++
		}
	}
	ans += sum * (sum + 1) / 2
	fmt.Println(ans)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string

	reader := bufio.NewReaderSize(os.Stdin, 300000)
	str, _ = reader.ReadString('\n')
	keys, _ = reader.ReadString('\n')

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	substringLen := 0
	result := 0
	for i := 0; i < len(str); i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string

	reader := bufio.NewReader(os.Stdin)

	str, _ = reader.ReadString('\n')
	keys, _ = reader.ReadString('\n')

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	var substringLen, result int64
	substringLen = 0
	result = 0
	for i := 0; i < n; i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string

	scanner := bufio.NewScanner(os.Stdin)

	if scanner.Scan() {
		str = scanner.Text()
	}
	if scanner.Scan() {
		keys = scanner.Text()
	}

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	var substringLen, result int64
	substringLen = 0
	result = 0
	for i := 0; i < n; i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string

	reader := bufio.NewReader(os.Stdin)

	//input, _ := ioutil.ReadFile("input.txt")
	//str = string(input)
	//keys = "a b c d e f g h i j k l m n o p q r s t u v w x y z"

	str, _ = reader.ReadString('\n')
	keys, _ = reader.ReadString('\n')

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	var substringLen, result int64
	substringLen = 0
	result = 0
	for i := 0; i < n; i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string

	reader := bufio.NewReader(os.Stdin)

	//input, _ := ioutil.ReadFile("input.txt")
	//str = string(input)
	//keys = "a b c d e f g h i j k l m n o p q r s t u v w x y z"

	str, _ = reader.ReadString('\n')
	keys, _ = reader.ReadString('\n')

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	substringLen := 0
	result := 0
	for i := 0; i < n; i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string
	fmt.Scanln(&str)

	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 1024*1024)
	scanner.Buffer(buf, 2048*1024)

	if scanner.Scan() {
		keys = scanner.Text()
	}

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	substringLen := 0
	result := 0
	for i := 0; i < len(str); i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string

	reader := bufio.NewReader(os.Stdin)

	//input, _ := ioutil.ReadFile("input.txt")
	//str = string(input)
	//keys = "a b c d e f g h i j k l m n o p q r s t u v w x y z"

	str, _ = reader.ReadString('\n')
	keys, _ = reader.ReadString('\n')

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	substringLen := 0
	result := int64(0)
	for i := 0; i < n; i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += int64((substringLen * (substringLen + 1)) / 2)
			substringLen = 0
		}
	}

	result += int64((substringLen * (substringLen + 1)) / 2)
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string

	reader := bufio.NewReader(os.Stdin)

	buf := make([]byte, n+1)
	//str, _ = reader.ReadString('\n')
	reader.Read(buf)
	str = string(buf)
	keys, _ = reader.ReadString('\n')

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	substringLen := 0
	result := 0
	for i := 0; i < len(str); i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string

	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 1024*1024)
	scanner.Buffer(buf, 2048*1024)

	if scanner.Scan() {
		str = scanner.Text()
	}

	if scanner.Scan() {
		keys = scanner.Text()
	}

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	substringLen := 0
	result := 0
	for i := 0; i < len(str); i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string
	fmt.Scanln(&str)

	scanner := bufio.NewScanner(os.Stdin)
	if scanner.Scan() {
		keys = scanner.Text()
	}

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	substringLen := 0
	result := 0
	for i := 0; i < len(str); i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string

	reader := bufio.NewReader(os.Stdin)
	str, _ = reader.ReadString('\n')
	keys, _ = reader.ReadString('\n')

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	substringLen := 0
	result := 0
	for i := 0; i < len(str); i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var str, keys string
	fmt.Scanln(&str)

	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 2048*1024)

	if scanner.Scan() {
		keys = scanner.Text()
	}

	keyMap := make(map[int]bool)
	for i := 0; i < len(keys); i++ {
		key := int(keys[i])
		if key >= 97 && key <= 122 {
			keyMap[key] = true
		}
	}

	substringLen := 0
	result := 0
	for i := 0; i < len(str); i++ {
		if keyMap[int(str[i])] {
			substringLen++
		} else {
			result += (substringLen * (substringLen + 1)) / 2
			substringLen = 0
		}
	}

	result += (substringLen * (substringLen + 1)) / 2
	fmt.Println(result)
}


package main

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

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

	var n, k int
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	var s, temp string
	fmt.Fscanf(reader, "%s\n", &s)
	letters := make([]string, 0)
	for i := 1; i <= k; i++ {
		fmt.Fscanf(reader, "%s", &temp)
		letters = append(letters, temp)
		s = strings.Replace(s, temp, "1", -1)
	}
	fmt.Fscanf(reader, "\n")
	var count, ans int64
	for _, ch := range []rune(s) {
		if ch != 49 {
			//fmt.Fprintf(writer, "%d %c %d\n", idx, ch, count)
			if count > 0 {
				ans = ans + ((count * (count + 1)) / 2)
			}
			count = 0
		} else {
			count = count + 1
		}
	}
	ans = ans + ((count * (count + 1)) / 2)
	fmt.Fprintf(writer, "%d\n", ans)
}


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

package main

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

func Solve(n int, k int, s string, c []string) int64 {
	substringCount := int64(0)
	run := int64(0)
	alphabetMap := make(map[string]bool)
	for _, elem := range c {
		alphabetMap[string(elem)] = true
	}
	for i, elem := range s {
		if alphabetMap[string(elem)] == true {
			run += 1
		}
		if alphabetMap[string(elem)] == false || i == n-1 {
			substringCount += run * (run + 1) / 2
			run = 0
		}
	}
	return substringCount
}

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

	var n, k int
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	var s string
	fmt.Fscanf(reader, "%s\n", &s)
	c := make([]string, k)
	for i := 0; i < k; i++ {
		fmt.Fscanf(reader, "%s", &c[i])
	}

	fmt.Fprintf(writer, "%d\n", Solve(n, k, s, c))
}


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

package main

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

func Solve(n int, k int, s string, c []string) int {
	substringCount := 0
	run := 0
	alphabetMap := make(map[string]bool)
	for _, elem := range c {
		alphabetMap[string(elem)] = true
	}
	for i, elem := range s {
		if alphabetMap[string(elem)] == true {
			run += 1
		}
		if alphabetMap[string(elem)] == false || i == n-1 {
			substringCount += run * (run + 1) / 2
			run = 0
		}
	}
	return substringCount
}

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

	var n, k int
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	var s string
	fmt.Fscanf(reader, "%s\n", &s)
	c := make([]string, k)
	for i := 0; i < k; i++ {
		fmt.Fscanf(reader, "%s", &c[i])
	}

	fmt.Fprintf(writer, "%d\n", Solve(n, k, s, c))
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var s, availChars string
	fmt.Scanln(&s)

	scanner := bufio.NewScanner(os.Stdin)
	if scanner.Scan() {
		availChars = scanner.Text()
	}

	availArray := strings.Split(availChars, " ")
	letterMap := make(map[rune]bool)
	for _, char := range availArray {
		runes := []rune(char)
		letterMap[runes[0]] = true
	}

	var substrings uint64
	substrings = 0
	num := 0
	letters := []rune(s)
	for _, char := range letters {
		if letterMap[char] {
			num++
		} else {
			substrings += (uint64)(num * (num + 1) / 2)
			num = 0
		}
	}

	substrings += (uint64)(num * (num + 1) / 2)

	fmt.Println(substrings)
}


package main

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

func main() {
	var n, k uint64
	fmt.Scanf("%d %d\n", &n, &k)

	var s, availChars string
	fmt.Scanln(&s)

	scanner := bufio.NewScanner(os.Stdin)
	if scanner.Scan() {
		availChars = scanner.Text()
	}

	availArray := strings.Split(availChars, " ")
	letterMap := make(map[rune]bool)
	for _, char := range availArray {
		runes := []rune(char)
		letterMap[runes[0]] = true
	}

	var substrings, num uint64
	substrings = 0
	num = 0
	letters := []rune(s)
	for _, char := range letters {
		if letterMap[char] {
			num++
		} else {
			substrings += (uint64)(num * (num + 1) / 2)
			num = 0
		}
	}

	substrings += (uint64)(num * (num + 1) / 2)

	fmt.Println(substrings)
}


package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)

	var s, availChars string
	fmt.Scanln(&s)

	scanner := bufio.NewScanner(os.Stdin)
	if scanner.Scan() {
		availChars = scanner.Text()
	}

	availArray := strings.Split(availChars, " ")
	letterMap := make(map[rune]bool)
	for _, char := range availArray {
		runes := []rune(char)
		letterMap[runes[0]] = true
	}

	substrings := 0
	num := 0
	letters := []rune(s)
	for _, char := range letters {
		if letterMap[char] {
			num++
		} else {
			substrings += num * (num + 1) / 2
			num = 0
		}
	}

	substrings += num * (num + 1) / 2

	fmt.Println(substrings)
}


<?php
list($n, $k) = explode(' ', trim(fgets(STDIN)));
list($s) = explode(' ', trim(fgets(STDIN)));
$aArray = explode(' ', trim(fgets(STDIN)));
$iCount = 0;
$j = 0;
for($i = 0; $i < strlen($s); $i++){
    if(in_array($s[$i],$aArray)){
        $j = $j + 1;
    } else {
        $iCount += ($j*($j + 1))/2;
        $j = 0;
    }
    if ($i == (strlen($s) - 1) && $j > 0) {
        $iCount += ($j*($j + 1))/2;
        $j = 0;
    }
}
echo $iCount . "\n";


n,k = map(int,raw_input().split(" "))
s1 = raw_input()
chars = raw_input().split(" ")
chars = set(chars)
cnt = 0
ans = []
for i in range(n):
	if s1[i] in chars:
		cnt += 1
	else:
		ans.append(cnt)
		cnt = 0

ans.append(cnt)
ret = 0
for i in ans:
	ret += i*(i+1)/2
print ret


n,k = map(int, raw_input().split())
s = raw_input()
l = set(raw_input().split())

ans = 0
index = 0
for i in xrange(n):
    if s[i] in l:
        index+=1
    else:
        ans+=((index*(index+1))/2)
        index = 0

ans+=((index*(index+1))/2)
print ans


p = raw_input().split()
s = raw_input()
n = len(s)
broke= raw_input().split()
p = [0]*26
for i in broke:
    p[ord(i)-ord('a')] = 1
s = list(s)
cnt = [0]*n
for i in range(0,len(s)):
    if(p[ord(s[i])-ord('a')] == 1):
        s[i] = ''
        cnt[i] = 1
    else:
        cnt[i] = 0
till = 0
final = 0
for i in range(0,n):
    if(cnt[i]==1):
        till+=1
    else:
        final += ((till)*(till+1))//2
        till =0
final += ((till+1)*(till))//2

print(final)


#!/usr/bin/env pypy
from __future__ import division, print_function
from collections import defaultdict, Counter, deque
from future_builtins import ascii, filter, hex, map, oct, zip
from itertools import imap as map, izip as zip
from __builtin__ import xrange as range
from math import ceil
from _continuation import continulet
from cStringIO import StringIO
from io import IOBase
import __pypy__
from bisect import bisect, insort, bisect_left, bisect_right
import sys
import os
import re
inf = float('inf')
mod = int(1e9) + 7
mod_ = 998244353

'''
Check for special cases (n=1)
One wrong submission = 10 mins penalty!
do smth instead of nothing and stay organized
'''

def main():
	n, m = map(int, input().split())
	s = input()
	availables = set(input().split())
	curr = 0
	ans = 0
	for c in s:
		if c in availables:
			curr += 1
		else:
			ans += curr*(curr+1)//2
			curr = 0
	ans += curr*(curr+1)//2
	print(ans)

BUFSIZE = 8192
class FastI(IOBase):
	def __init__(self, file):
		self._fd = file.fileno()
		self._buffer = StringIO()
		self.newlines = 0

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count("\n") + (not b)
			ptr = self._buffer.tell()
			self._buffer.seek(0, 2), self._buffer.write(
				b), self._buffer.seek(ptr)
		self.newlines -= 1
		return self._buffer.readline()
class FastO(IOBase):
	def __init__(self, file):
		self._fd = file.fileno()
		self._buffer = __pypy__.builders.StringBuilder()
		self.write = lambda s: self._buffer.append(s)

	def flush(self):
		os.write(self._fd, self._buffer.build())
		self._buffer = __pypy__.builders.StringBuilder()
def print(*args, **kwargs):
	sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop("end", "\n"))
	if kwargs.pop("flush", False):
		file.flush()
def gcd(x, y):
	while y:
		x, y = y, x % y
	return x
sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
	def bootstrap(cont):
		call, arg = cont.switch()
		while True:
			call, arg = cont.switch(to=continulet(
				lambda _, f, args: f(*args), call, arg))
	cont = continulet(bootstrap)
	cont.switch()
	main()


n, k = map(int, raw_input().split())
s = raw_input()
cs = set(raw_input().split())
cnt = ans = 0
for i in range(n):
    if s[i] in cs:
        cnt += 1
    else:
        ans += (cnt * (cnt + 1)) / 2
        cnt = 0
print ans + (cnt * (cnt + 1)) / 2


n,k = map(int, raw_input().split())
s = raw_input()
alp = raw_input()
alphabet = dict()
for i in alp:
  alphabet[i] = 0
count = 0
subs = []
for char in s:
  if char in alphabet:
    count+=1
  else:
    subs.append(count * (count + 1) / 2)
    count = 0
subs.append(count * (count + 1) / 2)
sm = 0
for i in subs:
  sm += i
print sm


from sys import stdin, stdout
from collections import Counter
raw_input = stdin.readline
n,k=map(int,raw_input().split())
s=raw_input().strip()
d=Counter(raw_input().split())
ans=0
dp=[0]*n
curr=0
for i in range(n-1,-1,-1):
    if d[s[i]]:
        curr+=1
    else:
        ans+=(curr*(curr+1))/2
        curr=0
if curr:
    ans+=(curr*(curr+1))/2
"""
for i in range(n):
    if d[s[i]]:
        ln=dp[i]-i
        ans+=(ln*(ln+1))/2
"""
print ans


from sys import stdin, stdout
from collections import Counter
raw_input = stdin.readline
n,k=map(int,raw_input().split())
s=raw_input().strip()
d=Counter(raw_input().split())
ans=(n*(n+1))/2
damage=0
for i in range(n):
    if not d[s[i]]:
        ans-=(i+1-damage)*(n-i)
        damage+=1
print ans


from sys import stdin, stdout
from collections import Counter
raw_input = stdin.readline
n,k=map(int,raw_input().split())
s=raw_input().strip()
d=Counter(raw_input().strip())
ans=(n*(n+1))/2
damage=0
for i in range(n):
    if not d[s[i]]:
        ans-=(i+1-damage)*(n-i)
        damage+=1
print ans


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def main():
    n, k = map(int, input().split())
    s = input()
    c = set(input().split(' '))

    a = 0
    l = 0
    for i in s:
        if i not in c:
            a += (l * (l - 1)) // 2 + l
            l = 0
            continue
        l += 1

    a += (l * (l - 1)) // 2 + l

    print(a)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


from __future__ import division, print_function

def main():
    def aton(c):
        return ord(c)-ord('a')

    n, k = input_as_list()
    s = input()
    exists = array_of(bool, 26)
    for c in input().split():
        exists[aton(c)] = True
    ans = 0
    cur = 0
    for c in s:
        if exists[aton(c)]:
            cur += 1
        else:
            cur = 0
        ans += cur
    print(ans)

INF = float('inf')
MOD = 10 ** 9 + 7
__interactive = False

import os, sys
sys.modules["hashlib"] = sys.sha512 = sys
from atexit import register
from io import BytesIO
import itertools
import __pypy__

if sys.version_info[0] < 3:
    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

if "LOCAL_" in os.environ:
    debug_print = print
else:
    if not __interactive:
        sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
        sys.stdout = BytesIO()
        register(lambda: os.write(1, sys.stdout.getvalue()))

        input = lambda: sys.stdin.readline().rstrip('\r\n')
    debug_print = lambda *x, **y: None

flush = sys.stdout.flush

def mulmod(x, y):
    return __pypy__.intop.int_mulmod(x, y, MOD)

def modinv(x):
    return pow(x, MOD-2, MOD)

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

def input_as_list():
    return [int(x) for x in input().split()]

def input_with_offset(o):
    return [int(x)+o for x in input().split()]

def input_as_matrix(n, m):
    return [input_as_list() for _ in range(n)]

def array_of(f, *dim):
    return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()

def range_with_count(start, step, count):
    return range(start, start + step * count, step)

def indices(l, start=0, end=0):
    return range(start, len(l)+end)

def ceil_power_of_2(n):
    """ [0, 1, 2, 4, 4, 8, 8, 8, 8, 16, 16, ...] """
    return 2 ** ((n - 1).bit_length())

def ceil_div(x, r):
    """ = ceil(x / r) """
    return (x + r - 1) // r

main()


n, k = map(int, raw_input().split())
string = raw_input()
availables = raw_input().split()

letters_availables = {}
result = 0
count = 0

for i in range(k):
    letters_availables[availables[i]] = True

for i in range(n + 1):
    if (i == n or not string[i] in letters_availables):
        result += (count + 1) * count / 2
        count = 0
    else:
        count += 1

print(result)


n, k = map(int, raw_input().split())
string = raw_input()
availables = raw_input().split()

letters_availables = {}
result = 0
count = 0

for i in range(k):
    letters_availables[availables[i]] = True

for i in range(n):
    if (not string[i] in letters_availables):
        result += (count + 1) * count / 2
        count = 0
    else:
        count += 1

if (count > 0):
    result += (count + 1) * count / 2

print(result)


from collections import Counter
n,k=map(int,raw_input().split())
s=raw_input()
arr=list(map(str,raw_input().split()))

def solve(arr,s,n,k):
    d=Counter(a)
    ans=0
    count=0
    for i in range(n):
        if d[s[i]]==1:
            count+=1
        else:
            ans+=count*(count+1)//2
            count=0
        if i==n-1:
            ans+=count*(count+1)//2
    return ans

print(solve(arr,s,n,k))


from collections import Counter
n,k=map(int,raw_input().split())
s=raw_input()
arr=list(map(str,raw_input().split()))

def solve(arr,s,n,k):
    d=Counter(arr)
    ans=0
    count=0
    for i in range(n):
        if d[s[i]]==1:
            count+=1
        else:
            ans+=count*(count+1)//2
            count=0
        if i==n-1:
            ans+=count*(count+1)//2
    return ans

print(solve(arr,s,n,k))


n,k=map(int,raw_input().split())
s=raw_input()
arr=list(map(str,raw_input().split()))

def solve(arr,s,n,k):
    ans=0
    x=""
    for i in range(n):
        if s[i] not in arr:
            l=len(x)
            ans += l*(l+1)/2
            x=""
        else:
            x+=s[i]
    if s[-1] in arr and x[-1]==s[-1]:
        l=len(x)
        ans += l*(l+1)/2
    return ans

print(solve(arr,s,n,k))


n,k=map(int,raw_input().split())
s=raw_input()
arr=list(map(str,raw_input().split()))

def solve(arr,s,n,k):
    if k==26:
        return n*(n+1)/2
    ans=0
    x=""
    for i in range(n):
        if s[i] not in arr:
            l=len(x)
            ans += l*(l+1)/2
            x=""
        else:
            x+=s[i]
    if s[-1] in arr and x[-1]==s[-1]:
        l=len(x)
        ans += l*(l+1)/2
    return ans

print(solve(arr,s,n,k))


n,k=map(int,raw_input().split())
s=raw_input()
arr=list(map(str,raw_input().split()))

def solve(arr,s,n,k):
    ans=0
    x=""
    for i in range(n):
        if s[i] not in arr:
            ans += len(x)*(len(x)+1)/2
            x=""
        else:
            x+=s[i]
    if s[-1] in arr and x[-1]==s[-1]:
        ans += len(x)*(len(x)+1)/2
    return ans

print(solve(arr,s,n,k))


n,k=map(int,raw_input().split())
s=raw_input()
arr=list(map(str,raw_input().split()))

def solve(arr,s,n,k):
    x=""
    for i in range(n):
        if s[i] in arr:
            x+="1"
        else:
            x+="0"

    # if "1" not in x:
    #     return 0
    # elif "0" not in x:
    #     return n*(n+1)/2

    i,j=0,0
    ans=0
    count=0
    while i<n and j<n:
        if x[j]=="1":
            count+=1
            j+=1
        else:
            ans+=count*(count+1)/2
            count=0
            i=j
            j+=1

    if x[-1]=="1":
        ans+=count*(count+1)/2
    return ans

print(solve(arr,s,n,k))


import sys
range = xrange
input = raw_input

orda = ord('a')

n,k = [int(x) for x in input().split()]
S = [ord(c) - orda for c in input()]
K = [ord(c) - orda for c in input().split()]

write = [0]*30
for c in K:
    write[c] = 1

subs = 0
first = 0
for i in range(n):
    if write[S[i]]:
        subs += i - first + 1
    else:
        first = i + 1

print subs


n,k = map(int,raw_input().split())
s = raw_input()
q = len(set(s))
l = raw_input().split()
d = {}
for i in l:
    if i in d:
        d[i] += 1
    else:
        d[i] = 1
resl = []
w = 0
for i in range(n):
    if s[i] in d:
        w+=1
    else:
        resl.append(w)
        w = 0
resl.append(w)
res = 0
for i in resl:
    res+=((i+1)*i)/2
print res


import sys
input = sys.stdin.readline

n, k = (int(x) for x in input().split())
s = input().strip()
c = set(input().split())
ans = 0
cnt = 0
for i in xrange(len(s)):
    if s[i] in c:
        cnt += 1
    else:
        cnt += 1
        ans += cnt * (cnt - 1) // 2
        cnt = 0
cnt += 1
ans += cnt * (cnt - 1) //2
print(ans)


N, K = map(int,raw_input().split())
S = raw_input()
C = set(raw_input().split())

def num(n) : return n*(n+1)/2

x, ans = 0, 0
for s in S :
  if s in C : x += 1
  else :
    ans += num(x)
    x = 0

ans += num(x)

print ans


'''input
10 3
sadfaasdda
f a d
'''

import sys
debug = 1
readln = sys.stdin.readline

def write(s):
    sys.stdout.write(str(s))

def writeln(s):
    sys.stdout.write(str(s))
    sys.stdout.write('\n')

def readint():
    return int(readln().strip())

def readints():
    return map(int, readln().split())

def readstr():
    return readln().strip()

def readstrs():
    return readln().split()

def dprint(*args):
    if debug: print(' '.join(map(str, args)))

def solve(s, ks):
    ans = 0
    clen = 0
    for c in s:
        if c in ks:
            clen += 1
            ans += clen
        else:
            clen = 0
    return ans

n, k = readints()
s = readstr()
ks = readstrs()
writeln(solve(s, ks))
pass


from sys import stdin,stdout
from collections import Counter
for _ in range(1):#int(stdin.readline())):
    # n=int(stdin.readline())
    n,k=list(map(int,stdin.readline().split()))
    s=input();ans=c=0
    keys=set(input().split())
    # print(keys)
    for i in range(n):
        if s[i] not in keys:
            ans+=(c*(c+1))//2
            c=0
        else:c+=1
    ans+=(c*(c+1))//2
    print(ans)


n,k = map(int,input().split())
s = input()
c = list(input().split())
set(c)
answer = 0
i = 0
while True:
    if i >= n:
        break
    j = i

    while (j < n and c.count(s[j])):
        j += 1

    answer += ((j - i) * (j - i + 1)) // 2
    i = j
    i+=1
print(answer)


n,k = map(int,input().split())
s = input()
c = list(input().split())
answer = 0
i = 0
while True:
    if i >= n-1:
        break
    j = i
    while (j < n and c.count(s[j])):
        j += 1
    answer += ((j - i) * (j - i + 1)) // 2
    i = j
    i+=1
print(answer)


n,k = map(int,input().split())
s = input()
c = list(input().split())
set(c)
answer = 0
i = 0
while True:
    if i >= n-1:
        break
    j = i
    while (j < n and c.count(s[j])):
        j += 1
    answer += ((j - i) * (j - i + 1)) // 2
    i = j
    i+=1
print(answer)


from collections import defaultdict
x,y=map(int,input().split())
n=input()
a=list(input().split())
d=defaultdict(int)
for i in a:
    d[i]=1
c=1
s=0
for i in range(x):
    if d[n[i]]==0:
        s+=c*(x-i)
    else:
        c+=1
print((x*(x+1))//2-s)


from collections import defaultdict
x,y=map(int,input().split())
n=list(input())
a=list(input().split())
d=defaultdict(int)
for i in a:
    d[i]=1
s=0
k=x
for i in range(x):
    if d[n[-(i+1)]]==1:
        s+=x-(k)
    else:
        k=x-(i+1)
        s+=(x-k)

print((x*(x+1))//2-s)


n, k = [int(p) for p in input().split()]
s =  input()
keys = input().split()
prefix = []
l = list(s)
for i in range(len(l)):
	if l[i] not in keys:
		l[i] =  ' '
s = ''.join(l).split()
counter = 0
for i in range(len(s)):
	counter += len(s[i])*(len(s[i]) + 1)//2
print(counter)


a, b = list(map(int, input().split()))
c = input()
d = set(input().split())
ans = 0
l = 0
for i in range(a):
    if c[i] in d:
        l += 1
    else:
        ans += (l * (l + 1)) // 2
        l = 0

ans += (l * (l + 1)) // 2

print(ans)


a, b = list(map(int, input().split()))
c = [[input()]]
d = set(input().split())

k = set()
for i in range(97, 123):
    k.add(chr(i))
#print(k)
k -= d

for i in k:
    temp = []
    for j in c:
        for m in j:
            temp.append(m.split(i))
    c = temp
ans = 0
#print(c)
for i in c:
    i = i[0]
    ans += (len(i) * (len(i) + 1)) // 2
print(ans)


a, b = list(map(int, input().split()))
c = [[input()]]
d = set(input().split())

k = set()
for i in range(97, 123):
    k.add(chr(i))

k -= d

for i in k:
    temp = []
    for j in c:
        # print(j, i)
        for m in j:
            temp.append(m.split(i))
    c = temp
ans = 0
for i in c:
    i = i[0]
    ans += (len(i) * (len(i) + 1)) // 2
print(ans)
# ans = map(lambda x: (len(x) * (len(x))+1) // 2, c)


def find_first_of(string, sub, a, b):
    for i in range(a, b):
        if string[i] in sub:
            return i
    return -1

def combinations(x):
    return x * (x + 1) // 2

n, k = map(int, input().split())
s = input()
abc = input().split()

res = 0
left = find_first_of(s, abc, 0, n)
while left != -1:
    cnt = 1
    while left + cnt < n and s[left + cnt] in abc:
        cnt += 1
    else:
        res += combinations(cnt)
    left = find_first_of(s, abc, left + cnt, n)
print(res)


def read_tokens():
    return input().strip().split(' ')

def read_ints():
    return [int(s) for s in read_tokens()]

n, k = read_ints()
s = input()
chars = read_tokens()

def contains_all(sub_str: str, unique_chars: set) -> bool:
    unique = set(sub_str)
    return all(el in unique_chars for el in unique)
    # unique = set(sub_str)
    # for el in unique:
    #     if not (el in unique_chars):
    #         return False
    # return True

def solve(s: str, chars: list) -> int:
    cnt = 0
    n = len(s)
    unique_chars = set(chars)
    for i in range(n):
        for j in range(i, n):
            sub_str = s[i:j+1]
            if contains_all(sub_str, unique_chars):
                cnt += 1
    return cnt

print(solve(s, chars))


def read_tokens():
    return input().strip().split(' ')

def read_ints():
    return [int(s) for s in read_tokens()]

n, k = read_ints()
s = input()
chars = read_tokens()

def solve(s: str, chars: list) -> int:
    cnt = 0
    n = len(s)
    unique_chars = set(chars)
    i = 0
    while i < n:
        if s[i] not in unique_chars:
            i = i + 1
            continue
        for j in range(i, n):
            if s[j] not in unique_chars:
                break
            cnt += 1
        i = i + 1
    return cnt

print(solve(s, chars))


def read_tokens():
    return input().strip().split(' ')

def read_ints():
    return [int(s) for s in read_tokens()]

n, k = read_ints()
s = input()
chars = read_tokens()

def contains_all(sub_str: str, unique_chars: set) -> bool:
    unique = set(sub_str)
    return all(el in unique_chars for el in unique)
    # unique = set(sub_str)
    # for el in unique:
    #     if not (el in unique_chars):
    #         return False
    # return True

def solve(s: str, chars: list) -> int:
    cnt = 0
    n = len(s)
    unique_chars = set(chars)
    for i in range(n):
        for j in range(i, n):
            sub_str = s[i:j+1]
            if contains_all(sub_str, unique_chars):
                cnt += 1
            else:
                break
    return cnt

print(solve(s, chars))


def read_tokens():
    return input().strip().split(' ')

def read_ints():
    return [int(s) for s in read_tokens()]

n, k = read_ints()
s = input()
chars = read_tokens()

def solve(s: str, chars: list) -> int:
    cnt = 0
    n = len(s)
    unique_chars = set(chars)
    i = 0
    while i < n:
        if s[i] not in unique_chars:
            i = i + 1
            continue

        for j in range(i, n):
            if s[j] not in unique_chars:
                diff = j-i
                cnt += (diff-1)*diff//2
                i = j
                break
            cnt += 1
        i = i + 1
    return cnt

print(solve(s, chars))


def read_tokens():
    return input().strip().split(' ')

def read_ints():
    return [int(s) for s in read_tokens()]

n, k = read_ints()
s = input()
chars = read_tokens()

def contains_all(sub_str: str, unique_chars: set) -> bool:
    unique = set(sub_str)
    return all(el in unique_chars for el in unique)
    # unique = set(sub_str)
    # for el in unique:
    #     if not (el in unique_chars):
    #         return False
    # return True

def solve(s: str, chars: list) -> int:
    cnt = 0
    n = len(s)
    unique_chars = set(chars)
    for i in range(n):
        curr_ch = s[i]
        if curr_ch not in unique_chars:
            continue

        for j in range(i, n):
            # next_str = s[j+1]
            # if contains_all(sub_str, unique_chars):
            #     cnt += 1
            # else:
            #     break
            next_ch = s[j]
            if next_ch not in unique_chars:
                break

            cnt += 1
    return cnt

print(solve(s, chars))


def read_tokens():
    return input().strip().split(' ')

def read_ints():
    return [int(s) for s in read_tokens()]

n, k = read_ints()
s = input()
chars = read_tokens()

def contains_all(sub_str: str, unique_chars: set) -> bool:
    unique = set(sub_str)
    for el in unique:
        if not (el in unique_chars):
            return False
    return True

def solve(s: str, chars: list) -> int:
    cnt = 0
    n = len(s)
    unique_chars = set(chars)
    for i in range(n):
        for j in range(i, n):
            sub_str = s[i:j+1]
            if contains_all(sub_str, unique_chars):
                # print(i+1, j+1)
                cnt += 1
    return cnt

print(solve(s, chars))


def read_tokens():
    return input().strip().split(' ')

def read_ints():
    return [int(s) for s in read_tokens()]

n, k = read_ints()
s = input()
chars = read_tokens()

def contains_all(sub_str: str, unique_chars: set) -> bool:
    unique = set(sub_str)
    return all(el in unique_chars for el in unique)
    # unique = set(sub_str)
    # for el in unique:
    #     if not (el in unique_chars):
    #         return False
    # return True

def solve(s: str, chars: list) -> int:
    cnt = 0
    n = len(s)
    unique_chars = set(chars)
    for i in range(n):
        curr_ch = s[i]
        if curr_ch not in unique_chars:
            continue

        for j in range(i+1, n):
            next_ch = s[j]
            if next_ch not in unique_chars:
                break

            cnt += 1
    return cnt

print(solve(s, chars))


def read_tokens():
    return input().strip().split(' ')

def read_ints():
    return [int(s) for s in read_tokens()]

n, k = read_ints()
s = input()
chars = read_tokens()

def solve_slow(s: str, chars: list) -> int:
    cnt = 0
    n = len(s)
    unique_chars = set(chars)
    i = 0
    while i < n:
        if s[i] not in unique_chars:
            i = i + 1
            continue

        for j in range(i, n):
            if s[j] not in unique_chars:
                diff = j-i
                cnt += (diff-1)*diff//2
                i = j
                break
            cnt += 1
        i = i + 1
    return cnt

def solve(s, chars):
    cnt = 0
    n = len(s)
    unique = set(chars)
    i = 0
    while i < n:
        j = i
        while j < n and s[j] in unique:
            j += 1
        diff = j - i
        cnt += diff * (diff + 1) // 2
        if i != j:
            i = j
        else:
            i += 1
    return cnt

print(solve(s, chars))


def read_tokens():
    return input().strip().split(' ')

def read_ints():
    return [int(s) for s in read_tokens()]

n, k = read_ints()
s = input()
chars = read_tokens()

def solve(s: str, chars: list) -> int:
    cnt = 0
    n = len(s)
    unique_chars = set(chars)
    i = 0
    while i < n:
        if s[i] not in unique_chars:
            continue
        for j in range(i, n):
            if s[j] not in unique_chars:
                break
            cnt += 1
        i = i + 1
    return cnt

print(solve(s, chars))


n,k = map(int,input().split())
s = input()
l = list(input().split())
groups = []
current = 0
for c in s:
    if c not in l:
        groups.append(current)
        current = 0
    else:
        current+=1
if current:
    groups.append(current)
total = 0
total += sum(x*(x+1)//2 for x in groups)
print (total)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
from collections import deque
from heapq import heappush,heappop

ip = lambda : int(stdin.readline())
inp = lambda: map(int,stdin.readline().split())
ips = lambda: stdin.readline().rstrip()

t = 1
for _ in range(t):
    n,k = inp()
    s = ips()
    arr = list(input().split())
    ans = []
    ch = []
    for i in s:
        if i in arr:
            ch.append(i)
        else:
            ans.append(ch)
            ch = []
    if len(ch) != 0:
        ans.append(ch)
    final = 0
    for i in ans:
        final += (len(i)*(len(i)+1))//2
    print(final)


t=1
while t:
   # n=int(input())
    #s=input()
    n,k=map(int,input().split())
    s=input()
    c1=list(input().split())
    ans=0
    c=[0]*(27)
    for i in range(len(c1)):
        c[ord(c1[i])-97]=1
    for i in range(n):
        if c[ord(s[i])-97]==1:
            ans+=1
            for j in range(i+1,n):
                if c[ord(s[j])-97]==1:
                    ans+=1
                else:
                    break
    print(ans)
    t-=1


#include"bits/stdc++.h"
using namespace std;
typedef long long               ll ;
typedef long double             ld ;
typedef unsigned long long      ull ;
typedef pair<int,int>           pii ;
typedef vector<int>             vi ;
typedef vector<vector<int>>     vvi ;
#define gcd(a,b) __gcd(a,b)
#define mem(a) memset(a,0,sizeof(a))
int Int(){int n;scanf("%d",&n);return n;}
ll LInt(){ll n;scanf("%lld",&n);return n;}
void print(int n){printf("%d",n);}
void printl(ll n){printf("%lld",n);}
#define Int Int()
#define lint LInt()

#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {cout << endl ;}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << ' ' ;
    err(++it, args...);
}

long long binpow(long long a, long long b) {
    long long res = 1;
    while (b > 0) {
        if (b & 1)
            res = res * a;
        a = a * a;
        b >>= 1;
    }
    return res;
}

ll mx,n,mx1,pos,pos1;
bool ok,ok1;
int main(){

    n=lint;
    ll a[n+3],b[n+3];
    for(int i=0;i<n;i++){
            a[i]=lint;
            b[i]=lint;
            if(i&&a[i]<a[i-1])ok=1;
            if(i&&b[i]<b[i-1])ok1=1;
            if(mx<a[i]){
                mx=a[i];
            }
            if(mx1<b[i]){
                mx1=b[i];
            }
    }
    // error(ok,ok1)
    if(ok&&ok1){
          printl( min(mx,mx1));

    }
    else  if(ok==1&&ok1==0){
       printl(mx);
    }
    else{
        printl(mx1);
    }

}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{
    int n;
    cin>>n;
    vector<pair<ll,ll>>v;
    for(int i=0;i<n;i++){
        ll x,y;
        cin>>x>>y;
        v.push_back(make_pair(x,y));
    }
    sort(v.begin(),v.end());
    if(v[n-2].second<=v[n-1].second){
        cout<<v[n-1].second;
    }
    else {
        cout<<v[n-1].first;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{
    int n;
    cin>>n;
    vector<pair<ll,ll>>v;
    for(int i=0;i<n;i++){
        ll x,y;
        cin>>x>>y;
        v.push_back(make_pair(x,y));
    }
    sort(v.begin(),v.end());
    if(v[n-2].second<=v[n-1].second || n==1){
        cout<<v[n-1].second;
    }
    else {
        cout<<v[n-1].first;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{
    int n;
    cin>>n;
    vector<pair<ll,ll>> v;
    for(int i=0;i<n;i++){
        ll x,y;
        cin>>x>>y;
        v.push_back(make_pair(x,y));
    }
    sort(v.begin(),v.end());
    ll best=-1;
    for(int i=0;i<n;i++){
        if(best<=v[i].second){
            best=v[i].second;
        }
        else {
            best=v[i].first;
        }
    }
    cout<<best;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{
    int n;
    cin>>n;
    vector<pair<ll,ll>> v;
    for(int i=0;i<n;i++){
        ll x,y;
        cin>>x>>y;
        v.push_back(make_pair(x,y));
    }
    sort(v.begin(),v.end());
    bool ok=true;
    for(int i=1;i<n;i++){
        if(v[i].second<v[i-1].second){
            ok=false;
            break;
        }
    }
    if(ok){
        cout<<v[n-1].second;
    }
    else {
        cout<<v[n-1].first;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{
    int n;
    cin>>n;
    vector<pair<ll,ll>> v;
    for(int i=0;i<n;i++){
        ll x,y;
        cin>>x>>y;
        v.push_back(make_pair(x,y));
    }
    sort(v.begin(),v.end());
    ll mx=0,l;
    for(int i=0;i<n;i++){
        if(mx<=v[i].second){
            l=i;
            mx=v[i].second;
        }
    }
    if(v[l].second==v[n-1].second){
        cout<<v[n-1].second;
    }
    else {
        cout<<v[n-1].first;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{
    int n;
    cin>>n;
    vector<pair<ll,ll>> v;
    for(int i=0;i<n;i++){
        ll x,y;
        cin>>x>>y;
        v.push_back(make_pair(x,y));
    }
    sort(v.begin(),v.end());
    bool ok=true;
    for(int i=1;i<n;i++){
        if(v[i].second<v[i-1].second){
            ok=false;
        }
    }
    if(ok){
        cout<<v[n-1].second;
    }
    else {
        cout<<v[n-1].first;
    }
    return 0;
}


#include <bits/stdc++.h>
//arshak.khoshnevis

using namespace std;

const int MAXX = 5e3 + 10;
int n;
pair <long long, long long> a[MAXX];

bool Ok() {
	for(int i = 1; i < n; i++)
		if(a[i].second < a[i - 1].second)
			return 0;
	return 1;
}

int main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n;
	for(int i = 0; i < n; i++)
		cin >> a[i].first >> a[i].second;
	sort(a, a + n);
	if(Ok())
		return cout << a[n - 1].second << endl, 0;
	if(a[n - 1].second >= a[n - 2].second)
		return cout << a[n - 1].second << endl, 0;
	return cout << a[n - 1].first << endl, 0;
}


#include <bits/stdc++.h>
//arshak.khoshnevis

using namespace std;

const int MAXX = 5e3 + 10;
int n, ans[MAXX];
pair <long long, long long> a[MAXX];

bool Ok() {
	for(int i = 1; i < n; i++)
		if(a[i].second < a[i - 1].second)
			return 0;
	return 1;
}

int main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n;
	for(int i = 0; i < n; i++)
		cin >> a[i].first >> a[i].second;
	sort(a, a + n);
	if(Ok())
		return cout << a[n - 1].second << endl, 0;
	ans[0] = min(a[0].first, a[0].second);
	for(int i = 1; i < n; i++) {
		if(a[i].second > ans[i - 1])
			ans[i] = a[i].second;
		else
			ans[i] = a[i].first;
	}
	return cout << ans[n - 1] << endl, 0;
}


#include <bits/stdc++.h>
//arshak.khoshnevis

using namespace std;

const int MAXX = 5e3 + 10;
int n, ans[MAXX];
pair <int, int> a[MAXX];

int Search_min(int x) {
	int mn = 1e9 + 10;
	for(int i = 0; i < n; i++)
		if(a[i].first == x)
			mn = min(a[i].second, mn);
	return mn;
}

int Search_max(int x) {
	int mx = 0;
	for(int i = 0; i < n; i++)
		if(a[i].first == x)
			mx = max(a[i].second, mx);
	return mx;
}

bool Ok() {
	for(int i = 1; i < n; i++)
		if(Search_max(a[i].first) < Search_min(a[i - 1].first))
			return 0;
	return 1;
}

int main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n;
	for(int i = 0; i < n; i++)
		cin >> a[i].first >> a[i].second;
	sort(a, a + n);
	if(Ok())
		return cout << a[n - 1].second << endl, 0;
	ans[0] = min(a[0].first, a[0].second);
	for(int i = 1; i < n; i++) {
		if(a[i].second > ans[i - 1])
			ans[i] = a[i].second;
		else
			ans[i] = a[i].first;
	}
	return cout << ans[n - 1] << endl, 0;
}


#include <bits/stdc++.h>
//arshak.khoshnevis

using namespace std;

const int MAXX = 5e3 + 10;
int n, ans[MAXX];
pair <int, int> a[MAXX];

int Search_min(int x) {
	int mn = 1e9 + 10;
	for(int i = 0; i < n; i++)
		if(a[i].first == x)
			mn = min(a[i].second, mn);
	return mn;
}

bool Ok() {
	for(int i = 1; i < n; i++)
		if(a[i].second < Search_min(a[i - 1].second))
			return 0;
	return 1;
}

int main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n;
	for(int i = 0; i < n; i++)
		cin >> a[i].first >> a[i].second;
	sort(a, a + n);
	if(Ok())
		return cout << a[n - 1].second << endl, 0;
	ans[0] = min(a[0].first, a[0].second);
	for(int i = 1; i < n; i++) {
		if(a[i].second > ans[i - 1])
			ans[i] = a[i].second;
		else
			ans[i] = a[i].first;
	}
	return cout << ans[n - 1] << endl, 0;
}


#include <bits/stdc++.h>
//arshak.khoshnevis

using namespace std;

const int MAXX = 5e3 + 10;
int n, ans[MAXX];
pair <int, int> a[MAXX];

int main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n;
	for(int i = 0; i < n; i++)
		cin >> a[i].first >> a[i].second;
	sort(a, a + n);
	ans[0] = min(a[0].first, a[0].second);
	for(int i = 1; i < n; i++) {
		if(a[i].second >= ans[i - 1])
			ans[i] = a[i].second;
		else
			ans[i] = a[i].first;
	}
	return cout << ans[n - 1] << endl, 0;
}


#include <bits/stdc++.h>
//arshak.khoshnevis

using namespace std;

const int MAXX = 5e3 + 10;
int n, ans[MAXX];
pair <int, int> a[MAXX];

int Search_min(int x) {
	int mn = 1e9 + 10;
	for(int i = 0; i < n; i++)
		if(a[i].first == x)
			mn = min(a[i].second, mn);
	return mn;
}

bool Ok() {
	for(int i = 1; i < n; i++)
		if(a[i].second < Search_min(a[i - 1].first))
			return 0;
	return 1;
}

int main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n;
	for(int i = 0; i < n; i++)
		cin >> a[i].first >> a[i].second;
	sort(a, a + n);
	if(Ok())
		return cout << a[n - 1].second << endl, 0;
	ans[0] = min(a[0].first, a[0].second);
	for(int i = 1; i < n; i++) {
		if(a[i].second > ans[i - 1])
			ans[i] = a[i].second;
		else
			ans[i] = a[i].first;
	}
	return cout << ans[n - 1] << endl, 0;
}


#include <bits/stdc++.h>
//arshak.khoshnevis

using namespace std;

const int MAXX = 5e3 + 10;
int n;
pair <long long, long long> a[MAXX];

bool Ok() {
	for(int i = 1; i < n; i++)
		if(a[i].second < a[i - 1].second)
			return 0;
	return 1;
}

int main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n;
	for(int i = 0; i < n; i++)
		cin >> a[i].first >> a[i].second;
	sort(a, a + n);
	if(Ok())
		return cout << min(a[n - 1].first, a[n - 1].second) << endl, 0;
	return cout << a[n - 1].first << endl, 0;
}


#include <bits/stdc++.h>
#include <stdio.h>
#define int long long int
#define us unsigned int
#define intt int
#define null 0
using namespace std;

void IOS()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

int32_t main()
{

IOS();

#ifdef LOCAL_PROJECT
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

int a[1000000];
for(int i=0;i<10000000000;i++)
a[0]=i;

}


#include <bits/stdc++.h>
#include <stdio.h>
#define int long long int
#define us unsigned int
#define intt int
#define null 0
using namespace std;

void IOS()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

int32_t main()
{

IOS();

#ifdef LOCAL_PROJECT
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

int a[100000000];
for(int i=0;i<100000000;i++)
a[i]=i;

}


#include <bits/stdc++.h>
#include <stdio.h>
#define int long long int
#define us unsigned int
#define intt int
#define null 0
using namespace std;

void IOS()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

int32_t main()
{

IOS();

#ifdef LOCAL_PROJECT
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

int a[1000000];

}


#include <bits/stdc++.h>
#include <stdio.h>
#define int long long int
#define us unsigned int
#define intt int
#define null 0
using namespace std;

void IOS()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

int32_t main()
{

IOS();

#ifdef LOCAL_PROJECT
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

int a[10000000];
for(int i=0;i<10000000;i++)
a[i]=i;

}


#include <bits/stdc++.h>
#include <stdio.h>
#define int long long int
#define us unsigned int
#define intt int
#define null 0
using namespace std;

void IOS()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

int32_t main()
{

IOS();

#ifdef LOCAL_PROJECT
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

int a[1000000];
for(int i=0;i<1000000000;i++)
a[0]=i;

}


#include <bits/stdc++.h>
#include <stdio.h>
#define int long long int
#define us unsigned int
#define intt int
#define null 0
using namespace std;

void IOS()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

int32_t main()
{

IOS();

#ifdef LOCAL_PROJECT
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

int a[1000000];
for(int i=0;i<1000000;i++)
a[i]=i;

}


#include <bits/stdc++.h>
#include <stdio.h>
#define int long long int
#define us unsigned int
#define intt int
#define null 0
using namespace std;

void IOS()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

int32_t main()
{

IOS();

#ifdef LOCAL_PROJECT
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

int n;
cin>>n;

pair<int,int> p[n];
for(int i=0;i<n;i++)
{
    cin>>p[i].first>>p[i].second;
}

sort(p,p+n);

for(int i=0;i<n-1;i++)
{
    if(p[i].second>p[i+1].second)
    {
        cout<<p[n-1].first;
        return 0;
    }
}
cout<<p[n-1].second;

}


#include <bits/stdc++.h>
#include <stdio.h>
#define int long long int
#define us unsigned int
#define intt int
#define null 0
using namespace std;

void IOS()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

int32_t main()
{

IOS();

#ifdef LOCAL_PROJECT
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

int n;
cin>>n;

pair<int,int> p[n];
for(int i=0;i<n;i++)
{
    cin>>p[i].first>>p[i].second;
}

sort(p,p+n);
int maxx=-1;
for(int i=0;i<n;i++)
{
   if(maxx<=p[i].second)
    maxx=p[i].second;
   else
    maxx=p[i].first;
}

cout<<maxx;

}


#include <bits/stdc++.h>
#include <stdio.h>
#define int long long int
#define us unsigned int
#define intt int
#define null 0
using namespace std;

void IOS()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

int32_t main()
{

IOS();

#ifdef LOCAL_PROJECT
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

int a[1000000];
for(int i=0;i<100000000000;i++)
a[i]=i;

}


#include <bits/stdc++.h>
#include <stdio.h>
#define int long long int
#define us unsigned int
#define intt int
#define null 0
using namespace std;

void IOS()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

int32_t main()
{

IOS();

#ifdef LOCAL_PROJECT
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

int a[1000000000];

}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[n]];
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]) b[c[i+1]]=b[c[i]]; mx(max(mx<b[c[i]]))
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[n]];
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]){ b[c[i+1]]=b[c[i]]; mx=max(mx,b[c[i]]);}
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[n]];
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]) b[c[i+1]]=b[c[i]];
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=1000000000000;
    for (int i=1;i<=n;++i) mx=min(mx,b[i]);
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx && b[c[i]]==mx) b[c[i+1]]=b[c[1]];
      else if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]){ b[c[i+1]]=b[c[i]];}
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    mx=max(mx,b[c[n]]);
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[n]];
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx && b[c]==mx) b[c[i+1]]=b[c[i]];
      else if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]){ b[c[i+1]]=b[c[i]];}
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    mx=max(mx,b[c[n]]);
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[n]];
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx && b[c[i]]==mx) b[c[i+1]]=b[c[i]];
      else if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]){ b[c[i+1]]=b[c[i]];}
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    mx=max(mx,b[c[n]]);
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[n]];
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx && b[c[i]]==mx) b[c[i+1]]=b[c[1]];
      else if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]){ b[c[i+1]]=b[c[i]];}
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    mx=max(mx,b[c[n]]);
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[n]];
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]){ b[c[i+1]]=b[c[i]];}
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    mx=max(mx,b[c[n]]);
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[n]];
    for (int i=1;i<n;++i){
      if (b[c[i]]>b[c[i+1]] || b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
    }
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
ll b[10000];
bool cmp(int x,int y){
  if (a[x]<a[y]) re 1;
  else if (a[x]==a[y] && b[x]<b[y]) re 1;
  else re 0;
}
int main()
{
    ll n;
    cin >> n;
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=1000000000000;
    for (int i=1;i<=n;++i) mx=min(mx,b[i]);
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx && b[c[i]]==mx) b[c[i+1]]=b[c[1]];
      else if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]){ b[c[i+1]]=b[c[i]];}
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    mx=max(mx,b[c[n]]);
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[n]];
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx && b[c]==mx) b[c[i+1]]=b[c[i]];
      else if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]])
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]){ b[c[i+1]]=b[c[i]];}
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    mx=max(mx,b[c[n]]);
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[n]];
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]) b[c[i+1]]=b[c[i]]; mx=max(mx<b[c[i]]);
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re return
ll a[10000];
bool cmp(int x,int y){
  re a[x]<a[y];
}
int main()
{
    ll n;
    cin >> n;
    ll b[n+10];
    ll c[n+10];
    for (int i=1;i<=n;++i) cin >> a[i] >> b[i];
    for (int i=1;i<=n;++i) c[i]=i;
    sort(c+1,c+n+1,cmp);
    ll mx=b[c[1]];
    for (int i=1;i<n;++i){
      if (b[c[i+1]]<mx && b[c[i]]==mx) b[c[i+1]]=b[c[1]];
      else if (b[c[i+1]]<mx) mx=max(mx,a[c[i+1]]);
      if (b[c[i]]>b[c[i+1]] && a[c[i]]==a[c[i+1]]){ b[c[i+1]]=b[c[i]];}
      else if (b[c[i]]>b[c[i+1]])  mx=max(mx,a[c[i+1]]);
    }
    mx=max(mx,b[c[n]]);
    cout << mx;
    return 0;
}


#include <bits/stdc++.h>
#define ll          long long int
#define ff          first
#define ss          second
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define mpll        map<ll,ll>
#define mpii        map<int,int>
#define vi          vector<ll>
#define vvi         vector<vi>
#define INF         1e9
#define bigMod      1000000007
#define pi          acos(-1.00)
#define fastRead    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX =1e6+6;
ll arr[2000005],brr[2000005],crr[2000005];

int main()
{
    fastRead;
    ll n,a,b;
    cin>>n;
    vector<pll>v,v1;
    for(int i=0; i<n; i++)
    {
        cin>>a>>b;
        v.push_back({a,b});
    }
    sort(v.begin(),v.end());
    if(n==1)
        cout<<min(v[0].first,v[0].second)<<"\n";
        else if(n==2)
        {
            ll mn=max(v[0].second,v[1].second);
            cout<<min(v[1].first,mn)<<"\n";
        }
        else if(v[n-3].second<=v[n-2].second&&v[n-2].second<=v[n-1].second)
            cout<<v[n-1].second<<"\n";

    else if(v[n-3].second>v[n-2].second&&v[n-2].second<v[n-1].second)
    {
        if(v[n-2].first<=v[n-1].second)
        cout<<v[n-1].second<<"\n";
        else cout<<v[n-1].first<<"\n";
    }
    else cout<<v[n-1].first<<"\n";
}


#include <bits/stdc++.h>
#define ll          long long int
#define ff          first
#define ss          second
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define mpll        map<ll,ll>
#define mpii        map<int,int>
#define vi          vector<ll>
#define vvi         vector<vi>
#define INF         1e9
#define bigMod      1000000007
#define pi          acos(-1.00)
#define fastRead    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX =1e6+6;
ll arr[2000005],brr[2000005],crr[2000005];

int main()
{
    fastRead;
    ll n,a,b;
    cin>>n;
    vector<pll>v,v1;
    for(int i=0; i<n; i++)
    {
        cin>>a>>b;
        v.push_back({a,b});
    }
    sort(v.begin(),v.end());
    if(n==1)
        cout<<min(v[0].first,v[0].second)<<endl;
    else if(v[n-2].second<=v[n-1].second)
        cout<<v[n-1].second<<"\n";
    else cout<<v[n-1].first<<"\n";
}


#include <bits/stdc++.h>
#define ll          long long int
#define ff          first
#define ss          second
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define mpll        map<ll,ll>
#define mpii        map<int,int>
#define vi          vector<ll>
#define vvi         vector<vi>
#define INF         1e9
#define bigMod      1000000007
#define pi          acos(-1.00)
#define fastRead    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX =1e6+6;
ll arr[2000005],brr[2000005],crr[2000005];

int main()
{
    fastRead;
    ll n,a,b;
    cin>>n;
    vector<pll>v,v1;
    for(int i=0; i<n; i++)
    {
        cin>>a>>b;
        v.push_back({b,a});
        v1.push_back({a,b});
    }
    sort(v.begin(),v.end());

    int f=1;
    for(int i=0; i<n-1; i++)
        if(v[i].second>v[i+1].second)
            f=0;
    if(f)
        cout<<v[n-1].first<<endl;
    else
    {
        ll ans=0;
        sort(v1.begin(),v1.end());
        if(v1[n-1].second>=v1[n-2].first)
            ans=v1[n-1].second;
        else ans=v1[n-1].first;
        cout<<ans<<endl;
    }
}


#include <bits/stdc++.h>
#define ll          long long int
#define ff          first
#define ss          second
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define mpll        map<ll,ll>
#define mpii        map<int,int>
#define vi          vector<ll>
#define vvi         vector<vi>
#define INF         1e9
#define bigMod      1000000007
#define pi          acos(-1.00)
#define fastRead    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX =1e6+6;
ll arr[2000005],brr[2000005],crr[2000005];

int main()
{
    fastRead;
    ll n,a,b;
    cin>>n;
    vector<pll>v,v1;
    for(int i=0; i<n; i++)
    {
        cin>>a>>b;
        v.push_back({a,b});
    }
    sort(v.begin(),v.end());
    if(n==1)
        cout<<min(v[0].first,v[0].second)<<endl;
    else if(v[n-2].second<=v[n-1].second&&v[n-2].first<=v[n-1].second)
        cout<<v[n-1].second<<"\n";
    else cout<<v[n-1].first<<"\n";
}


#include <bits/stdc++.h>
#define ll          long long int
#define ff          first
#define ss          second
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define mpll        map<ll,ll>
#define mpii        map<int,int>
#define vi          vector<ll>
#define vvi         vector<vi>
#define INF         1e9
#define bigMod      1000000007
#define pi          acos(-1.00)
#define fastRead    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX =1e6+6;
ll arr[2000005],brr[2000005],crr[2000005];

int main()
{
    fastRead;
    ll n,a,b;
    cin>>n;
    vector<pll>v,v1;
    for(int i=0; i<n; i++)
    {
        cin>>a>>b;
        v.push_back({a,b});
    }
    sort(v.begin(),v.end());

    ll ans=v[0].second;
    for(int i=1;i<n;i++)
    {
        if(v[i].second>=ans)
            ans=v[i].second;
            else ans=v[i].first;
    }
    cout<<ans<<"\n";
}


#include <bits/stdc++.h>
#define ll          long long int
#define ff          first
#define ss          second
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define mpll        map<ll,ll>
#define mpii        map<int,int>
#define vi          vector<ll>
#define vvi         vector<vi>
#define INF         1e9
#define bigMod      1000000007
#define pi          acos(-1.00)
#define fastRead    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX =1e6+6;
ll arr[2000005],brr[2000005],crr[2000005];

int main()
{
    fastRead;
    ll n,a,b;
    cin>>n;
    vector<pll>v;
    for(int i=0; i<n; i++)
    {
        cin>>a>>b;
        v.push_back({b,a});
    }
    sort(v.begin(),v.end());
    int f=1;
    for(int i=0; i<n-1; i++)
        if(v[i].second>v[i+1].second)
            f=0;
    if(f)
    cout<<v[n-1].first<<endl;
    else{
            ll ans=0;
        for(int i=0;i<n;i++)
        {
            if(v[i].second>ans)
              ans=v[i].second;
        }
    cout<<ans<<endl;
    }
}


#include <bits/stdc++.h>
#define ll          long long int
#define ff          first
#define ss          second
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define mpll        map<ll,ll>
#define mpii        map<int,int>
#define vi          vector<ll>
#define vvi         vector<vi>
#define INF         1e9
#define bigMod      1000000007
#define pi          acos(-1.00)
#define fastRead    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX =1e6+6;
ll arr[2000005],brr[2000005],crr[2000005];

int main()
{
    fastRead;
    ll n,a,b;
    cin>>n;
    vector<pll>v,v1;
    for(int i=0; i<n; i++)
    {
        cin>>a>>b;
        v.push_back({a,b});
    }
    sort(v.begin(),v.end());
    if(v[n-2].second<=v[n-1].second)
        cout<<v[n-1].second<<"\n";
    else cout<<v[n-1].first<<"\n";
}


#include <bits/stdc++.h>
#define ll          long long int
#define ff          first
#define ss          second
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define mpll        map<ll,ll>
#define mpii        map<int,int>
#define vi          vector<ll>
#define vvi         vector<vi>
#define INF         1e9
#define bigMod      1000000007
#define pi          acos(-1.00)
#define fastRead    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX =1e6+6;
ll arr[2000005],brr[2000005],crr[2000005];

int main()
{
    fastRead;
    ll n,a,b;
    cin>>n;
    vector<pll>v,v1;
    for(int i=0; i<n; i++)
    {
        cin>>a>>b;
        v.push_back({a,b});
    }
    sort(v.begin(),v.end());

    ll ans=v[0].second;
    for(int i=1; i<n; i++){
        if(v[i].second>=ans)
            ans=v[i].second;
        else ans=v[i].first;
    }
  cout<<ans<<endl;
}


#include<bits/stdc++.h>
#define pb push_back
#define in insert
#define ff first
#define ss second
#define mp make_pair
#define int long long
#define uint unsigned long long
#define rep(i,x,m) for(int i=x;i<m;i++)
#define repr(i,x,m) for(int i=x;i>=m;i--)
#define MOD 1000000007
#define endl "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define vi vector<int>
#define vs vector<string>
#define print(v) for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl
using namespace std;
#define noob ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

void ram5564()
{
    int n;
    cin>>n;
    vector<pair<int,int>>v;
    vi v1,v2;
    rep(i,0,n)
    {
        int x,y;
        cin>>x>>y;
        v.pb(mp(x,y));
        v1.pb(x);
        v2.pb(y);
    }
    sort(all(v));
    sort(all(v1));
    sort(all(v2));
    int ok=0;
    for(int i=0;i<n-1;++i)
    {
        if(v[i+1].ss<v[i].ss)
        {
            ok=1;
            break;
        }
    }
    if(ok)
    {
        cout<<v1[n-1];return;
    }
    cout<<v2[n-1];
}

signed main()
{
        noob
        #ifndef ONLINE_JUDGE
         freopen("input.txt","r",stdin);
         freopen("output.txt","w",stdout);
         #endif

        int t=1;
        //cin>>t;
        while(t--)
        ram5564();
        return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define in insert
#define ff first
#define ss second
#define mp make_pair
#define int long long
#define uint unsigned long long
#define rep(i,x,m) for(int i=x;i<m;i++)
#define repr(i,x,m) for(int i=x;i>=m;i--)
#define MOD 1000000007
#define endl "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define vi vector<int>
#define vs vector<string>
#define print(v) for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl
using namespace std;
#define noob ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

void ram5564()
{
    int n;
    cin>>n;
    vector<pair<int,int>>v;
    vi v1,v2;
    rep(i,0,n)
    {
        int x,y;
        cin>>x>>y;
        v.pb(mp(x,y));
        v1.pb(x);
        v2.pb(y);
    }
    sort(all(v));
    sort(all(v1));
    sort(all(v2));
    int ok=0;
    for(int i=0;i<n-1;++i)
    {
        if(v[i+1].ss<v[i].ss)
        {
            ok=1;
            break;
        }
    }
    if(ok)
    {
        cout<<v1[n-1];return;
    }
    cout<<min(v2[n-1],v1[n-1]);
}

signed main()
{
        noob
        #ifndef ONLINE_JUDGE
         freopen("input.txt","r",stdin);
         freopen("output.txt","w",stdout);
         #endif

        int t=1;
        //cin>>t;
        while(t--)
        ram5564();
        return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define in insert
#define ff first
#define ss second
#define mp make_pair
#define int long long
#define uint unsigned long long
#define rep(i,x,m) for(int i=x;i<m;i++)
#define repr(i,x,m) for(int i=x;i>=m;i--)
#define MOD 1000000007
#define endl "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define vi vector<int>
#define vs vector<string>
#define print(v) for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl
using namespace std;
#define noob ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

void ram5564()
{
    int n;
    cin>>n;
    vector<pair<int,int>>v;
    vi v1,v2;
    rep(i,0,n)
    {
        int x,y;
        cin>>x>>y;
        v.pb(mp(x,y));
        v1.pb(x);
        v2.pb(y);
    }
    sort(all(v));
    sort(all(v1));
    sort(all(v2));
    int ok=0;
    if(n==1)
    {
        cout<<min(v[0].ff,v[0].ss);return;
    }
    for(int i=0;i<n-1;++i)
    {
        if(v[i+1].ss<v[i].ss)
        {
            ok=1;
            break;
        }
    }
    if(ok)
    {
        cout<<v1[n-1];return;
    }
    //cout<<"r";
    cout<<v2[n-1]-v2[0]+1;
}

signed main()
{
        noob
        #ifndef ONLINE_JUDGE
         freopen("input.txt","r",stdin);
         freopen("output.txt","w",stdout);
         #endif

        int t=1;
        //cin>>t;
        while(t--)
        ram5564();
        return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define in insert
#define ff first
#define ss second
#define mp make_pair
#define int long long
#define uint unsigned long long
#define rep(i,x,m) for(int i=x;i<m;i++)
#define repr(i,x,m) for(int i=x;i>=m;i--)
#define MOD 1000000007
#define endl "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define vi vector<int>
#define vs vector<string>
#define print(v) for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl
using namespace std;
#define noob ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

void ram5564()
{
    int n;
    cin>>n;
    vector<pair<int,int>>v;
    vi v1,v2;
    rep(i,0,n)
    {
        int x,y;
        cin>>x>>y;
        v.pb(mp(x,y));
        v1.pb(x);
        v2.pb(y);
    }
    sort(all(v));
    sort(all(v1));
    sort(all(v2));
    int ok=0;
    if(n==1)
    {
        cout<<min(v[0].ff,v[0].ss);return;
    }
    for(int i=0;i<n-1;++i)
    {
        if(v[i+1].ss<v[i].ss)
        {
            ok=1;
            break;
        }
    }
    if(ok)
    {
        cout<<v1[n-1];return;
    }
    //cout<<"r";
    cout<<v2[n-1];
}

signed main()
{
        noob
        #ifndef ONLINE_JUDGE
         freopen("input.txt","r",stdin);
         freopen("output.txt","w",stdout);
         #endif

        int t=1;
        //cin>>t;
        while(t--)
        ram5564();
        return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define in insert
#define ff first
#define ss second
#define mp make_pair
#define int long long
#define uint unsigned long long
#define rep(i,x,m) for(int i=x;i<m;i++)
#define repr(i,x,m) for(int i=x;i>=m;i--)
#define MOD 1000000007
#define endl "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define vi vector<int>
#define vs vector<string>
#define print(v) for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl
using namespace std;
#define noob ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

void ram5564()
{
    int n;
    cin>>n;
    vector<pair<int,int>>v;
    vi v1,v2;
    rep(i,0,n)
    {
        int x,y;
        cin>>x>>y;
        v.pb(mp(x,y));
        v1.pb(x);
        v2.pb(y);
    }
    sort(all(v));
    sort(all(v1));
    sort(all(v2));
    int ok=0;
    for(int i=0;i<n-1;++i)
    {
        if(v[i+1].ss<v[i].ss)
        {
            ok=1;
            break;
        }
    }
    if(ok)
    {
        cout<<v1[n-1];return;
    }
    cout<<min(v2[n-1]-v2[0]+1,v1[n-1]-v1[0]+1);
}

signed main()
{
        noob
        #ifndef ONLINE_JUDGE
         freopen("input.txt","r",stdin);
         freopen("output.txt","w",stdout);
         #endif

        int t=1;
        //cin>>t;
        while(t--)
        ram5564();
        return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define in insert
#define ff first
#define ss second
#define mp make_pair
#define int long long
#define uint unsigned long long
#define rep(i,x,m) for(int i=x;i<m;i++)
#define repr(i,x,m) for(int i=x;i>=m;i--)
#define MOD 1000000007
#define endl "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define vi vector<int>
#define vs vector<string>
#define print(v) for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl
using namespace std;
#define noob ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

void ram5564()
{
    int n;
    cin>>n;
    vector<pair<int,int>>v;
    vi v1,v2;
    rep(i,0,n)
    {
        int x,y;
        cin>>x>>y;
        v.pb(mp(x,y));
        v1.pb(x);
        v2.pb(y);
    }
    sort(all(v));
    sort(all(v1));
    sort(all(v2));
    int ok=0;
    if(n==1)
    {
        cout<<min(v[0].ff,v[0].ss);return;
    }
    int day=-1;
    for(int i=0;i<n-1;++i)
    {
        if(day<=v[i].ss)
        {
            day=v[i].ss;

        }
        else
            day=v[i].ff;
    }

    cout<<day;
}

signed main()
{
        noob
        #ifndef ONLINE_JUDGE
         freopen("input.txt","r",stdin);
         freopen("output.txt","w",stdout);
         #endif

        int t=1;
        //cin>>t;
        while(t--)
        ram5564();
        return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define in insert
#define ff first
#define ss second
#define mp make_pair
#define int long long
#define uint unsigned long long
#define rep(i,x,m) for(int i=x;i<m;i++)
#define repr(i,x,m) for(int i=x;i>=m;i--)
#define MOD 1000000007
#define endl "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define vi vector<int>
#define vs vector<string>
#define print(v) for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl
using namespace std;
#define noob ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

void ram5564()
{
    int n;
    cin>>n;
    vector<pair<int,int>>v;
    vi v1,v2;
    rep(i,0,n)
    {
        int x,y;
        cin>>x>>y;
        v.pb(mp(x,y));
        v1.pb(x);
        v2.pb(y);
    }
    sort(all(v));
    sort(all(v1));
    sort(all(v2));
    int ok=0;
    if(n==1)
    {
        cout<<min(v[0].ff,v[0].ss);return;
    }
    int day=-1;
    for(int i=0;i<n;++i)
    {
        if(day<=v[i].ss)
        {
            day=v[i].ss;

        }
        else
            day=v[i].ff;
    }

    cout<<day;
}

signed main()
{
        noob
        #ifndef ONLINE_JUDGE
         freopen("input.txt","r",stdin);
         freopen("output.txt","w",stdout);
         #endif

        int t=1;
        //cin>>t;
        while(t--)
        ram5564();
        return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define in insert
#define ff first
#define ss second
#define mp make_pair
#define int long long
#define uint unsigned long long
#define rep(i,x,m) for(int i=x;i<m;i++)
#define repr(i,x,m) for(int i=x;i>=m;i--)
#define MOD 1000000007
#define endl "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define vi vector<int>
#define vs vector<string>
#define print(v) for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl
using namespace std;
#define noob ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

void ram5564()
{
    int n;
    cin>>n;
    vector<pair<int,int>>v;
    vi v1,v2;
    rep(i,0,n)
    {
        int x,y;
        cin>>x>>y;
        v.pb(mp(x,y));
        v1.pb(x);
        v2.pb(y);
    }
    sort(all(v));
    sort(all(v1));
    sort(all(v2));
    int ok=0;
    if(n==1)
    {
        cout<<min(v[0].ff,v[0].ss);return;
    }
    for(int i=0;i<n-1;++i)
    {
        if(v[i+1].ss<v[i].ss)
        {
            ok=1;
            break;
        }
    }
    if(ok)
    {
        cout<<v1[n-1];return;
    }
    cout<<v1[n-1]-v1[0]+1;
}

signed main()
{
        noob
        #ifndef ONLINE_JUDGE
         freopen("input.txt","r",stdin);
         freopen("output.txt","w",stdout);
         #endif

        int t=1;
        //cin>>t;
        while(t--)
        ram5564();
        return 0;
}


    #pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
#define l(i,a,b) for(auto i=a;i<b;i++)
#define lr(i,a,b) for(auto i=a;i>=b;i--)
#define ll long long
#define lli long long int
#define ld long double
#define vec vector<int>
#define mii map<int,int>
#define vl vector<long long>
#define se set <long long int>
#define pi pair<long long,long long>
#define pb push_back
#define mp make_pair
#define ft first
#define sd second
#define all(v) v.begin(), v.end()
#define in(x) cin>>x
#define o(x) cout<<x
#define SYNC ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
bool compare(const pair<long long,long long> &a, const pair<long long,long long> &b)
{
    if(a.sd == b.sd)
    return a.ft<a.ft;
   return a.sd<b.sd;
}
bool col1(const pair<long long,long long> &a, const pair<long long,long long> &b)
{
    return a.ft<b.ft;
}

int main()
{
    ll n;
    in(n);
    vector<pi> v;
    l(i,0,n)
    {
        ll x,y;
        in(x)>>y;
        v.push_back({x,y});
    }
    sort(v.begin(),v.end(),compare);

    if(is_sorted(v.begin(),v.end(),col1))
    o(v[n-1].sd);
    else
    {
        sort(v.begin(),v.end(),col1);
        o(v[n-1].ft);
    }

}


    #pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
#define l(i,a,b) for(auto i=a;i<b;i++)
#define lr(i,a,b) for(auto i=a;i>=b;i--)
#define ll long long
#define lli long long int
#define ld long double
#define vec vector<int>
#define mii map<int,int>
#define vl vector<long long>
#define se set <long long int>
#define pi pair<long long,long long>
#define pb push_back
#define mp make_pair
#define ft first
#define sd second
#define all(v) v.begin(), v.end()
#define in(x) cin>>x
#define o(x) cout<<x
#define SYNC ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
bool compare(const pair<long long,long long> &a, const pair<long long,long long> &b)
{
    if(a.sd == b.sd)
    return a.ft<b.ft;

   return a.sd<b.sd;
}
bool col2(const pair<long long,long long> &a, const pair<long long,long long> &b)
{
    return a.sd<b.sd;
}

int main()
{
    ll n;
    in(n);
    vector<pi> v;
    l(i,0,n)
    {
        ll x,y;
        in(x)>>y;
        v.push_back({x,y});
    }
    sort(v.begin(),v.end());
    auto temp = v[0].sd;
    ll ans=temp;
    l(i,1,n)
    {
        if(v[i].sd>=temp)
        {
            temp=v[i].sd;
        }
        else
        {
            temp=v[i].ft;
        }
        ans=temp;
    }
    o(ans);

}