Cod sursa(job #1228352)

Utilizator claudiumihailClaudiu Mihail claudiumihail Data 13 septembrie 2014 21:49:14
Problema Diametrul unui arbore Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <iterator>
//#include <algorithm>

#define MAXN 100002

using namespace std;

typedef vector<vector<int>> Graph;

Graph graph;

bool visited[MAXN];

int dfs(int node)
{
    int dist = 0;

    visited[node] = true;
    for (int neighbor : graph[node])
    {
        if (visited[neighbor] == false)
        {
            dist = max(dist, dfs(neighbor));
        }
    }
    
    return dist + 1;
}

int main()
{
    int n;
    fstream fin("darb.in", fstream::in);
    fstream fout("darb.out", fstream::out);

    fin >> n;
    //cout << n << endl;
    
    graph.resize(n);

    for (int i=0; i<n-1; ++i)
    {
        int x, y;
        fin >> x >> y;
        //cout << x << " " << y << endl;
        
        graph[x-1].push_back(y-1);
        graph[y-1].push_back(x-1);
    }
    
    /*for (int i=0; i<n; ++i)
    {
        cout << i+1 << " ---> ";
        for (int node : graph[i])
        {
            cout << node+1 << " ";
        }
        cout << endl;
    }*/
    
    int maxs[2] = {};
    
    visited[0] = true;
    for (int node : graph[0])
    {
        int dist = dfs(node);
        
        if (dist >= maxs[0])
        {
            maxs[1] = maxs[0];
            maxs[0] = dist;
        }
        else if (dist > maxs[1])
        {
            maxs[1] = dist;
        }
    }
    
    fout << maxs[0] + maxs[1] + 1 << "\n";

    return 0;
}