HDU 4638 group(离线+树状数组)

时间:2023-01-26 00:31:11

此题实质上是询问每段区间[l,r]内的数字能组成多少段连续的数字。

不大好用线段树合并区间来写。

考虑离线,类似于HH的项链的话,对询问按右端点排序,对于右端点的每一次右移,则对于询问,实际上是求的后缀区间。

如果前面已经出现了a[r]-1的话,那么它们能组成连续的区间,a[r]+1同理。

剩下的模仿HH的项链即可。

# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi acos(-1.0)
# define eps 1e-
# define MOD
# define INF
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<,l,mid
# define rch p<<|,mid+,r
# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
int res=, flag=;
char ch;
if((ch=getchar())=='-') flag=;
else if(ch>=''&&ch<='') res=ch-'';
while((ch=getchar())>=''&&ch<='') res=res*+(ch-'');
return flag?-res:res;
}
void Out(int a) {
if(a<) {putchar('-'); a=-a;}
if(a>=) Out(a/);
putchar(a%+'');
}
const int N=;
//Code begin... struct Q{int l, r, id;}q[N];
int a[N], to[N][], vis[N], tree[N], ans[N], n; bool comp(Q a, Q b){return a.r<b.r;}
void add(int x, int val){while (x<=n) tree[x]+=val, x+=lowbit(x);}
int sum(int x)
{
int res=;
while (x) res+=tree[x], x-=lowbit(x);
return res;
}
int main ()
{
int T, m;
T=Scan();
while (T--) {
mem(to,); mem(vis,); mem(tree,);
n=Scan(); m=Scan();
FOR(i,,n) {
a[i]=Scan();
if (vis[a[i]-]) to[i][]=vis[a[i]-];
if (vis[a[i]+]) to[i][]=vis[a[i]+];
vis[a[i]]=i;
}
FOR(i,,m) q[i].l=Scan(), q[i].r=Scan(), q[i].id=i;
sort(q+,q+m+,comp);
int now=;
FOR(i,,m) {
while (now<q[i].r) {
++now;
add(now,);
if (to[now][]) add(to[now][],-);
if (to[now][]) add(to[now][],-);
}
ans[q[i].id]=sum(q[i].r)-sum(q[i].l-);
}
FOR(i,,m) Out(ans[i]), putchar('\n');
}
return ;
}