[HDU4638]Group(莫队)

题目描述

传送门

题解

莫队。

代码

#include
#include
#include
#include
#include
using namespace std;

const int max_n=1e5+5;

int T,n,m,t,cnt,ans;
int num[max_n],a[max_n],final[max_n],vis[max_n];
struct hp{int l,r,ln,rn,id;}q[max_n];

inline void clear(){
    t=cnt=ans=0;
    for (int i=1;i<=n;++i) num[i]=a[i]=vis[i]=final[i]=0;
}
inline int cmp(hp a,hp b){return a.lnint main(){
    scanf("%d",&T);
    while (T--){
        scanf("%d%d",&n,&m);
        clear();
        t=(int)sqrt(n);
        for (int i=1;i<=n;++i)
          if (i%t==0) num[i]=i/t;
          else num[i]=i/t+1;
        for (int i=1;i<=n;++i) scanf("%d",&a[i]);
        for (int i=1;i<=m;++i){
            scanf("%d%d",&q[i].l,&q[i].r);if (q[i].l>q[i].r) swap(q[i].l,q[i].r);
            q[i].ln=num[q[i].l];
            q[i].rn=num[q[i].r];
            q[i].id=i;
        }
        sort(q+1,q+m+1,cmp);
        for (int i=q[1].l;i<=q[1].r;++i){
            vis[a[i]]=true;
            if (!vis[a[i]-1]&&!vis[a[i]+1]) ans++;
            else if (vis[a[i]-1]&&vis[a[i]+1]) ans--;
        }
        final[q[1].id]=ans;
        for (int i=2;i<=m;++i){
            if (q[i-1].l<q[i].l)
              for (int j=q[i-1].l;j<q[i].l;++j){
                vis[a[j]]--;
                if (!vis[a[j]-1]&&!vis[a[j]+1]) ans--;
                else if (vis[a[j]-1]&&vis[a[j]+1]) ans++;
              }

            if (q[i-1].l>q[i].l)
              for (int j=q[i-1].l-1;j>=q[i].l;--j){
                vis[a[j]]++;
                if (!vis[a[j]-1]&&!vis[a[j]+1]) ans++;
                else if (vis[a[j]-1]&&vis[a[j]+1]) ans--;
              }

            if (q[i-1].r<q[i].r)
              for (int j=q[i-1].r+1;j<=q[i].r;++j){
                vis[a[j]]++;
                if (!vis[a[j]-1]&&!vis[a[j]+1]) ans++;
                else if (vis[a[j]-1]&&vis[a[j]+1]) ans--;
              }

            if (q[i-1].r>q[i].r)
              for (int j=q[i-1].r;j>q[i].r;--j){
                vis[a[j]]--;
                if (!vis[a[j]-1]&&!vis[a[j]+1]) ans--;
                else if (vis[a[j]-1]&&vis[a[j]+1]) ans++;
              }

            final[q[i].id]=ans;
        }
        for (int i=1;i<=m;++i)
          printf("%d\n",final[i]);
    }
}

总结

vis数组要开int,不能用bool。因为有可能减了又加回来。

你可能感兴趣的:(题解,莫队)