Pagini recente » Cod sursa (job #955324) | Cod sursa (job #546450) | Cod sursa (job #3336965) | Cod sursa (job #1017873) | Cod sursa (job #2799197)
#include <iostream>
#include <vector>
#include <utility>
#include <fstream>
using namespace std;
ifstream f("darb.in");
ofstream g("darb.out");
int n;
struct node {
bool visited = false;
vector<int> adjacentNodes; // there will be stored maximum 3 nodes (2 children, 1 parent)
} nodes[100001];
void getLongestDiameter(int current_node, int distance, pair<int, int> &furthestLeaf) {
if (distance > furthestLeaf.second) { // update the furthest node
furthestLeaf.first = current_node;
furthestLeaf.second = distance;
}
nodes[current_node].visited = true;
for (auto child: nodes[current_node].adjacentNodes) {
if (nodes[child].visited == false) {
getLongestDiameter(child, distance + 1, furthestLeaf);
}
}
}
int main() {
f >> n;
for (int i = 1; i < n; ++i) {
int x, y;
f >> x >> y;
nodes[x].adjacentNodes.push_back(y);
nodes[y].adjacentNodes.push_back(x);
}
pair<int, int> furthestLeaf (1, 1); // first element denotes the node, the second element denotes the distance
getLongestDiameter(furthestLeaf.first, 1, furthestLeaf);
for (int i = 1; i <= n; ++i) { // clean the visited status variable for each node
nodes[i].visited = false;
}
getLongestDiameter(furthestLeaf.first, 1, furthestLeaf);
g << furthestLeaf.second << "\n";
return 0;
}