树的直径模板题
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<vector>
#include<cstring>
#include<stack>
#define mem(ss) memset(ss,0,sizeof(ss))
#define rep(d, s, t) for(int d=s;d<=t;d++)
#define rev(d, s, t) for(int d=s;d>=t;d--)
#define inf 0x3f3f3f3f
typedef long long ll;
typedef long double ld;
typedef double db;
typedef std::pair<int, int> pii;
typedef std::pair<ll, ll> pll;
const ll mod = 1e9 + 7;
const int N = 1e5 + 10;
#define io_opt ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }
inline ll read() {
ll x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-')f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
ll m_pow(ll x, ll n, ll m) {
ll res = 1;
while (n > 0) {
if (n & 1)
res = (res * x) % m;
x = (x * x) % m;
n >>= 1;
}
return res % m;
}
struct Edge {
int u, w;
};
int n, m;
int dis[N * 2];
bool vis[N];
vector<Edge> v[N];
void addEdge(int from, int to, int w) {
v[from].push_back(Edge{to, w});
v[to].push_back(Edge{from, w});
}
void dfs(int x) {
vis[x] = true;
for (auto e:v[x])
if (!vis[e.u]) {
dis[e.u] = dis[x] + e.w;
dfs(e.u);
}
}
int main() {
scanf("%d", &n);
m = n - 1;
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
addEdge(x, y, 1);
addEdge(y, x, 1);
}
memset(vis, false, sizeof(vis));
memset(dis, inf, sizeof(dis));
dis[1] = 0;
dfs(1);
int start, endd, maxx = -inf;
for (int i = 1; i <= n; i++)
if (dis[i] > maxx && dis[i] != inf) {
maxx = dis[i];
start = i;
}
memset(vis, false, sizeof(vis));
memset(dis, inf, sizeof(dis));
dis[start] = 0;
dfs(start);
maxx = -inf;
for (int i = 1; i <= n; i++)
if (dis[i] > maxx && dis[i] != inf) {
maxx = dis[i];
endd = i;
}
cout << maxx;
return 0;
}