AnimeshSinha1309 / algorithms-notebook

The team notebook to keep all template code and notes in.
23 stars 5 forks source link

Code for finding diameter of tree #16

Open GaurangTandon opened 4 years ago

GaurangTandon commented 4 years ago
int diameter(int node, VI &visited, VVI &adj, VI &distances) {
    VI seen = {};

    queue<int> q;
    q.push(node);
    distances[node] = 0;
    visited[node] = true;
    int farthest = node;

    while(!q.empty()) {
        auto node = q.front();
        q.pop();

        seen.push_back(node);
        for (auto neigh : adj[node]) {
            if (not visited[neigh]) {
                visited[neigh] = true;
                distances[neigh] = 1 + distances[node];
                if (distances[farthest] < distances[neigh]) farthest = neigh;
                q.push(neigh);
            }
        }
    }

    for (auto x : seen) distances[x] = INT_MIN, visited[x] = false;
    q.push(farthest);
    distances[farthest] = 0;
    visited[farthest] = true;

    while(!q.empty()) {
        auto node = q.front();
        q.pop();

        seen.push_back(node);
        for (auto neigh : adj[node]) {
            if (not visited[neigh]) {
                visited[neigh] = true;
                distances[neigh] = 1 + distances[node];
                if (distances[farthest] < distances[neigh]) farthest = neigh;
                q.push(neigh);
            }
        }
    }

    return distances[farthest];
}

Call it like this:

    VI visited(n + 1, false);
    VI distances(n + 1, 0);
    for (int i = 1; i <= n; i++) {
        if (!visited[i]) {
            diameter(i, visited, adj, distances);
        }
    }

Tested on problem 455C

Find a place to put this in our repo. Not everything needs to be in the icpc notebook, some things can be there just for easy copy-paste :P