Pagini recente » Cod sursa (job #1224485) | Cod sursa (job #317724) | Cod sursa (job #2783585) | Cod sursa (job #878324) | Cod sursa (job #2422701)
#include <iostream>
#include <fstream>
#include <vector>
#include <limits.h>
using namespace std;
class Node{
public:vector<int> neighbors;
};
int minimum(int a, int b, int *which)
{
if (a < b)
{
*which = 1;
return a;
}
else
{
*which = 2;
return b;
}
}
int LCA(int node1, int node2, vector<int> &path, vector<int> &levels)
{
int min = INT_MAX - 1;
int ok = 0;
int node = -1;
int which;
for (int i = 0; i < path.size(); i++)
{
if (path.at(i) == node1 || path.at(i) == node2)
{
if (ok == 0)
{
ok = 1;
min = minimum(levels.at(i), min, &which);
if (which == 1)
node = path.at(i);
}
else if (ok == 1)
{
min = minimum(levels.at(i), min, &which);
if (which == 1)
node = path.at(i);
break;
}
}
if (ok == 1)
{
min = minimum(levels.at(i), min, &which);
if (which == 1)
node = path.at(i);
}
}
return node;
}
void DFS(Node graph[], int node, int level, bool visited[], vector<int> &path, vector<int> &levels)
{
visited[node] = true;
path.push_back(node);
levels.push_back(level);
for (int neighbor : graph[node].neighbors)
{
if (visited[neighbor] == false)
{
DFS(graph, neighbor, level + 1, visited, path, levels);
path.push_back(node);
levels.push_back(level);
}
}
}
int main(int argc, char const *argv[])
{
ifstream read("lca.in");
ofstream write("lca.out");
int N, M;
read >> N >> M;
Node graph[N + 1];
bool visited[N + 1];
vector<int> path;
vector<int> levels;
int father;
for (int i = 2; i <= N; i++)
{
read >> father;
graph[father].neighbors.push_back(i);
graph[i].neighbors.push_back(father);
}
DFS(graph, 1, 0,visited, path, levels);
int node1, node2;
for (int i = 0; i < M; i++)
{
read >> node1 >> node2;
write << LCA(node1, node2, path, levels) << '\n';
}
read.close();
write.close();
return 0;
}