AT_abc392_f

· · 题解

题意简述

给你 n 个数和一个序列 p,让你将 i,插入到 p_i 的位置

思路

平衡树板子题,这里提供两种写法

1.vector暴力重构

这是一种类似于分块的做法。首先我们考虑暴力怎么做,是不是就是每次 \operatorname {insert} 到对应的位置上,这样极限复杂度是 O(n^2) 的,会超时。

我们考虑序列分块,每 \sqrt n 个数放在一个块里,每次 \operatorname {insert} 的复杂度变为 O(\sqrt n) ,当一个块长度过大时,直接暴力重构,即将所有的序列上的数取出再重新分块。

代码:

#include<bits/stdc++.h>
#define int long long 
using namespace std;
int len=3000;
vector<int> v[10010];
int n;
pair<int,int> find(int x)
{
    int cnt=1;
    while(x>v[cnt].size())
    {
        x-=v[cnt].size();
        cnt++;
    }
    return {cnt,x};
}
void rebuild()
{
    vector<int> tmp;
    int cnt=1;
    while(!v[cnt].empty())
    {
        for(auto i:v[cnt])
            tmp.emplace_back(i);
        v[cnt].clear();
        cnt++;
    }
    for(int i=0;i<tmp.size();i++)
    {
        v[i/len+1].emplace_back(tmp[i]);
    }
}
signed main()
{
    cin>>n;
    len=sqrt(n)+2;
    for(int i=1,x;i<=n;i++)
    {
        cin>>x;
        x--;
        auto id=find(x);
        v[id.first].insert(v[id.first].begin()+id.second,i);
        // cout<<id.first<<" "<<id.second<<endl;
        if(v[id.first].size()>20*len)
            rebuild();
    }
    int cnt=1;
    while(!v[cnt].empty())
    {
        for(auto i:v[cnt])
            cout<<i<<" ";
        cnt++;
    }
    return 0;
}

2.普通平衡树实现

这里我使用的是 \operatorname {FHQ - Treap} ,注意按排名分裂,最后输出按二叉搜索树的性质,即左边的权值小于根的权值小于右边的权值,对应到这道题就是排名。所以递归输出即可

代码:

#include<bits/stdc++.h>
using namespace std;
const int N=5e5+10;
int n;
struct fhq_treap
{
    int ch[2];
    int rd,siz,val;
}t[N];//排名分裂
int tot,root;
void push_up(int u)
{
    t[u].siz=t[t[u].ch[0]].siz+t[t[u].ch[1]].siz+1;
}
int New(int val)
{
    tot++;
    t[tot].rd=rand();
    t[tot].val=val;
    t[tot].siz=1;
    t[tot].ch[0]=t[tot].ch[1]=0;
    return tot;
}
int megry(int x,int y)//小根堆
{
    if(!x||!y)
        return x+y;
    if(t[x].rd<t[y].rd)
    {
        t[x].ch[1]=megry(t[x].ch[1],y);
        push_up(x);
        return x;
    }
    else
    {
        t[y].ch[0]=megry(x,t[y].ch[0]);
        push_up(y);
        return y;
    }
}
void split(int now,int val,int &x,int &y)
{
    if(!now)
    {
        x=y=0;
        return ;
    }
    if(val<=t[t[now].ch[0]].siz)
    {
        y=now;
        split(t[now].ch[0],val,x,t[now].ch[0]);
        push_up(now);
    }
    else
    {
        x=now;
        split(t[now].ch[1],val-t[t[now].ch[0]].siz-1,t[now].ch[1],y);
        push_up(now);
    }
}
void out(int u)
{
    if(!u)
        return ;
    out(t[u].ch[0]);
    cout<<t[u].val<<" ";
    out(t[u].ch[1]);
}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    int x=0,y=0;
    for(int i=1,in;i<=n;i++)
    {
        cin>>in;
        split(root,in-1,x,y);
        root=megry(megry(x,New(i)),y);
    }
    out(root);
    return 0;
}