权值线段树

· · 个人记录

权值线段树是指线段树的节点管辖的不是一段下标,而是一段值域。接下来,我以 P1637 为例为大家讲解权值线段树。

题目概述

在 a _ 1 , a _ 2 , …… ,a _ n 中统计满足 i<j<k 且 a _ i < a _ j < a _ k 的所有三元组 i,j,k 的对数。

题目解法

别的解法不说,这里只讲解权值线段树的做法。

先考虑 i、j:从前往后循环,每次把 a _ j 所属节点加一。因为符合 i<j 的 i 对应的 a _ i 总在 a _ j 前面放入线段树,又因为要满足 a _ i < a _ j ,所以问题就转化为了求结点编号为 1 \thicksim a _ j - 1 的结点上的数之和,很容易想到线段树,时间复杂度:O(n \times \max a _ i \times log\max a _ i)。

再考虑 j、k:解法同上,从前往后循环改为从后往前循环。

最后将每个 j 对应的 i 的数量和对应的 k 的数量之积加起来,就是答案。

代码部分

最后,献上 \color {gold}\mathbb{CODE}:

#include <bits/stdc++.h>
#define int long long
using namespace std ;
const int NR = 1e5 + 5 ;
int n , ans ;
int a[NR] , tree[4 * NR] , le[NR] , ri[NR] ;
void pushup(int cur)
{
    tree[cur] = tree[cur * 2] + tree[cur * 2 + 1] ;
    return ;
}
void build(int cur , int lt , int rt)
{
    if(lt == rt)
    {
        tree[cur] = 0 ;
        return ;
    }
    int mid = (lt + rt) >> 1 ;
    build(cur * 2 , lt , mid) ;
    build(cur * 2 + 1 , mid + 1 , rt) ;
    pushup(cur) ;
    return ;
}
int query(int cur , int lt , int rt , int qx , int qy)
{
    if(lt > qy || rt < qx)
        return 0 ;
    if(lt >= qx && rt <= qy)
        return tree[cur] ;
    int mid = (lt + rt) >> 1 ;
    return query(cur * 2 , lt , mid , qx , qy) + query(cur * 2 + 1 , mid + 1 , rt , qx , qy) ;
}
void update(int cur , int lt , int rt , int qx , int qy , int val)
{
    if(lt > qy || rt < qx)
        return ;
    if(lt == rt)
    {
        tree[cur] += val ;
        return ;
    }
    int mid = (lt + rt) >> 1 ;
    update(cur * 2 , lt , mid , qx , qy , val) ;
    update(cur * 2 + 1 , mid + 1 , rt , qx , qy , val) ;
    pushup(cur) ;
    return ;
}
signed main()
{
    cin >> n ;
    for(int i = 1 ; i <= n ; i++)   cin >> a[i] ;
    build(1 , 1 , 1e5) ;
    for(int i = 1 ; i <= n ; i++)
    {
        le[i] = query(1 , 1 , 1e5 , 1 , a[i] - 1) ;
        update(1 , 1 , 1e5 , a[i] , a[i] , 1) ;
    }
    build(1 , 1 , 1e5) ;
    for(int i = n ; i >= 1 ; i--)
    {
        ri[i] = query(1 , 1 , 1e5 , a[i] + 1 , 1e5) ;
        update(1 , 1 , 1e5 , a[i] , a[i] , 1) ;
        ans += ri[i] * le[i] ;
    }
    cout << ans ;
    return 0 ;
}