use std::cmp; use std::collections::HashMap; use std::io::*; use std::io::{stderr, stdin}; use std::str::FromStr; fn main() { let cin = stdin(); let mut sc = Scanner::new(cin.lock()); let n = sc.next::(); let q = sc.next::(); let a = sc.vec::(n); let mut mp = HashMap::new(); for i in 0..n { mp.entry(a[i]).or_insert(vec![]).push(i); } let mut dp = vec![vec![2e9 as usize; n]; q + 1]; dp[0][0] = 0; let mut prv = 0; for i in 0..q { let b = sc.next::(); if i == 0 { for j in mp.get(&b).unwrap() { dp[i + 1][*j] = cmp::min(dp[i + 1][*j], dp[i][0] + *j); } } else { for j in mp.get(&prv).unwrap() { for k in mp.get(&b).unwrap() { dp[i + 1][*k] = cmp::min( dp[i + 1][*k], dp[i][*j] + (cmp::max(*j, *k) - cmp::min(*j, *k)), ); } } } prv = b; } let mut mi = usize::MAX; for i in mp.get(&prv).unwrap() { mi = cmp::min(mi, dp[q][*i]); } println!("{}", mi); } pub struct Scanner { reader: R, } #[allow(dead_code)] impl Scanner { fn new(reader: R) -> Scanner { Scanner { reader: reader } } fn read(&mut self) -> Option { let token = self .reader .by_ref() .bytes() .map(|c| c.unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect::(); if token.is_empty() { None } else { token.parse::().ok() } } fn next(&mut self) -> T { if let Some(s) = self.read() { s } else { writeln!(stderr(), "Terminated with EOF").unwrap(); std::process::exit(0); } } fn vec(&mut self, n: usize) -> Vec { (0..n).map(|_| self.next()).collect() } fn char(&mut self) -> char { self.next::().chars().next().unwrap() } }