Cod sursa(job #3234207)

Utilizator susanSusan Ssssss susan Data 7 iunie 2024 12:26:30
Problema Diametrul unui arbore Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
#include <vector>
using namespace std;

// Common Macros
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define all(x) (x).begin(), (x).end()

using ll = long long;

void init_io(const string &filename = "") {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);

#ifndef LOCAL
  if (!filename.empty()) {
    freopen((filename + ".in").c_str(), "r", stdin);
    freopen((filename + ".out").c_str(), "w", stdout);
  }
#endif
}

void solv() { /* Write code here*/
  int n;
  cin >> n;

  vector<vector<int>> G(n + 1);
  for (int i = 1; i < n; ++i) {
    int a, b;
    cin >> a >> b;
    G[a].pb(b);
    G[b].pb(a);
  }

  queue<int> Q;
  vector<bool> vis(n + 1);
  Q.push(1);
  int last = 0;
  vis[1] = true;

  while (!Q.empty()) {
    last = Q.front();
    Q.pop();

    for (auto &j : G[last]) {
      if (!vis[j]) {
        vis[j] = true;
        Q.push(j);
      }
    }
  }

  auto dfs = [&](auto &&dfs, int i, int j) -> int {
    int maxim = 0;

    for (auto &it : G[i]) {
      if (it != j) {
        maxim = max(dfs(dfs, it, i), maxim);
      }
    }

    return maxim + 1;
  };

  cout << dfs(dfs, last, -1) << '\n';
}

int main() {
  init_io();

  int t = 1;
  // cin >> t;

  while (t--)
    solv();
  return 0;
}