F.Sasha and the Wedding Binary Search Tree:
题目描述:
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static int mod = 998244353;
static long[] pow;
static long[] inv;
public static void main(String[] args) throws IOException {
pow = new long[500005];
inv = new long[500005];
pow[0] = inv[0] = 1;
for (int i = 1; i < 500005; i++) {
pow[i] = pow[i-1] * i % mod;
inv[i] = qkm(pow[i]);
}
int t = f.nextInt();
while (t > 0) {
solve();
t--;
}
w.flush();
w.close();
}
static Node[] nodes;
static int[] a;
public static void solve() throws IOException{
p = 1;
int n = f.nextInt(); int c = f.nextInt();
nodes = new Node[n+1];
a = new int[n+2];
for (int i = 0; i < n + 1; i++) {
nodes[i] = new Node();
}
for (int i = 1; i <= n; i++) {
int l = f.nextInt(); int r = f.nextInt(); int val = f.nextInt();
if (l != -1)
nodes[i].l = nodes[l];
if (r != -1)
nodes[i].r = nodes[r];
nodes[i].val = val;
}
a[0] = 1; a[n+1] = c;
dfs(nodes[1]);
long ans = 1;
for (int i = 0; i < n + 1;) {
int j = i+1;
while (j < n+2 && a[j] == -1) j++;
if (i+1 < j){
long res = 1;
for (int k = a[j] - a[i] + j-i-1; k > a[j] - a[i]; k--) {
res *= k;
res %= mod;
}
ans *= res * inv[j-i-1] % mod;
ans %= mod;
}
i = j;
}
System.out.println(ans);
}
static int p = 1;
public static void dfs(Node cur){
if (cur.l != null) dfs(cur.l);
a[p++] = cur.val;
if (cur.r != null) dfs(cur.r);
}
public static long bin(int x, int y){
return pow[x] * inv[y] % mod * inv[x-y] % mod;
}
public static class Node{
Node l;
Node r;
int val;
}
static long qkm (long x){
long res = 1;
long b = mod - 2;
while (b > 0) {
if ((b & 1) == 1) res = (res * x) % mod;
x = x*x % mod;
b >>= 1;
}
return res;
}
static PrintWriter w = new PrintWriter(new OutputStreamWriter(System.out));
static Input f = new Input(System.in);
static class Input {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Input(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() throws IOException{
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public Double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
思路解析:
显然我们可以得到这个二叉搜索树的中序表现形式,假设为 [2 -1 -1 4 -1 -1 -1 5] 其中-1表示该点的值是任意的,但是必须满足 1 <= -1 <= c。 那我们可以发现此时二叉搜索树需要满足,[2 -1 -1 4]为非降序数列, [4 -1 -1 -4 5] 为非降序数列。 对于第一个数列其中-1可能为2或3或4,如果我们确定了2的个数和3的个数和4的个数,此时那么对应的 -1 -1 这个非降序数列也就确定了,所以非降序数列的个数,就变成了将2个球分为3组的情况数,并且要求每组的个数大于等于0。然后我们发现第一个序列的取值,并不影响下一个序列,所以变成了每个序列答案相乘。
代码实现: