牛客多校第一场 J-Different Integers

J-Different Integers

问题分析

第一次知道了是什么是离线+树状数组…..
首先题意就是要找两段区间里的不同数的个数。我们记 1 n 之间不同的个数为 t o t a l
对于若干个区间,我们对这些区间的右端点从小到大排序。
考虑去求 ( l , r ) 不同数字的的个数,假设 r = l a s t [ x ] ,那么当 l < f i r s r [ x ] 时, x 就肯定在这段 ( l , r ) 区间有出现,所以我们可以用树状数组维护,可以求出 ( l , r ) 区间内不同数字个数(假设为 c n t ),答案就是 t o t a l c n t

#include <bits/stdc++.h>
using std::cin;
using std::cout;
using std::endl;
const int N = 1E5+1;

struct node{
    int l,r,id;
    bool operator < (const node&u){
        return r < u.r;
    }
}Query[N];

int a[N],first[N],last[N],root[N],result[N],n,q;

inline void add(int idx)
{
    while(idx <= n){
        root[idx]++;
        idx += idx & -idx;
    }
}

inline int sum(int idx)
{
    int res = 0;
    while(idx>0) {
        res += root[idx];
        idx -= idx & -idx;
    }
    return res;
}

int main()
{
//    std::ios::sync_with_stdio(false);
    while(~scanf("%d%d",&n,&q))
    {
        memset(root,0, sizeof(root));
        memset(first,-1, sizeof(first));
        int total = 0;
        for(int i = 1; i <= n; ++i){
//            cin>>a[i];
            scanf("%d",a+i);
            last[a[i]] = i;
            if(first[a[i]] == -1){
                total++;
                first[a[i]] = i;
            }
        }
        for(int i = 0; i < q; ++i){
//            cin>>Query[i].l>>Query[i].r;
            scanf("%d%d",&Query[i].l,&Query[i].r);
            Query[i].id = i;
        }
        std::sort(Query,Query+q);
        for(int i = 0, k = 1; i < q; ++i){
            while(k < Query[i].r){
                if(last[a[k]] == k){
                    add(first[a[k]]);
                }
                k++;
            }
            result[Query[i].id] = total-(sum(Query[i].r-1)-sum(Query[i].l));
        }
        for(int i = 0; i < q; ++i)
//            cout<<result[i]<<endl;
            printf("%d\n",result[i]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Eternally831143/article/details/81175160
今日推荐