#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; void Main() { int N,Q; cin >> N >> Q; vector A(N),B(Q); vector comp; comp.reserve(N + Q); for(int i = 0;i < N;i++) { cin >> A[i]; comp.push_back(A[i]); } for(int i = 0;i < Q;i++) { cin >> B[i]; comp.push_back(B[i]); } sort(comp.begin(),comp.end()); comp.erase(unique(comp.begin(),comp.end()), comp.end()); vector> G(comp.size() + 1); for(int i = 0;i < N;i++) { int id = lower_bound(comp.begin(),comp.end(),A[i]) - comp.begin(); G[id].push_back(i); } G[comp.size()].push_back(0); int cur = comp.size(); vector dp(1, 0); for(int q = 0;q < Q;q++) { int nxt = lower_bound(comp.begin(),comp.end(), B[q]) - comp.begin(); vector n_dp(G[nxt].size(), (int)1e9); int j = 0; for(int i = 0;i < (int)G[nxt].size();i++) { while(j < G[cur].size() && G[cur][j] < G[nxt][i]) { j++; } if(j > 0) { n_dp[i] = min(n_dp[i], dp[j - 1] + G[nxt][i] - G[cur][j - 1]); } if(j < (int)G[cur].size()) { n_dp[i] = min(n_dp[i], dp[j] + G[cur][j] - G[nxt][i]); } } swap(n_dp,dp); swap(nxt, cur); } int ans = (int)1e9; for(int i = 0;i < (int)dp.size();i++) { ans = min(ans, dp[i]); } cout << ans << "\n"; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt = 1; /* cin >> tt; */ while(tt--) Main(); }