#include<bits/stdc++.h>
using namespace std;
inline char gc(){
const short SIZE = 1 << 14;
static char buf[SIZE],*t1 = buf,*t2 = buf;
return t1 == t2 && (t2 = (t1 = buf) + fread(buf,1,SIZE,stdin),t1 == t2) ? EOF : *t1++;
}
int read(){
char c = gc();
int x = 0;
while(c < '0' || c > '9')
c = gc();
while(c >= '0' && c <= '9'){
x = (x << 3) + (x << 1) + c - 48;
c = gc();
}
return x;
}
const int N = 5e5 + 9,M = 5e5 + 9;
int n,m;
int a[N],pos[N];
int seq[N],top;
struct block{
int l,r;
} b[N];
short belong[N];
void build_block(){
const short block_len = 5000,block_cnt = (n + block_len - 1) / block_len;
for(short i = 1;i <= block_cnt;i++){
b[i].l = b[i - 1].r + 1;
b[i].r = b[i].l + block_len - 1;
}
b[block_cnt].r = n;
for(short i = 1;i <= block_cnt;i++)
for(int j = b[i].l;j <= b[i].r;j++)
belong[j] = i;
}
struct Query{
int l,r;
int id;
} q[M];
bool cmp(Query q1,Query q2){
return (belong[q1.l] ^ belong[q2.l]) ? belong[q1.l] < belong[q2.l] : q1.r > q2.r;
}
set<int> s;
long long ans[M],tmp;
void add(int x){
if(x <= *s.begin()){
s.insert(x);
int nex = *(++s.lower_bound(x));
tmp += abs(pos[x] - pos[nex]);
return;
}
if(x >= *s.rbegin()){
s.insert(x);
int pre = *(--s.lower_bound(x));
tmp += abs(pos[x] - pos[pre]);
return;
}
s.insert(x);
int pre = *(--s.lower_bound(x)),nex = *(++s.lower_bound(x));
tmp -= abs(pos[nex] - pos[pre]);
tmp += abs(pos[x] - pos[pre]);
tmp += abs(pos[x] - pos[nex]);
}
void del(int x){
if(x == *s.begin()){
int nex = *(++s.lower_bound(x));
tmp -= abs(pos[x] - pos[nex]);
s.erase(x);
return;
}
if(x == *s.rbegin()){
int pre = *(--s.lower_bound(x));
tmp -= abs(pos[x] - pos[pre]);
s.erase(x);
return;
}
int pre = *(--s.lower_bound(x)),nex = *(++s.lower_bound(x));
tmp -= abs(pos[x] - pos[pre]);
tmp -= abs(pos[x] - pos[nex]);
tmp += abs(pos[nex] - pos[pre]);
s.erase(x);
}
signed main(){
ios::sync_with_stdio(false);
cout.tie(0);
n = read();m = read();
build_block();
for(int i = 1;i <= n;i++){
a[i] = read();
pos[a[i]] = i;
}
for(int i = 1;i <= m;i++)
q[i] = (Query){read(),read(),i};
sort(q + 1,q + m + 1,cmp);
for(int i = q[1].l;i <= q[1].r;i++){
seq[++top] = a[i];
s.insert(a[i]);
}
sort(seq + 1,seq + top + 1);
for(int i = 1;i < top;i++)
tmp += abs(pos[seq[i + 1]] - pos[seq[i]]);
ans[q[1].id] = tmp;
int lres = q[1].l,rres = q[1].r;
for(int i = 2;i <= m;i++){
int L = q[i].l,R = q[i].r;
if(L == R){
tmp = 0;
ans[q[i].id] = tmp;
continue;
}
while(lres > L)
add(a[--lres]);
while(rres < R)
add(a[++rres]);
while(lres < L)
del(a[lres++]);
while(rres > R)
del(a[rres--]);
ans[q[i].id] = tmp;
}
for(int i = 1;i <= m;i++)
cout << ans[i] << '\n';
return 0;
}