分析:首先树形dp(dfs计算出每个点为根节点的子树的最长距离和次长距离),然后找出L=dis[u][0]+dis[u][1]最长的那个点u,然后在以u为根节点dfs,统计长度为L的条数:具体做法:把u的儿子节点为根节点的子树深搜遍历到每个叶子节点,用h[dist[v]]统计该子树中u到v的距离,然后对于遍历过的叶子节点且不再当前子树中的s[L-dist[v]]的个数加到ans中,最后ans即为所求条数:
#pragma comment(linker, "/STACK:1024000000,1024000000")#include"stdio.h"#include"string.h"#include"stdlib.h"#include"queue"#include"algorithm"#include"string.h"#include"string"#include"math.h"#include"vector"#include"stack"#include"map"#define eps 1e-4#define inf 0x3f3f3f3f#define M 100009#define PI acos(-1.0)using namespace std;struct node{ int u,v,next; __int64 w;}edge[M*2];int t,head[M],belong[M],dis[M][4],degree[M];int cnt;__int64 dist[M],a[M],L,ans;map<__int64,int>s,h;void init(){ t=0; memset(head,-1,sizeof(head));}void add(int u,int v,int w){ edge[t].u=u; edge[t].v=v; edge[t].w=w; edge[t].next=head[u]; head[u]=t++;}void dfs(int u,int f){ dis[u][0]=0; dis[u][1]=0; for(int i=head[u];~i;i=edge[i].next) { int v=edge[i].v; if(v==f)continue; dfs(v,u); if(dis[u][0]1) { dfs(i,-1); break; } } int id=1; L=dis[id][0]+dis[id][1]; for(i=2;i<=n;i++) { if(dis[id][0]+dis[id][1]