跳到正文

题解

AALC001D 题解&浅谈线段树(4)

NoneOfTheAbove约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年10月13日
收录
2026年11月26日
更新
2026年11月26日
篇幅
约 5 分钟
获赞
3

版本

  1. v1当前

前言

这些文章同时都是 AALC001 的题解,因为该比赛只涉及普通线段树和带懒标线段树,所以文章中不会提及可持久化线段树、线段树分裂、线段树合并等高级线段树知识。

AALC001A 题解&浅谈线段树(1)

AALC001B 题解&浅谈线段树(2)

AALC001C 题解&浅谈线段树(3)

本题是普通线段树的一个习题,所以直接进入题目。

luogu link

atcoder link

Solution

因为数据范围保证:0≤Ai≤20 \le A_i \le 2,所以逆序对只可能有 1,01,0,2,02,0 和 2,12,1 三种情况,所以对于一个区间,维护它的 0,1,20,1,2 的个数 cnt0,cnt1,cnt2cnt_0,cnt_1,cnt_2 和 (1,0),(2,0),(2,1)(1,0),(2,0),(2,1) 数对的个数 cnt1,0,cnt2,0,cnt2,1cnt_{1,0},cnt_{2,0},cnt_{2,1}。

这个也挺好合并的,因为数对 (x,y)(x,y) 的两个数要么在同一个块,要么在两个不同的块。在同一块的就是两个儿子的 cntx,ycnt_{x,y} 之和。在不同块的就利用乘法原理,有左儿子的 cntxcnt_x 乘上右儿子的 cntycnt_y 个。

一个节点
C++
struct node
{
    ll cnt0,cnt1,cnt2,cnt10,cnt20,cnt21;
    node operator+(node a) const
    {
        return {cnt0+a.cnt0,cnt1+a.cnt1,cnt2+a.cnt2,cnt10+a.cnt10+cnt1*a.cnt0,cnt20+a.cnt20+cnt2*a.cnt0,cnt21+a.cnt21+cnt2*a.cnt1}; // 合并方式
    }
}tr[maxn*4];

对于我们要查询的区间,直接用区间查询的方法查询,但不可以直接加起来,因为块之间也有逆序对,所以也要查询 node,然后每次合并左右儿子的结果。

Code

code
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef char ch;
typedef string str;
typedef double db;
typedef __int128 i128;
const ll inf=9e18,maxn=2e5+1;
const i128 Inf=1e35;
ll n,a[maxn],q;
struct node
{
    ll cnt0,cnt1,cnt2,cnt10,cnt20,cnt21;
    node operator+(node a) const
    {
        return {cnt0+a.cnt0,cnt1+a.cnt1,cnt2+a.cnt2,cnt10+a.cnt10+cnt1*a.cnt0,cnt20+a.cnt20+cnt2*a.cnt0,cnt21+a.cnt21+cnt2*a.cnt1};
    }
}tr[maxn*4];
void pushup(ll u)
{
    tr[u]=tr[u*2]+tr[u*2+1]; 
}
void update(ll u,ll x)
{
    tr[u]={(x==0),(x==1),(x==2),0,0,0};
}
void build(ll u,ll l,ll r)
{
    if(l==r) return update(u,a[l]);
    ll mid=(l+r)/2;
    build(u*2,l,mid),build(u*2+1,mid+1,r),pushup(u);
}
void modify(ll u,ll l,ll r,ll pos,ll x)
{
    if(l==r) return update(u,x);
    ll mid=(l+r)/2;
    if(pos<=mid) modify(u*2,l,mid,pos,x);
    else modify(u*2+1,mid+1,r,pos,x);
    pushup(u);
}
node query(ll u,ll l,ll r,ll ql,ll qr)
{
    if(ql<=l&&r<=qr) return tr[u];
    ll mid=(l+r)/2;
    node ans={0,0,0,0,0,0};
    if(ql<=mid) ans=ans+query(u*2,l,mid,ql,qr);
    if(qr>mid) ans=ans+query(u*2+1,mid+1,r,ql,qr);
    return ans;
} 
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
    cin>>n>>q;
    for(int i=1;i<=n;i++) cin>>a[i];
    build(1,1,n);
    while(q--)
    {
        ll op;
        cin>>op;
        if(op==1)
        {
            ll i,x;
            cin>>i>>x,modify(1,1,n,i,x);
        }
        else
        {
            ll l,r;
            cin>>l>>r;
            node nd=query(1,1,n,l,r);
            cout<<nd.cnt10+nd.cnt20+nd.cnt21<<"\n";
        }
    }
}
原文
存档评论1 条抓取于