题解:P11648 【MX-X8-T7】「TAOI-3」2236 A.D.
学习 dsu on tree + 高低位分块题解。
考虑对每个点算以它为 lca 的路径权值。现在的问题是:维护
dsu on tree。问题变成:维护桶
高低位分块。记
维护
精细实现的复杂度
::::info[
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i = (a);i <= (b);++i)
#ifdef ONLINE_JUDGE
static char buf[1000000],*p1=buf,*p2=buf;
#define getchar() p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++
#endif
int read(){
int x = 0;
char c = getchar();
for(;!isdigit(c);c = getchar());
for(;isdigit(c);c = getchar()) x = x * 10 + c - '0';
return x;
}
using ll = long long;
const int N = 5e5 + 5;
const ll mod = 998244353;
int n,k,c[N],dep[N],siz[N],son[N],cnt[N][15];
ll a[1 << 15],ans[N];
vector<int> G[N];
unordered_map<int,int> O[N],tmp;
namespace DS{
ll f[256][128];
void upd(int x,ll v){
rep(i,0,127) f[x >> 7][i] = (f[x >> 7][i] + v * a[i | (x & 127)]) % mod;
}
ll qry(int x,ll s = 0){
rep(i,0,255) s = (s + a[(i << 7) | (x >> 7 << 7)] * f[i][x & 127]) % mod;
return s;
}
}
void dfs0(int u,int ft){
rep(i,0,14) cnt[u][i] = cnt[ft][i] + (i == c[u]);
siz[u] = 1,dep[u] = dep[ft] + 1;
for(int v : G[u]) if(v != ft){
dfs0(v,u),siz[u] += siz[v];
if(siz[v] > siz[son[u]]) son[u] = v;
}
}
void dfs1(int u,int ft,array<int,15> P){
rep(i,0,14) if(P[i] && i != c[u]){
int s = 0;
rep(j,0,14) if(cnt[u][j] > cnt[P[i]][j]) s |= 1 << j;
++O[P[i]][s];
}
for(int v : G[u]) if(v != ft && v != son[u]) P[c[u]] = 0,dfs1(v,u,P);
if(son[u]) P[c[u]] = u,dfs1(son[u],u,P);
}
void dfs2(int u,int ft,int s){
s |= 1 << c[u],++tmp[s];
for(int v : G[u]) if(v != ft) dfs2(v,u,s);
}
void sol(int u,int ft,bool clr){
for(int v : G[u]) if(v != ft && v != son[u]) sol(v,u,1),ans[u] += ans[v];
if(son[u]) sol(son[u],u,0),ans[u] += ans[son[u]];
for(auto[x,y] : O[u]) DS::upd(x,mod - y),DS::upd(x | 1 << c[u],y);
DS::upd(1 << c[u],1),(ans[u] += DS::qry(1 << c[u])) %= mod;
for(int v : G[u]) if(v != ft && v != son[u]){
tmp.clear(),dfs2(v,u,1 << c[u]);
for(auto[x,y] : tmp) (ans[u] += DS::qry(x) * y) %= mod;
for(auto[x,y] : tmp) DS::upd(x,y);
}
if(clr){
tmp.clear(),dfs2(u,ft,0);
for(auto[x,y] : tmp) DS::upd(x,mod - y);
}
}
int main(){
n = read(),k = read(),ranges::fill(a,1);
rep(i,0,14){
ll x = i < k ? read() : 0;
rep(j,0,(1 << 15) - 1) if(j >> i & 1) (a[j] *= x) %= mod;
}
rep(i,1,n) c[i] = read() - 1;
rep(i,1,n - 1){
int u = read(),v = read();
G[u].push_back(v),G[v].push_back(u);
}
dfs0(1,0),dfs1(1,0,array<int,15>()),sol(1,0,0);
rep(i,1,n) printf("%lld ",ans[i]);
return 0;
}
::::