POJ 1985 樹的直徑

2022-06-01 08:09:10 字數 735 閱讀 9283

傳送門

給一顆n個點的樹,求樹的直徑(最長的一條鏈)

先隨便找乙個點u,dfs出離它最遠的點v

於是有以下情況:

只需要從v再進行一邊dfs,便可以求出直徑。

#include#include#include#includeusing namespace std;

int n, m;

int adj[50005], nxt[100005], go[100005], len[100005], ecnt;

long long dist[50005];

inline void addedge(int u, int v, int w)

inline void dfs(int u, int f)

}int main()

int v; long long ret = 0;

dist[1] = 0;

dfs(1, 0);

for(int i = 1; i <= n; i++)

if(ret < dist[i]) ret = dist[i], v = i;

dist[v] = ret = 0;

dfs(v, 0);

for(int i = 1; i <= n; i++)

if(ret < dist[i]) ret = dist[i], v = i;

printf("%lld\n", ret);

}}

poj 1985 樹的直徑

題意 求樹的直徑。樹的直徑即樹上距離最遠的兩個點之間的距離 思路 以任意點開始深搜,得到距離其最遠的點 再以求得的點開始深搜,再次搜得的最遠距離即為樹的直徑 include include define n 100005 struct edgee n 2 int first n flag n top...

poj1985 樹的直徑

題意求樹的直徑,直接貼 include include include include include using namespace std typedef struct edge edge edge 100050 開50000會wa int head 50000 e int dis 50000 ...

poj4607 樹的直徑)

題目 park visit 題意 乙個人去公園,想走k個景點,問最短的距離。思路 求出樹的直徑 最長的鏈 最長路徑 從任意點a,找到離a最遠點b。再找到離b最遠點c,bc就是最長路徑。如果k include include include include include include includ...