【题目链接】
【算法】
预处理i^k的前缀和,对于每次询问,树上倍增即可
时间复杂度 : O(nk + mlog(n))
【代码】
#include<bits/stdc++.h>
using namespace std;
#define MAXK 55
#define MAXN 300010
#define MAXLOG 20
const long long P = 998244353;
struct Edge
{
int to,nxt;
} e[MAXN<<1];
int n,x,i,j,y,q,k,Lca,tot;
int anc[MAXN][MAXLOG],dep[MAXN],head[MAXN],fa[MAXN];
long long p[MAXN][MAXK],s[MAXN][MAXK];
long long ans;
template <typename T> inline void read(T &x)
{
int f = 1; x = 0;
char c = getchar();
for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
x *= f;
}
template <typename T> inline void write(T x)
{
if (x < 0)
{
putchar('-');
x = -x;
}
if (x > 9) write(x/10);
putchar(x%10+'0');
}
template <typename T> inline void writeln(T x)
{
write(x);
puts("");
}
inline void add(int x,int y)
{
tot++;
e[tot] = (Edge){y,head[x]};
head[x] = tot;
}
inline void dfs(int u)
{
int i,v;
anc[u][0] = fa[u];
for (i = 1; i < MAXLOG; i++)
{
if (dep[u] < (1 << i)) break;
anc[u][i] = anc[anc[u][i-1]][i-1];
}
for (i = head[u]; i; i = e[i].nxt)
{
v = e[i].to;
if (fa[u] != v)
{
fa[v] = u;
dep[v] = dep[u] + 1;
dfs(v);
}
}
}
inline int lca(int x,int y)
{
int i,t;
if (dep[x] > dep[y]) swap(x,y);
t = dep[y] - dep[x];
for (i = 0; i < MAXLOG; i++)
{
if (t & (1 << i))
y = anc[y][i];
}
if (x == y) return x;
for (i = MAXLOG - 1; i >= 0; i--)
{
if (anc[x][i] != anc[y][i])
{
x = anc[x][i];
y = anc[y][i];
}
}
return fa[x];
}
int main()
{
read(n);
for (i = 1; i < n; i++)
{
read(x); read(y);
add(x,y);
add(y,x);
}
for (i = 1; i < n; i++)
{
p[i][0] = 1;
for (j = 1; j < MAXK; j++) p[i][j] = p[i][j-1] * i % P;
}
for (i = 1; i < n; i++)
{
for (j = 1; j < MAXK; j++)
{
s[i][j] = (s[i-1][j] + p[i][j]) % P;
}
}
dfs(1);
read(q);
while (q--)
{
read(x); read(y); read(k);
Lca = lca(x,y);
ans = (s[dep[x]][k] + s[dep[y]][k]) % P;
ans = ((ans - (2 * s[dep[Lca]][k]) % P) + P) % P;
ans = (ans + p[dep[Lca]][k] + P) % P;
writeln(ans);
}
return 0;
}