Cod sursa(job #2147929)

Utilizator andr3i_kaabAndrei Ciineanu andr3i_kaab Data 1 martie 2018 12:10:13
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
//#include <stdio.h>
//#include <string.h>
//#include <bits/stdc++.h>
#define M 100005

using namespace std;

ifstream f("darb.in");
ofstream g("darb.out");

vector <int> a[M];
int n, s, viz[M], d[M];
queue <int> q;

int bfs(int s)
{
    //memset(viz, -1, sizeof(viz));
    int k;
    viz[s]=1;
    d[s]=1;
    q.push(s);
    while ( !q.empty() )
    {
        k=q.front();
        q.pop();
        for (int i=0; i<a[k].size(); i++)
          if (!viz[a[k][i]])
          {
              viz[a[k][i]]=1;
              q.push(a[k][i]);
              d[a[k][i]]=d[k]+1;
          }
    }
    k=1;
    for (int i=2; i<=n; i++)
      if (d[i]>d[k])
       k=i;
    return k;
}
int main()
{
    int i, j, x, y;

    f>>n;

    for (i=1; i<=n-1; i++)
    {
        f>>x>>y;
        a[x].push_back(y);
        a[y].push_back(x);
    }

    x=bfs(1);

    for (i=1; i<=n; i++)
    {
        viz[i]=0; d[i]=0;
    }

    y=bfs(x);

    //for (i=1; i<=n; i++) cout<<d[i]<<" "; cout<<"\n";

    g<<d[y];
    /*int max1=-1;
    for (i=1; i<=n; i++)
      {
          bfs(i);
          for (j=1; j<=n; j++) if (max1<viz[j]) max1=viz[j];
      }
    g<<max1+1;*/
    return 0;
}