Cod sursa(job #3228037)

Utilizator matei.buzdeaBuzdea Matei matei.buzdea Data 4 mai 2024 22:27:47
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>

using namespace std;

class Task {
public:
    void solve() {
        read_input();
        print_output(darb(1));
    }

private:
    static const int NMAX = (int)1e5 + 5;
    const int INF = 1e9;

    int n;
    vector<int> adj[NMAX];

    void read_input() {
        ifstream fin("darb.in");
        fin >> n;
        for (int i = 1, x, y; i <= n - 1; i++) {
            fin >> x >> y;
            adj[x].push_back(y);
            adj[y].push_back(x);
        }
        fin.close();
    }

    int darb(int node) {
        int max_depth = 0, max_node = 0;
        vector<int> visited(n + 1, 0);
        dfs(node, visited, 0, max_depth, max_node);

        max_depth = 0;
        visited.assign(n + 1, 0);
        dfs(max_node, visited, 0, max_depth, max_node);

        return max_depth + 1;
    }

    void dfs(int node, vector<int> &visited, int depth, int &max_depth, int &max_node) {
        visited[node] = 1;
        if (depth > max_depth) {
            max_depth = depth;
            max_node = node;
        }

        for (auto &neighbor : adj[node]) {
            if (!visited[neighbor]) {
                dfs(neighbor, visited, depth + 1, max_depth, max_node);
            }
        }
    }

    void print_output(int depth) {
        ofstream fout("darb.out");
        fout << depth;
        fout.close();
    }
};

int main() {
    auto* task = new (nothrow) Task();
    if (!task) {
        cerr << "Error\n";
        return -1;
    }
    task->solve();
    delete task;
    return 0;
}