zoukankan      html  css  js  c++  java
  • CSU 1515 Sequence

    莫队算法+map

    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<map>
    #include<algorithm>
    using namespace std;
    
    const int maxn=200000+10;
    int n,t,a[maxn],cnt[maxn*10],pos[maxn];
    struct X
    {
        int l,r,id;
    } s[maxn];
    int L,R;
    int Ans,f[maxn];
    
    bool cmp(const X&a,const X&b)
    {
        if(pos[a.l]==pos[b.l]) return a.r<b.r;
        return pos[a.l]<pos[b.l];
    }
    
    int main()
    {
        while(~scanf("%d",&n))
        {
            scanf("%d",&t);
            int sz=sqrt(n);
            for(int i=1; i<=n; i++)
            {
                scanf("%d",&a[i]);
                pos[i]=i/sz;
            }
            for(int i=1; i<=t; i++)
            {
                scanf("%d%d",&s[i].l,&s[i].r);
                s[i].id=i;
            }
    
            sort(s+1,s+1+t,cmp);
    
            map<int,int>m;
            Ans=0;
            for(int i=s[1].l; i<=s[1].r; i++)
            {
                Ans=Ans+m[a[i]-1]+m[a[i]+1];
                m[a[i]]++;
            }
    
            f[s[1].id]=Ans;
            L=s[1].l;
            R=s[1].r;
    
            for(int i=2; i<=t; i++)
            {
                while(L<s[i].l)
                {
                    Ans=Ans-m[a[L]-1]-m[a[L]+1];
                    m[a[L]]--;
                    L++;
                }
    
                while(L>s[i].l)
                {
                    L--;
                    Ans=Ans+m[a[L]-1]+m[a[L]+1];
                    m[a[L]]++;
                }
    
                while(R>s[i].r)
                {
                    Ans=Ans-m[a[R]-1]-m[a[R]+1];
                    m[a[R]]--;
                    R--;
                }
    
                while(R<s[i].r)
                {
                    R++;
                    Ans=Ans+m[a[R]-1]+m[a[R]+1];
                    m[a[R]]++;
                }
    
                f[s[i].id]=Ans;
            }
    
            for(int i=1; i<=t; i++)
                printf("%d
    ",f[i]);
        }
    
        return 0;
    }
  • 相关阅读:
    2.替换空格
    1.二维数组的查找
    poj 2431 expedition
    python入门第三天
    python入门第二天__练习题
    [Python3.6] print vs sys.stdout.write
    python入门第二天
    使用Flask-mail发送邮件无法连接主机
    KMP
    逆序对 线段树&树状数组 (重制版)
  • 原文地址:https://www.cnblogs.com/zufezzt/p/5403228.html
Copyright © 2011-2022 走看看