topic:
input Output:
Conclusion on the diameter of the tree:
Principle seeking tree diameter: beginning at any point x, do first BFS (DFS), find the furthest point y, then y this point, once BFS (DFS), find the furthest point z, z to y is in the tree diameter, denoted D (Z, Y) .
Code:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
const int MAXN = 50005; //刚开始开的数据太小 导致最后一个点过不去
int dis[MAXN],head[MAXN],vis[MAXN];
int n,ind,ans,sourDot;
queue<int> q;
struct node
{
int y,cost,next;
}edge[MAXN*2];
void Add(int x,int y,int len)
{
edge[++ind].y = y;
edge[ind].cost = len;
edge[ind].next = head[x];
head[x] = ind;
}
void BFS(int x)
{
vis[x] = true;
dis[x] = 0;
q.push(x);
while(!q.empty())
{
int tmpNo = q.front();
q.pop();
for(int i=head[tmpNo];i;i=edge[i].next)
{
if(!vis[edge[i].y])
{
vis[edge[i].y] = true;
dis[edge[i].y] = dis[tmpNo] + edge[i].cost;
if(dis[edge[i].y] > ans)
{
ans = dis[edge[i].y];
sourDot = edge[i].y;
}
q.push(edge[i].y);
}
}
}
}
int main()
{
scanf("%d",&n);
int x,y,len;
for(int i=1;i<=n-1;++i)
{
scanf("%d%d%d",&x,&y,&len);
Add(x,y,len);
Add(y,x,len);
}
BFS(1);
memset(vis,false,sizeof(vis));
memset(dis,0,sizeof(dis));
ans = 0;
int tmp = sourDot;
BFS(tmp);
int res;
if(ans%2)
res = (ans+1)*(ans/2) + (ans+1)/2 + ans*10;
else
res = (ans+1)*(ans/2) + ans*10;
printf("%d\n",res);
return 0;
}