不是 mod
,不是 long long
,不是 dep[0]=-1
,不是位运算优先级,不是 LCA 写错了,不是容斥写错了,不是 maxn
开小了,不是 dep
数组用错了,不是 u 是 v 祖先没返回,不是遍历时把 i >= 0
写成 i
,不是厌氧程序。
emmm 总之就是把所有讨论区帖子都看了照着改了一遍还是 0 分。
#include <bits/stdc++.h>
using namespace std;
#define int long long
const long long N = 1e6 + 1, P = 51, mod = 998244353;
vector<int> e[N]; int POW2[25];
long long dep[N], a[N][P], fa[N][20];
void dfs(int now, int _fa) {
fa[now][0] = _fa;
for(int i = 0;i < e[now].size();i++)
if(e[now][i] == _fa) continue;
else dep[e[now][i]] = dep[now] + 1,
dfs(e[now][i], now);
} int lca(int x, int y) {
if(dep[x] > dep[y]) swap(x, y);
for(int i = 18;i >= 0;i--)
if((dep[y] - dep[x]) >= POW2[i])
y = fa[y][i];
if(x == y) return x;
for(int i = 18;i >= 0;i--)
if(fa[y][i] != fa[x][i])
y = fa[y][i], x = fa[x][i];
return fa[x][0];
} signed main() {
int n; cin >> n; POW2[0] = 1;
for(int i = 1;i <= 20;i++) POW2[i] = POW2[i-1] * 2ll;
for(int i = 1, u, v;i < n;i++)
cin >> u >> v,
e[u].push_back(v), e[v].push_back(u);
dfs(1, 0); for(int i = 1;i <= n;i++) {
a[i][1] = i; int now = i; a[i][1] = (a[i][1] + a[i-1][1]) % mod;
for(int j = 2;j <= 50;j++)
now = (1ll * now * i) % mod,
a[i][j] = now, a[i][j] = (a[i][j] + a[i-1][j]) % mod;
} for(int i = 1;i <= 18;i++)
for(int j = 1;j <= n;j++)
fa[j][i] = fa[fa[j][i-1]][i-1];
int m; cin >> m; while(m--) {
int x, y, z; cin >> x >> y >> z;
int _ = lca(x, y);
long long ans = ((a[dep[x]][z] - a[dep[_]-1][z] + 3 * mod) % mod
+ (a[dep[y]][z] - a[dep[_]-1][z] + 3 * mod) % mod
- a[dep[_]][z] + 3 * mod) % mod;
cout << ans << endl;
}
return 0;
}