Header Ads

Header ADS

Group(HDU-4638)

 Problem Link:https://vjudge.net/problem/HDU-4638

Main Idea:

Given a sequence of length n, each query gives an interval and asks how many consecutive segments the interval can be divided into 

In fact, the idea is not very difficult. Consider any value x and after it is deleted, judge whether x+1, x-1 exist, and then the answer is derived.

Solution:

#include<cstdio>

#include<cstring>

#include<algorithm>

#include<iostream>

#include<string>

#include<vector>

#include<stack>

#include<bitset>

#include<cstdlib>

#include<cmath>

#include<set>

#include<map>

#include<list>

#include<deque>

#include<queue>

using namespace std;

typedef long long ll;

static const ll mod=1000000000+7;

const ll N=100010;

struct nnode{

    int l,r,id;

}g[N];

int n,m,unit,a[N];

ll num[N],res[N],tmp;

void add(int i){

    num[a[i]]=1;

    if(num[a[i]-1] && num[a[i]+1])tmp--;

    if(!num[a[i]-1] && !num[a[i]+1])tmp++;

}

void del(int i){

    num[a[i]]=0;

    if(num[a[i]-1] && num[a[i]+1])tmp++;

    if(!num[a[i]-1] && !num[a[i]+1])tmp--;

}

void solve(){

    tmp=0;

    memset(num,0,sizeof(num));

    unit=(int)sqrt(1.0*n);

    sort(g+1,g+1+m,[](nnode a,nnode b){return a.l/unit!=b.l/unit?a.l/unit<b.l/unit:a.r<b.r;});

    ll l=1,r=0;

    for(int i=1;i<=m;i++){

        while(r<g[i].r)add(++r);

        while(r>g[i].r)del(r--);

        while(l<g[i].l)del(l++);

        while(l>g[i].l)add(--l);

        res[g[i].id]=tmp;

    }

    for(int i=1;i<=m;i++)printf("%lld\n",res[i]);

}

int main()

{

    int t;

    scanf("%d",&t);

    while(t-->0){

    scanf("%d%d",&n,&m);

    for(int i=1;i<=n;i++)scanf("%d",&a[i]);

    for(int i=1;i<=m;i++){

        scanf("%d%d",&g[i].l,&g[i].r);

        g[i].id=i;

    }

    solve();}

}

No comments

Theme images by enot-poloskun. Powered by Blogger.