Cod sursa(job #3250043)

Utilizator IleaIlea Bogdan Ilea Data 19 octombrie 2024 09:41:06
Problema Diametrul unui arbore Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>

using namespace std;

string file="darb";
ifstream fin(file+".in");
ofstream fout(file+".out");

set<int> g[100001];
set<int> nod;
vector<int> b;
void bfs(int i)
{
    queue<int> q;
    q.push(i);
    b[i]=1;
    while (!q.empty()){
        i=q.front();
        q.pop();
        for (auto j:g[i]){
            if (!b[j]){
                q.push(j);
                b[j]=b[i]+1;
            }
        }
    }
}
int main()
{
    int n;
    fin>>n;
    int x, y;
    while(fin>>x>>y){
        g[x].insert(y), g[y].insert(x);
        if (g[x].size()==1)nod.insert(x);
        else nod.erase(x);
        if (g[y].size()==1)nod.insert(y);
        else nod.erase(y);
    }
    int maxim=0;
    for (auto i:nod){
        b.resize(n+1);
        bfs(i);
        for (auto j:nod){
            maxim=max(maxim, b[i]+b[j]-1);
        }
        b.clear();
    }
    fout<<maxim;
    return 0;
}