「BJOI2018」求和

Posted zsbzsb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了「BJOI2018」求和相关的知识,希望对你有一定的参考价值。

「BJOI2018」求和

传送门
观察到 (k) 很小而且模数不会变,所以我们直接预处理 (k) 取所有值时树上前缀答案,查询的时候差分一下即可。
参考代码:

#include <algorithm>
#include <cstdio>
#define rg register
#define file(x) freopen(x".in", "r", stdin), freopen(x".out", "w", stdout)
using namespace std;
template < class T > inline void read(T& s) {
    s = 0; int f = 0; char c = getchar();
    while ('0' > c || c > '9') f |= c == '-', c = getchar();
    while ('0' <= c && c <= '9') s = s * 10 + c - 48, c = getchar();
    s = f ? -s : s;
}

const int _ = 3e5 + 5, p = 998244353;

int tot, head[_], nxt[_ << 1], ver[_ << 1];
inline void Add_edge(int u, int v)
{ nxt[++tot] = head[u], head[u] = tot, ver[tot] = v; }

int n, m, dep[_], val[51][_], fa[20][_];

inline int power(int x, int k) {
    int res = 1;
    for (; k; k >>= 1, x = 1ll * x * x % p)
        if (k & 1) res = 1ll * res * x % p;
    return res % p;
}

inline void dfs(int u, int f, int d) {
    dep[u] = d, fa[0][u] = f;
    for (rg int i = 1; i <= 19; ++i)
        fa[i][u] = fa[i - 1][fa[i - 1][u]];
    for (rg int k = 1; k <= 50; ++k)
        val[k][u] = (val[k][f] + power(d, k)) % p;
    for (rg int i = head[u]; i; i = nxt[i]) {
        int v = ver[i]; if (v == f) continue ;
        dfs(v, u, d + 1);
    }
}

inline int LCA(int x, int y) {
    if (dep[x] < dep[y]) swap(x, y);
    for (rg int i = 19; ~i; --i)
        if (dep[fa[i][x]] >= dep[y]) x = fa[i][x];
    if (x == y) return x;
    for (rg int i = 19; ~i; --i)
        if (fa[i][x] != fa[i][y]) x = fa[i][x], y = fa[i][y];
    return fa[0][x];
}

inline int dist(int x, int y, int k) {
    int lca = LCA(x, y), res = 0;
    res = (val[k][x] - val[k][lca] + p) % p;
    res = (res + (val[k][y] - val[k][fa[0][lca]] + p) % p) % p;
    return res;
}

int main() {
#ifndef ONLINE_JUDGE
    file("cpp");
#endif
    read(n);
    for (rg int u, v, i = 1; i < n; ++i)
        read(u), read(v), Add_edge(u, v), Add_edge(v, u);
    dfs(1, 0, 0);
    read(m);
    for (rg int x, y, k; m--; )
        read(x), read(y), read(k), printf("%d
", dist(x, y, k));
    return 0;
}

以上是关于「BJOI2018」求和的主要内容,如果未能解决你的问题,请参考以下文章

[BJOI2018]求和

[BJOI 2018]求和

题解 P4427 [BJOI2018]求和

BJOI2018 求和

D BJOI2018求和

[BJOI2018]求和