HDU4638 Group 莫队

HDU4638 Group

题意:

n个数,m次询问。值为x的人可以 和 值为 x-1,x+1 的人一组,求每次所给的区间内有多少组。

1
5 2
3 1 2 5 4
1 5
2 4

第一次询问中 1 2 3 4 5 一组

第二次询问中 1 2一组,5一组

 

#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<bitset>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 2e5+10;
struct node
{
    int l,r,id;

}t[maxn];
int a[maxn];
int n,m,block;
int cnt[maxn],res[maxn],ans;

bool cmp(node a,node b){//按照奇偶性排序
    if( (a.l/block)==(b.l/block) ){//当左端点位于同一个块时
        if( (a.l/block)%2 )//左端点的块序号为奇数时
            return a.r<b.r;//按照从小到大排
        else//左端点的块序号为偶数时
            return a.r>b.r;//按照从大到小排
    }
    else//当左端点不位于同一个块时
        return a.l<b.l;//按照块的位置进行排序
    //return (a.l/block)^(b.l/block) ? a.l<b.l : ( ((a.l/block)&1)?a.r<b.r:a.r>b.r );
}
void add(int x)
{
    cnt[x] = 1;
    if(cnt[x-1] && cnt[x+1])
        ans--;
    else if(!cnt[x-1] && !cnt[x+1])
        ans++;
}
void del(int x)
{
    cnt[x] = 0;
    if(cnt[x-1] && cnt[x+1])
        ans++;
    else if(!cnt[x-1] && !cnt[x+1])
        ans--;
}
int main()
{
    int T;
    int l,r;
    scanf("%d",&T);
    for(int k=1;k<=T;k++)
    {
        memset(cnt,0,sizeof(cnt));
        scanf("%d%d",&n,&m);
        block = sqrt(1.0*n);
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        for(int i=1;i<=m;i++)
        {
            scanf("%d%d",&t[i].l,&t[i].r);
            t[i].id = i;
        }
        //printf("Case %d:\n",k);
        sort(t+1,t+m+1,cmp);
        l = t[1].l , r = t[1].l-1;
        ans = 0;
        for(int i=1;i<=m;i++)
        {   //范围先扩大后缩小
            while(l>t[i].l)  add(a[--l]);
            while(r<t[i].r)  add(a[++r]);
            while(l<t[i].l)  del(a[l++]);
            while(r>t[i].r)  del(a[r--]);
            res[t[i].id] = ans;
        }
        for(int i=1;i<=m;i++)
            printf("%d\n",res[i]);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值