「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\n", dist(x, y, k));
	return 0;
}
posted @ 2020-01-23 22:51  Sangber  阅读(190)  评论(0编辑  收藏  举报