跳到正文

题解

题解:CF1929F Sasha and the Wedding Binary Search Tree

_Ch1F4N_约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
题目
CF1929F

版本

  1. v1当前

简单题。

二叉搜索树的限制不好处理,考虑求出中序遍历后,限制等价于其不减,对于一段极长的未填区域,可以通过插板求出填数方案,虽然组合数的上标非常大,但是下标的和是 O(n)O(n) 的,于是暴力处理即可做到 O(nlog⁡n)O(n \log n)。

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod = 998244353;
const int maxn = 5e5+114;
int L[maxn],R[maxn];
int a[maxn],b[maxn],tot;
int qpow(int a,int b){
    if(b==0) return 1;
    if(b==1) return a;
    int res=qpow(a,b/2);
    res=res*res%mod;
    if(b%2==1) res=res*a%mod;
    return res;
}
int n,c;
void build(int cur){
    if(cur==-1) return ;
    build(L[cur]);
    b[++tot]=a[cur];
    build(R[cur]);
}
int C(int n,int m){
    int res=1;
    for(int i=n;i>=n-m+1;i--) res=res*i%mod;
    for(int i=1;i<=m;i++) res=res*qpow(i,mod-2)%mod;
    return res;
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int t;
    cin>>t;
    while(t--){
        tot=0;
        cin>>n>>c;
        for(int i=1;i<=n;i++) cin>>L[i]>>R[i]>>a[i];
        build(1);
        int lstp=0,lstv=1;
        int res=1;
        for(int i=1;i<=n;i++){
            if(b[i]!=-1){
                res=res*C(b[i]-lstv+i-lstp-1,i-lstp-1)%mod;
                lstp=i;
                lstv=b[i];
            }
        }
        res=res*C(c-lstv+n+1-lstp-1,n+1-lstp-1)%mod;
        cout<<res<<"\n";
    }
    return 0;
}
原文