Cod sursa(job #3336134)

Utilizator voaidesrVoaides Robert voaidesr Data 24 ianuarie 2026 12:14:12
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <vector>
#include <queue>
#include <math.h>
using namespace std;

const int INF = 1e9;

ifstream cin("amici2.in");
ofstream cout("amici2.out");

pair<int, int>
diam(int s, const auto &adj, int n) {
    queue<int> q;
    vector<int> dist(n + 1, -1);

    int loc_max = 0;
    int farthest_node = s;

    dist[s] = 0;
    q.push(s);

    while (!q.empty()) {
        int c = q.front();
        q.pop();

        if (dist[c] > loc_max)  {
            loc_max = dist[c];
            farthest_node = c;
        }

        for (int n : adj[c]) {
            if (dist[n] == -1) {
                dist[n] = dist[c] + 1;
                q.push(n);
            }
        }
    }

    return {farthest_node, loc_max};
}

int main() {
    int n, m, t;
    cin >> t;

    for (int i = 0; i < t; i ++) {
        cin >> n >> m;
        vector<vector<int>> adj(n + 1, vector<int>());

        for (int j = 0; j < m; j++) {
            int u, v;
            cin >> u >> v;
            adj[u].push_back(v);
            adj[v].push_back(u);
        }

        auto first_pass = diam(1, adj, n);
        int u = first_pass.first;

        auto second_pass = diam(u, adj, n);
        int glob_max = second_pass.second;

        cout << ceil(log2(glob_max)) << "\n";
    }

    return 0;
}