Pagini recente » Cod sursa (job #2776577) | Cod sursa (job #2410452) | Cod sursa (job #701177) | Cod sursa (job #2700750) | Cod sursa (job #3127000)
#include <bits/stdc++.h>
using namespace std;
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
static constexpr int NMAX = (int)1e5 + 5;
int n;
vector<int> adj[NMAX];
void read_input() {
ifstream fin("darb.in");
fin >> n;
int x, y;
while (fin >> x >> y) {
adj[x].push_back(y);
adj[y].push_back(x);
}
fin.close();
}
vector<int> get_result() {
vector<int> d1(n + 1, -1);
vector<int> d2(n + 1, -1);
vector<int> visited(n + 1);
int source = 1;
d1[source] = 1;
visited[source] = 1;
queue<int> q;
q.push(source);
while(!q.empty()) {
int node = q.front();
q.pop();
for(auto neigh : adj[node]) {
if(visited[neigh] == 0) {
q.push(neigh);
d1[neigh] = d1[node] + 1;
visited[neigh] = 1;
}
}
}
int maxi = -1;
int max_leaf;
for(int i = 1; i <= n; i++) {
if (d1[i] > maxi) {
maxi = d1[i];
max_leaf = i;
}
visited[i] = 0;
}
source = max_leaf;
d2[source] = 1;
visited[source] = 1;
q.push(source);
while(!q.empty()) {
int node = q.front();
q.pop();
for(auto neigh : adj[node]) {
if(visited[neigh] == 0) {
q.push(neigh);
d2[neigh] = d2[node] + 1;
visited[neigh] = 1;
}
}
}
return d2;
}
void print_output(const vector<int>& d) {
ofstream fout("darb.out");
int maxi = -1;
for (int node = 1; node <= n; node++) {
if (maxi < d[node]) {
maxi = d[node];
}
}
fout << maxi;
fout.close();
}
};
int main() {
auto* task = new (nothrow) Task();
if (!task) {
cerr << "new failed: WTF are you doing? Throw your PC!\n";
return -1;
}
task->solve();
delete task;
return 0;
}