本题目是一个可以用莫队解决的题目,而且是一个裸的,(当然可以用线段树和树状数组,本蒟蒻目前线段树学的不好,,,,)
依然是分块+排序,把对应的解放到对应的位置,最后顺序输出即可
我今天也算是知道了为什么大佬们的莫队代码,都是添加应用在删除前面,因为如果一开始就删除的话,很有可能会产生负值,整个程序不会崩溃,但是会影响后面的计算,所以以后写莫队还是要以下面的顺序写的
while(r < rr)ins(++r);
while(l > ll)ins(--l);
while(l < ll)del(l++);
while(r > rr)del(r--);
话不多说,直接上代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int t, n, m, res, block;
const int maxn = 100100;
int a[maxn], pos[maxn], ans[maxn], vis[maxn];
struct p{
int l, r, id;
} c[maxn];
bool cmp(p a, p b){
if(pos[a.l] == pos[b.l])return a.r < b.r;
return pos[a.l] < pos[b.l];
}
void ins(int x){
int xx = a[x];
vis[xx] = 1;
if(vis[xx - 1] && vis[xx + 1])res--;
else if(vis[xx - 1] == 0 && vis[xx + 1] == 0)res++;
}
void del(int x){
int xx = a[x];
vis[xx] = 0;
if(vis[xx - 1] && vis[xx + 1])res++;
else if(vis[xx - 1] == 0 && vis[xx + 1] == 0)res--;
}
int main()
{
scanf("%d", &t);
while(t--){
scanf("%d %d", &n, &m);
memset(vis, 0, sizeof vis);
memset(ans, 0, sizeof ans);
block = sqrt(n);
for(int i = 1; i <= n; i++){
scanf("%d", &a[i]);
pos[i] = (i - 1) / block + 1;
}
for(int i = 1; i <= m; i++){
scanf("%d %d", &c[i].l, &c[i].r);
c[i].id = i;
}
sort(c + 1, c + 1 + m, cmp);
int l, r;
l = 1;
r = 0;
res = 0;
for(int i = 1; i <= m; i++){
int ll = c[i].l, rr = c[i].r;
while(r < rr)ins(++r);
while(l > ll)ins(--l);
while(l < ll)del(l++);
while(r > rr)del(r--);
ans[c[i].id] = res;
}
for(int i = 1; i <= m; i++)printf("%d\n", ans[i]);
}
return 0;
}