http://poj.org/problem?id=2631
树的直径裸题
dfs/bfs均可
/* dfs */ #include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <cstring> #include <string> using namespace std; const int N = 1e5 + 10; #define yxy getchar() int now = 1, point, Max_dis; int dis[N], head[N]; bool vis[N]; struct Node {int v, w, nxt;} G[N << 1]; inline void add(int u, int v, int w){ G[now].v = v; G[now].w = w; G[now].nxt = head[u]; head[u] = now ++; } void dfs(int u, int dist){ for(int i = head[u]; ~ i; i = G[i].nxt){ int v = G[i].v; if(!vis[v]){ dis[v] = dist + G[i].w; vis[v] = 1; if(dis[v] > Max_dis){ Max_dis = dis[v]; point = v; } dfs(v, dis[v]); } } } int main() { memset(head, -1, sizeof(head)); int u_, v_, w_; while(scanf("%d%d%d", &u_, &v_, &w_) == 3){ add(u_, v_, w_); add(v_, u_, w_); } vis[1] = 1; dfs(1, 0); Max_dis = 0; memset(vis, 0, sizeof(vis)); vis[point] = 1; dfs(point, 0); cout << Max_dis; return 0; }
/* bfs */ #include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <cstring> #include <string> #include <queue> using namespace std; const int N = 1e5 + 10; #define yxy getchar() int now = 1, point, Max_dis; int dis[N], head[N]; bool vis[N]; struct Node {int v, w, nxt;} G[N << 1]; queue <int> Q; inline void add(int u, int v, int w){ G[now].v = v; G[now].w = w; G[now].nxt = head[u]; head[u] = now ++; } void bfs(int S){ Q.push(S); vis[S] = 1; while(!Q.empty()){ int topp = Q.front(); Q.pop(); for(int i = head[topp]; ~ i; i = G[i].nxt){ int v = G[i].v; if(!vis[v]){ vis[v] = 1; dis[v] = dis[topp] + G[i].w; Q.push(v); if(dis[v] > Max_dis){ Max_dis = dis[v]; point = v; } } } } } int main() { memset(head, -1, sizeof(head)); int u_, v_, w_; while(scanf("%d%d%d", &u_, &v_, &w_) == 3){ add(u_, v_, w_); add(v_, u_, w_); } bfs(1); Max_dis = 0; memset(vis, 0, sizeof(vis)); memset(dis, 0, sizeof(dis)); bfs(point); cout << Max_dis; return 0; }