F - Range Set Query

原题链接

题解

暴力想法:

每次枚举每次查询

O(qn)

进阶想法:对查询按 r 排序,用树状数组维护 [1,r] 内,该范围内每个数最后一次出现的位置

code

#include<bits/stdc++.h>
using namespace std;
/*
#define double long double
const int inf=1e18;
const int mod=1e9+7;

const int N=4e5;
int qpow(int a,int n)
{
    int res=1;
    while(n)
    {
        if(n&1) res=res*a%mod;
        a=a*a%mod;
        n>>=1;
    }
    return res;
}
int inv(int x)
{
    return qpow(x,mod-2);
}
int fa[2000005];
int finds(int now){return now==fa[now]?now:finds(fa[now]);}

vector<int> G[200005];

int dfn[200005],low[200005];
int cnt=0,num=0;
int in_st[200005]={0};
stack<int> st;
int belong[200005]={0};

void scc(int now,int fa)
{
    dfn[now]=++cnt;
    low[now]=dfn[now];
    in_st[now]=1;
    st.push(now);

    for(auto next:G[now])
    {
        if(next==fa) continue;

        if(!dfn[next])
        {
            scc(next,now);
            low[now]=min(low[now],low[next]);
        }
        else if(in_st[next])
        {
            low[now]=min(low[now],dfn[next]);
        }
    }

    if(low[now]==dfn[now])
    {
        int x;
        num++;
        do
        {
            x=st.top();
            st.pop();
            in_st[x]=0;
            belong[x]=num;
        }while(x!=now);
    }
}
vector<int> prime;
bool mark[200005]={0};
void shai()
{
    for(int i=2;i<=200000;i++)
    {
        if(!mark[i]) prime.push_back(i);

        for(auto it:prime)
        {
            if(it*i>200000) break;

            mark[it*i]=1;
            if(it%i==0) break;
        }
    }
}
*/
#define int long long
#define lowbit(x) ((x)&(-x))
int tree[1000005];
struct node
{
    int l,r;
    int id;
}q[1000005];
int a[1000005];
int n,Q;
void update(int x,int v)
{
    while(x<=n)
    {
        tree[x]+=v;
        x+=lowbit(x);
    }
}

bool cmp(node b,node c)
{
    return b.r<c.r;
}
int query(int x)
{
    int res=0;
    while(x)
    {
        res+=tree[x];
        x-=lowbit(x);
    }
    return res;
}

int pre[1000005]={0};
int ans[1000005]={0};
void solve()
{
    cin>>n;

    for(int i=1;i<=n;i++) cin>>a[i];

    int it=1;

    cin>>Q;
    for(int i=1;i<=Q;i++)
    {
        cin>>q[i].l>>q[i].r;
        q[i].id=i;
    }

    sort(q+1,q+1+Q,cmp);

    for(int i=1;i<=Q;i++)
    {
        if(q[i].r!=q[i-1].r)
        {
            while(it<=q[i].r)
            {
                if(pre[a[it]])
                {
                    update(pre[a[it]],-1);
                }
                update(it,1);
                pre[a[it]]=it;
                it++;
            }
        }
        ans[q[i].id]=query(q[i].r)-query(q[i].l-1);
    }

    for(int i=1;i<=Q;i++) cout<<ans[i]<<'\n';
}
signed main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int TT=1;
    //cin>>TT;
    while(TT--) solve();
    return 0;
}


posted @   纯粹的  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示