题目大意
给定一棵n个点的树,求树上两两距离相等的点三元组个数。
题目分析
考虑dp。
令fx,i表示x为根的子树内,距离
然后在
对于一个子树y,我们有
这样我们就可以做到O(n2)的时间和空间复杂度。
怎么将时空复杂度优化呢?注意到对于节点x,设
我们不妨对这棵树长链剖分,然后将重儿子作为第一次枚举的子树,使用类似指针的思路来做到O(1)的数组位移,然后其余的子树直接暴力转移。
这样做时间复杂度是O(n)的,因为一个点x所在的子树被暴力转移当且仅当
至于空间复杂度,我们给每条长链顶端分配正比于长链长度的空间就好了,最后也是O(n)的。
一些实现细节请读者自行思考。
代码实现
#include <iostream>
#include <cstdio>
#include <cctype>
using namespace std;
typedef long long LL;
int read()
{
int x=0,f=1;
char ch=getchar();
while (!isdigit(ch)) f=ch=='-'?-1:f,ch=getchar();
while (isdigit(ch)) x=x*10+ch-'0',ch=getchar();
return x*f;
}
const int N=100005;
const int M=N<<1;
const int E=N<<1;
int last[N],hea[N],depth[N],lng[N],mxl[N],fa[N],fst[N],gst[N];
int tov[E],nxt[E];
LL f[N],g[M];
int n,tot,fcnt,gcnt;
LL ans;
void insert(int x,int y){tov[++tot]=y,nxt[tot]=last[x],last[x]=tot;}
void dfs(int x)
{
mxl[x]=lng[x]=0;
for (int i=last[x],y;i;i=nxt[i])
if ((y=tov[i])!=fa[x])
{
depth[y]=depth[fa[y]=x]+1,dfs(y);
if (mxl[x]<mxl[y]+1) mxl[x]=mxl[lng[x]=y]+1;
}
}
void dp(int x,int top)
{
if (x==top) fst[x]=fcnt,fcnt+=mxl[x]+1,gst[x]=gcnt,gcnt+=mxl[x]<<1|1;
if (lng[x]) dp(lng[x],top);
int fptr=fst[top]+depth[x]-depth[top],gptr=gst[top]+mxl[top]-depth[x]+depth[top];
++f[fptr],ans+=g[gptr];
for (int i=last[x],y;i;i=nxt[i])
if ((y=tov[i])!=fa[x]&&y!=lng[x])
{
dp(y,y);
for (int j=0;j<mxl[y];++j) ans+=f[fptr+j]*g[gst[y]+mxl[y]+j+1];
for (int j=0;j<=mxl[y]&&gptr+j+1<gst[top]+(mxl[top]<<1|1);++j) ans+=g[gptr+j+1]*f[fst[y]+j];
for (int j=0;j<=mxl[y]&&gptr+j+1<gst[top]+(mxl[top]<<1|1)&&fptr+j+1<fst[top]+mxl[top]+1;++j) g[gptr+j+1]+=f[fptr+j+1]*f[fst[y]+j];
for (int j=0;j<mxl[y];++j) g[gptr+j]+=g[gst[y]+mxl[y]+j+1];
for (int j=0;j<=mxl[y]&&fptr+j+1<fst[top]+mxl[top]+1;++j) f[fptr+j+1]+=f[fst[y]+j];
}
}
int main()
{
freopen("tree.in","r",stdin),freopen("tree.out","w",stdout);
n=read();
for (int i=1,x,y;i<n;++i) x=read(),y=read(),insert(x,y),insert(y,x);
depth[1]=1,dfs(1),fcnt=gcnt=1,dp(1,1),printf("%lld\n",ans);
fclose(stdin),fclose(stdout);
return 0;
}