两遍dfs或bfs
bfs:
#include <queue>//树的直径bfs
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1e5+7;
const int maxm = 1e5+7;
struct node{
int id;
int d;
int Next;
}side[maxm];
int head[maxn];
int cnt = 0;
void Init()
{
memset(head,-1,sizeof(head));
cnt = 0;
}
void add(int x,int y,int d)
{
side[cnt].id = y;
side[cnt].d = d;
side[cnt].Next = head[x];
head[x] = cnt++;
}
//关键的结构体,储存点和累积的权值
struct Node{
int id;
int d;
};
int mk[maxn];
//注意&d
int bfs(int x,int &d)
{
memset(mk,0,sizeof(mk));
queue <Node> q;
Node tmp;
tmp.id = x;
tmp.d = 0;
q.push(tmp);
mk[x] = 1;
int mx = 0,ans = x;
while(q.size())
{
tmp = q.front();
q.pop();
for(int i = head[tmp.id]; i!=-1; i=side[i].Next)
{
if(!mk[side[i].id]){
mk[side[i].id] = 1;
Node nd;
nd.id = side[i].id;
nd.d = tmp.d+side[i].d;
if(nd.d > mx)
{
mx = nd.d;
ans = y;
}
q.push(nd);
}
}
}
d = mx;
return ans;//返回距离x最远的点
}
int main()
{
Init();
int x,y,w;
while(scanf("%d%d%d",&x,&y,&w)!=EOF)
{
add(x,y,w);
add(y,x,w);
}
int d;
int u = bfs(1,d);
int v = bfs(u,d);
printf("%d\n",d);
return 0;
}
dfs版:
#include<iostream>//树的直径dfs
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAX 100000
using namespace std;
struct node{
int id;
int d;
int next;
}side[400000];
int head[100000];
int vis[100000];
int n,m,f,ans;
int cnt=0;
void add(int x,int y,int w)
{
side[cnt].id=y;
side[cnt].d=w;
side[cnt].next=head[x];
head[x]=cnt++;
}
void Init()
{
memset(head,-1,sizeof(head));
cnt=0;
}
void dfs(int x,int num)
{
vis[x]=1;//走过就标记
if(num>ans)
{
ans=num;
f=x;
}
for(int i=head[x];i!=-1;i=side[i].next)//延伸x所能到达的点
{
if(!vis[side[i].id])
dfs(side[i].id,num+side[i].d);
}
}
int main()
{
Init();
scanf("%d",&n);
m=n-1;
while(m--)
{
int x,y,w;
scanf("%d%d",&x,&y);
add(x,y,1);
add(y,x,1);
}
ans=0;
memset(vis,0,sizeof(vis));
dfs(1,0);
memset(vis,0,sizeof(vis));
dfs(f,0);
printf("%d\n",ans);
return 0;
}