牛客多校第一场 J-Different Integers

127 篇文章 0 订阅
85 篇文章 2 订阅

J-Different Integers

问题分析

第一次知道了是什么是离线+树状数组…..
首先题意就是要找两段区间里的不同数的个数。我们记 1n 1 − n 之间不同的个数为 total t o t a l
对于若干个区间,我们对这些区间的右端点从小到大排序。
考虑去求 (l,r) ( l , r ) 不同数字的的个数,假设 r=last[x] r = l a s t [ x ] ,那么当 l<firsr[x] l < f i r s r [ x ] 时, x x 就肯定在这段(l,r)区间有出现,所以我们可以用树状数组维护,可以求出 (l,r) ( l , r ) 区间内不同数字个数(假设为 cnt c n t ),答案就是 totalcnt 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值