省选题竟然考模板题…
直接预处理
然后每次询问求lca即可
注意得卡一波常…
c++代码如下:
#include<bits/stdc++.h>
#define rep(i,x,y) for(register int i = x ; i <= y ; ++ i)
#define repd(i,x,y) for(register int i = x ; i >= y ; -- i)
using namespace std;
typedef long long ll;
template<typename T>inline void read(T&x)
{
char c;int sign = 1;x = 0;
do { c = getchar(); if(c == '-') sign = -1; } while(!isdigit(c));
do { x = x * 10 + c - '0'; c = getchar(); }while(isdigit(c));
x *= sign;
}
const int N = 3e5+50;
int head[N],nxt[N << 1],to[N << 1],tot;
int n,m,mx,fa[N],deep[N],f[N][51],pre[N][51];
int size[N],hson[N],top[N];
inline void add(int x,int y)
{
nxt[tot] = head[x];
to[tot] = y;
head[x] = tot ++ ;
}
const int mod = 998244353;
void dfs(int x)
{
size[x] = 1;
mx = max(mx,deep[x]);
for(register int i = head[x];~i;i=nxt[i])
if(to[i] != fa[x])
{
fa[to[i]] = x;
deep[to[i]] = deep[x] + 1;
dfs(to[i]);
size[x] += size[to[i]];
if(size[hson[x]] < size[to[i]])
hson[x] = to[i];
}
}
void dfs2(int x,int t)
{
top[x] = t;
if(hson[x]) dfs2(hson[x],t);
for(register int i = head[x];~i;i=nxt[i])
if(to[i] != fa[x] && to[i] != hson[x])
dfs2(to[i],to[i]);
}
int lca(int x,int y)
{
while(top[x] != top[y])
{
if(deep[top[x]] < deep[top[y]]) swap(x,y);
x = fa[top[x]];
}
if(deep[x] > deep[y]) swap(x,y);
return x;
}
int main()
{
memset(head,-1,sizeof head);
read(n);
rep(i,2,n)
{
int u,v;
read(u); read(v);
add(u,v); add(v,u);
}
dfs(1);
dfs2(1,1);
rep(i,1,mx)
{
ll x = 1;
rep(j,1,50)
{
x = x * i % mod;
f[i][j] = (f[i-1][j] + x) % mod;
pre[i][j] = x;
}
}
read(m);
while(m--)
{
int u,v,k;
read(u); read(v); read(k);
int z = lca(u,v);
printf("%lld\n",((1ll * f[deep[u]][k] + f[deep[v]][k] - 1ll*f[deep[z]][k]*2 + pre[deep[z]][k])%mod+mod)%mod );
}
return 0;
}