Pagini recente » Cod sursa (job #1221874) | Cod sursa (job #1946175) | Cod sursa (job #2470201) | Cod sursa (job #2024068) | Cod sursa (job #2799196)
#include <iostream>
#include <vector>
#include <utility>
#include <fstream>
using namespace std;
ifstream f("darb.in");
ofstream g("darb.out");
int n;
struct node {
int value;
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;
//vector<int> children (nodes[current_node].adjacentNodes.begin(), nodes[current_node].adjacentNodes.end());
for (auto child: nodes[current_node].adjacentNodes) {
if (nodes[child].visited == false) {
getLongestDiameter(child, distance + 1, furthestLeaf);
}
}
/*for (int i = 0; i < children.size(); ++i) {
int child = nodes[children[i]].value;
}*/
}
int main() {
f >> n;
for (int i = 1; i < n; ++i) {
int x, y;
f >> x >> y;
nodes[x].value = x;
nodes[y].value = 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;
}