树的直径(树中最左边端点到最右边端点的距离)
#include<iostream>
#include<cstdio>#include<string.h>
#include<string>
#include<stack>
#include<set>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#include<sstream>
#include<queue>
#define ll __int64
#define lll unsigned long long
#define MAX 1000009
#define MAXN 2009
#define eps 1e-8
#define INF 0x7fffffff
#define mod 1000000007
#define clr(a) memset(a,0,sizeof(a))
#define clr1(a) memset(a,-1,sizeof(a))
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
using namespace std;
/*
想法: 树的直径(树中最左边端点到最右边端点的距离)
题意:求树中最长的路径
*/
struct node
{
int v;
int w;
int next;
int len;
}edge[MAX];
queue<int>Q;
int dist[MAX];
int head[MAX];
int vis[MAX];
int tot,top;
int n,m;
int point;
void init()
{
clr(vis);
clr1(head);
tot = 0;
top = 0;
}
void add_edge(int u,int v,int w)
{
edge[tot].v = v;
edge[tot].w = w;
edge[tot].len = 0;
edge[tot].next = head[u];
head[u] = tot++;
}
int bfs(int start)
{
//cout<<start<<endl;
while(!Q.empty())Q.pop();
clr(dist);
vis[start] = 1;
int ans = -INF;
Q.push(start);
while(!Q.empty())
{
int u = Q.front();Q.pop();
//cout<<u<<endl;
for(int i = head[u];i!=-1;i = edge[i].next)
{
int v = edge[i].v;
//cout<<u<<" "<<v<<endl;
if(!vis[v])
{
vis[v] = 1;
dist[v]= dist[u] + edge[i].w;
if(dist[v]>ans)
{
ans = dist[v];
point = v;
}
Q.push(v);
}
}
}
return ans;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("an.txt","r", stdin);
#endif
int u,v,w;
while(~scanf("%d%d",&n,&m))
{
init();
for(int i = 0;i<m;i++)
{
char s;
scanf("%d%d%d%c",&u,&v,&w,&s);
getchar();
add_edge(u,v,w);
add_edge(v,u,w);
}
bfs(1);
clr(vis);
//cout<<point<<endl;
printf("%d\n",bfs(point));
}
return 0;
}