版权声明:Andy https://blog.csdn.net/Alibaba_lhl/article/details/81427767
Source::Click here
Sample Input
5 1 6
1 4 5
6 3 9
2 6 8
6 1 7
Sample Output
22
这篇博客的证明讲解听清楚的,值得收藏!Click here
求树的直径的方法
题解
下面的模板代码中用到了pair,之前没用过,第一次见,觉得用来存权值比较方便。通过别人的博客再了解一下(Click here)。
AC Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <functional>
#include <algorithm>
#define _USE_MATH_DEFINES
using namespace std;
typedef long long ll;
const int maxn =100020;
int dis[maxn],ans;
bool vis[maxn];
vector <pair <int,int> > V[maxn]; //pair<int,int>主要的作用是将两个数据组合成一个数据,两个数据可以是同一类型或者不同类型。
int bfs(int x)
{
memset(dis,0,sizeof(dis)); //清空距离数组
memset(vis,0,sizeof(vis));//标记该节点是否被访问过
queue<int>Q;//存放节点的队列
Q.push (x);
vis[x]=1;
int point = 0;
while(!Q.empty())
{
int F=Q.front();
Q.pop();
if(dis[F]>ans)//如果当前节点的dis大于ans,更新ans,point
{
ans = dis [F];
point = F;
}
pair<int,int>t;
for(int i=0; i<V[F].size(); i++)//对与F点相连的所有边进行遍历,找出与其最远的一个
{
t=V[F][i];
if(vis[t.first] == 0)
{
vis[t.first] = 1;
dis[t.first] = dis[F]+t. second ;
Q.push(t.first);
}
}
}
return point ;
}
int main()
{
int x, y, z;
while(cin>>x>>y>>z)
{
V[x].push_back(make_pair(y,z));//存图(无向图)(x->y && y->x)(权值为z)
V[y].push_back(make_pair(x,z));
}
ans = 0;
int point = bfs (1);
ans = 0;
bfs(point);
cout<< ans << endl ;
return 0;
}