跳到正文

题解

题解:P1001 A+B Problem

CsBalloon约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年2月4日
篇幅
约 4 分钟
获赞
7
题目
P1001

版本

  1. v1当前

本篇题解前置知识:splay

思路分析

知周所众,平衡树是一个可以高效维护区间问题的数据结构。看到此题,我们可以将其转化为两个元素的区间,对区间求和,显然,可以使用平衡树解决。

代码实现

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,tot;
struct Node
{
    Node *ls,*rs,*fa;
    int val,siz,idx,sum;
}tr[100010],*rt,*NIL,*cnt;
void update(Node *x)
{
    if (x==NIL)
        return ;
    x->siz=x->ls->siz+x->rs->siz+1;
    x->sum=x->ls->sum+x->rs->sum+x->val;
}//更新节点
bool getson(Node *x)
{
    return x==x->fa->rs;
}//左右儿子
void rotate(Node *x)
{
    Node *fa=x->fa,*gfa=fa->fa;
    if (!getson(x))
    {
        if (!getson(fa))
            gfa->ls=x;
        else
            gfa->rs=x;
        x->fa=gfa;
        fa->ls=x->rs;
        x->rs->fa=fa;
        x->rs=fa;
        fa->fa=x;
    }
    else
    {
        if (!getson(fa))
            gfa->ls=x;
        else
            gfa->rs=x;
        x->fa=gfa;
        fa->rs=x->ls;
        x->ls->fa=fa;
        x->ls=fa;
        fa->fa=x;
    }
    update(fa);
    update(x);
}//旋转
void splay(Node *x,Node *y)
{
    while (x->fa!=y)
    {
        Node *fa=x->fa,*gfa=fa->fa;
        if (gfa!=y)
        {
            if (getson(x)==getson(fa))
                rotate(fa);
            else
                rotate(x);
        }
        rotate(x);
    }
    if (y==NIL)
        rt=x;
    update(x);
}//splay操作
Node *newnode(int x)
{
    Node *p=++cnt;
    p->val=p->sum=x;
    p->siz=1;
    p->fa=p->ls=p->rs=NIL;
    p->idx=++tot;
    return p;
}
void ins(Node *&u,int x,Node *fa)
{
    if (u==NIL)
    {
        u=newnode(x);
        u->fa=fa;
        splay(u,NIL);
        return ;
    }
    if (u->val>=x)
        ins(u->ls,x,u);
    else
        ins(u->rs,x,u);
    update(u);
}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    NIL=&tr[0];
    NIL->val=0x7f7f7f7f;
    NIL->siz=0;
    NIL->fa=NIL->ls=NIL->rs=NIL;
    cnt=NIL;
    rt=NIL;
    ins(rt,0x7f7f7f7f,NIL);
    ins(rt,-0x7f7f7f7f,NIL);//初始化+哨兵节点

    int a,b;
    cin>>a>>b;

    ins(rt,a,NIL);
    ins(rt,b,NIL);//插入

    cout<<rt->sum;
    return 0;
}

提醒

注意指针不要越界!!!

原文