Files
Data-Structure/Algorithm/DP-DynamicProgramming/Tree-DP/树的直径-最远点对.cpp
2025-09-15 22:16:09 +08:00

61 lines
856 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> adj;
vector<int> dp;
void dfs(int v, int parent){
//no return;
for(auto x : adj[v]){
if(x == parent) continue;
dfs(x, v);
dp[v] = max(dp[v], dp[x] + 1);
}
}
int main(){
int n;
cin >> n;
adj.resize(n, vector<int>());
dp.resize(n, 1);
vector<bool> visited(n, false);
//ÕâÀï½Úµã´Ó0¿ªÊ¼µ½n - 1
for(int i = 0; i < n - 1; i++){
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(0, -1);
int mmax = 0;
if(adj[0].size() == 1) cout << dp[0] << endl;
else{
vector<int> tmp;
for(auto x : adj[0]){
tmp.push_back(dp[x]);
}
sort(tmp.begin(), tmp.end());
mmax = *(tmp.end() - 1) + *(tmp.end() - 2);
cout << mmax + 1<< endl;
}
return 0;
}
/*
7
0 1
0 2
1 3
1 4
2 5
2 6
8
0 1
0 2
1 3
1 4
2 5
2 6
3 7
*/