分两种情况。三点两两lca相同:在三点的lca处对其统计即可,显然其离lca距离应相同;某点在另两点lca的子树外部:对每个点统计出与其距离x的点有多少个即可。
可以长链剖分做到线性,当然不会。
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define N 5010 int read() { int x=0,f=1;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } char getc(){char c=getchar();while ((c<'A'||c>'Z')&&(c<'a'||c>'z')) c=getchar();return c;} int gcd(int n,int m){return m==0?n:gcd(m,n%m);} int n,p[N],t,deep[N]; ll ans,f[N]; short cnt[N][N],d[N][N]; struct data{int to,nxt; }edge[N<<1]; void addedge(int x,int y){t++;edge[t].to=y,edge[t].nxt=p[x],p[x]=t;} void dfs(int k,int from) { for (int i=p[k];i;i=edge[i].nxt) if (edge[i].to!=from) dfs(edge[i].to,k); memset(f,0,sizeof(f));cnt[k][deep[k]]++; for (int i=p[k];i;i=edge[i].nxt) if (edge[i].to!=from) { for (int j=deep[edge[i].to];j<=n;j++) ans+=cnt[edge[i].to][j]*f[j], f[j]+=cnt[edge[i].to][j]*cnt[k][j], cnt[k][j]+=cnt[edge[i].to][j]; } memset(f,0,sizeof(f)); for (int i=p[k];i;i=edge[i].nxt) if (edge[i].to!=from) { for (int j=deep[edge[i].to];j<=n;j++) ans+=cnt[edge[i].to][j]*f[j]*(d[k][j-deep[k]]-cnt[k][j]), f[j]+=cnt[edge[i].to][j]; } } void dfs2(int k,int from,int root) { d[root][deep[k]]++; for (int i=p[k];i;i=edge[i].nxt) if (edge[i].to!=from) { deep[edge[i].to]=deep[k]+1; dfs2(edge[i].to,k,root); } } int main() { #ifndef ONLINE_JUDGE freopen("a.in","r",stdin); freopen("a.out","w",stdout); const char LL[]="%I64d "; #else const char LL[]="%lld "; #endif n=read(); for (int i=1;i<n;i++) { int x=read(),y=read(); addedge(x,y),addedge(y,x); } for (int i=n;i>=1;i--) deep[i]=0,dfs2(i,i,i); dfs(1,1); cout<<ans; return 0; }