【题目链接】http://www.lydsy.com/JudgeOnline/status.php?user_id=SGG
【解题思路】暴力枚举中点,直接计数即可
【呆马】
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<iostream>
#define ll long long
const int N=5001;
using namespace std;
struct st{int to,next;} e[N<<1];
int n,cnt,x,y,i,j,k,fi[N];
ll Max,ans,num[N],dep[N],a[N],b[N];
void add(int x,int y)
{
e[++cnt].to=y; e[cnt].next=fi[x]; fi[x]=cnt;
e[++cnt].to=x; e[cnt].next=fi[y]; fi[y]=cnt;
}
void dfs(int x,int fa)
{
Max=max(Max,dep[x]);
num[dep[x]]++;
for (int i=fi[x];i;i=e[i].next)
if (e[i].to!=fa)
{
dep[e[i].to]=dep[x]+1;
dfs(e[i].to,x);
}
}
int main()
{
scanf("%d\n",&n);
for (i=1;i<n;i++)
{
scanf("%d%d\n",&x,&y);
add(x,y);
}
for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++) a[j]=b[j]=0;
for (j=fi[i];j;j=e[j].next)
{
Max=0;
dep[e[j].to]=1;
dfs(e[j].to,i);
for (k=1;k<=Max;k++)
{
ans+=b[k]*num[k];
b[k]+=a[k]*num[k];
a[k]+=num[k];
}
for (k=1;k<=Max;k++) num[k]=0;
}
}
printf("%lld",ans);
}