Cod sursa(job #2838519)

Utilizator 100pCiornei Stefan 100p Data 23 ianuarie 2022 22:02:17
Problema Diametrul unui arbore Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <bits/stdc++.h>
#define ull unsigned long long
#define FILES freopen("darb.in","r",stdin);\
              freopen("darb.out","w",stdout);
#define CMAX 1000000
#define fastio std::ios_base::sync_with_stdio(NULL),cin.tie(NULL),cout.tie(NULL);
#define mp make_pair
#define INF 999999999999999
#define mod 1000000007
#define ll long long
#define MAX 100000
#define SMAX 500000
#define pb push_back
#define add emplace_back
#define void inline void
using namespace std;
int n,fr[MAX+5],ans,z;
bool ok[MAX+5];
pair<int,int> dp[MAX+5];
vector<int> v[MAX+5];
void GetFr(int x)
{
    ok[x] = 1;
    for(auto i : v[x])
    {
        if(!ok[i])
        {
            GetFr(i);
            fr[x]++;
        }
    }
}
void dfs(int x,int y,int dist)
{
    fr[x] = 1;
    if(x == z)
    {
        ans += dist;
        return;
    }
    for(auto i : v[x])
    {
        if(!fr[i])
            dfs(i,y,dist+1);
    }
}
int main()
{
    fastio
    FILES
    cin >> n;
    for(int i = 1;i < n; ++i)
    {
        int a,b;
        cin >> a >> b;
        v[a].add(b),v[b].add(a);
    }
    GetFr(1);
    queue<int> q;
    for(int i = 1;i <= n; ++i)
        if(!fr[i]) q.push(i),dp[i].first = i;
    while(!q.empty())
    {
        int x = q.front();
        if(dp[x].first || dp[x].second) z = x;
        for(auto i : v[x])
        {
            fr[i]--;
            if(fr[i] >= 0) dp[i].second = dp[i].first,dp[i].first = dp[x].first;
            if(!fr[i]) q.push(i);
        }
        q.pop();
    }
    memset(fr,false,sizeof(fr));
    dfs(dp[z].first,z,0);
    memset(fr,false,sizeof(fr));
    if(dp[z].second)
    dfs(dp[z].second,z,0);
    cout << ans + 1;
}