bzoj 5293 树上差分 and 倍增
作者:互联网
题意:问你树上两点之间路径上 sigma(每个点深度^k);
解:
1、树上倍增时维护每个深度k次幂到根的前缀和
2、树上差分+简单容斥
#include<bits/stdc++.h>
using namespace std;
#define MAXN 300010
#define maxn 300010
#define en '\n'
#define ll long long
int MAXLOG;
const int mo=998244353;
const int INF = 1e8;
const int inf = 1e8;
int T,tot = 1;
int dep[maxn],anc[maxn][66],n,m;
int val[66];
int a[maxn][66];
template<class T>void rep(T &x){x%=mo;x+=mo;x%=mo;}
template<class T>void rd(T &x)
{
x=0;int f=0;char ch=getchar();
while(ch<'0'||ch>'9') {f|=(ch=='-');ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
x=f?-x:x;
return;
}
struct node{
int nxt,v;
}edge[maxn<<1];
int head[maxn];
void add(int u,int v){
edge[++tot].nxt=head[u];head[u]=tot;edge[tot].v=v;
}
void dfs(int x,int fa){
dep[x]=dep[fa]+1;
val[0]=1;
for(int i=1;i<=50;i++){
val[i]=((ll)val[i-1]*dep[x])%mo;
}
for(int i=1;i<=50;i++){
a[x][i]=(a[fa][i]+val[i])%mo;
}
anc[x][0]=fa;
if(!anc[x][0])anc[x][0]=1;
for(int i=1;i<MAXLOG;i++){
anc[x][i]=anc[anc[x][i-1]][i-1];
}
for(int i=head[x];i;i=edge[i].nxt){
int y=edge[i].v;
if(y==fa)continue;
dfs(y,x);
}
}
int lca(int x,int y){
if(dep[x]>dep[y])swap(x,y);
int t=dep[y]-dep[x];
for(int i=0;i<MAXLOG;i++){
if((t>>i)&1){
y=anc[y][i];
}
}
if(y==x)return x;
for(int i=MAXLOG-1;i>=0;--i){
if(anc[x][i]==anc[y][i])continue;
x=anc[x][i],y=anc[y][i];
}
return anc[x][0];
}
signed main()
{
#ifdef local
freopen("input2.txt","r",stdin);
#endif // local
cin>>n;
MAXLOG=log10(1.0*n)/log10(2)+2;
for(int i=1;i<n;i++){
int x,y;
rd(x),rd(y);
add(x,y),add(y,x);
}
dep[0]=-1;
dfs(1,0);
cin>>m;
for(int i=0;i<m;i++){
int x,y,k;
rd(x),rd(y),rd(k);
int LCA=lca(x,y);
ll tem=(ll)a[x][k]+a[y][k]-a[LCA][k]-a[anc[LCA][0]][k];
rep(tem);
cout<<tem<<en;
}
return 0;
}
标签:ch,anc,int,mo,5293,差分,maxn,define,bzoj 来源: https://blog.csdn.net/qq_40675883/article/details/100181023