求救!!不会平衡树的蒟蒻用二叉搜索树做 90分TLE一点
查看原帖
求救!!不会平衡树的蒟蒻用二叉搜索树做 90分TLE一点
420667
Timmy_楼主2022/6/18 19:30
#include <iostream>
using namespace std;
struct tree
{
    int l,r;
    long long x;
}s[1000000];
int n;
int cnt=1;
long long maxn=1e15;
void insertion(long long key,int now)
{
    maxn=min(maxn,abs(s[now].x-key));
    //cout<<s[now].x<<" ";
    //cout<<maxn<<" ";
    if(key>s[now].x)
    {
        if(s[now].r==0)
        {
            s[now].r=cnt;
            s[cnt].x=key;
            return;
        }
        insertion(key,s[now].r);
    }
    else
    {
        if(s[now].l==0)
        {
            s[now].l=cnt;
            s[cnt].x=key;
            //cout<<".";
            return;
        }
        insertion(key,s[now].l);
    }
    return;
}
int main()
{
    ios::sync_with_stdio(false);
    long long ans=0;
    int i,j;
    cin>>n;
    int temp;
    cin>>temp;
    ans+=temp;
    s[1].x=temp;
    for(i=2; i<=n; i++)
    {
        cin>>temp;
        maxn=1e15;
        cnt++;
        insertion(temp,1);
        ans+=maxn;
        //cout<<endl;
        //cout<<endl<<maxn<<endl;
    }
    cout<<ans;
    return 0;
}
2022/6/18 19:30
加载中...