LCA简单基础入门题。赤裸裸的求LCA的题,不过输入比较麻烦。题意:其实看图加样例就能懂了,不多说了,最后输出每个节点成为括号内节点LCA的节点id和次数,次数为0就不输出了。
我的解题思路:用Tarjan的离线算法最后把答案哈希输出就ok了,关于此算法的原理等见请看上一个解题报告。
我的解题代码:离线求LCA算法
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
#define N 1000
bool root[N]; //判断是否根节点
bool vis[N];
int father[N]; //幷查集使用
int lca[N]; //LCA
int ans[N];
vector <int> e[N]; //存储子节点
vector <int> q[N]; //存储询问
int n, qn;
void InitRead();
int Find(int x);
void DataProcess(int x);
int main()
{
while (~scanf("%d", &n))
{
InitRead();
for (int i=1; i<=n; ++i)
{
if (root[i])
{
DataProcess(i);
break;
}
}
for (int i=1; i<=n; ++i)
{
if (ans[i] != 0)
{
printf("%d:%d\n", i, ans[i]);
}
}
}
return 0;
}
void InitRead()
{
for (int i=0; i<=n; ++i)
{
root[i] = true;
vis[i] = false;
father[i] = i;
ans[i] = lca[i] = 0;
e[i].clear();
q[i].clear();
}
int a, b, c;
for (int i=0; i<n; ++i)
{
scanf("%d:(%d)", &a, &b);
while (b--)
{
scanf("%d", &c);
e[a].push_back(c);
root[c] = false;
}
}
scanf("%d", &qn);
while (qn--)
{
scanf(" (%d %d)", &a, &b);
q[a].push_back(b);
q[b].push_back(a);
}
return;
}
int Find(int x)
{
int z, y = x;
while (y != father[y]) y = father[y];
while (x != father[x])
{
z = father[x];
father[x] = y;
x = z;
}
return y;
}
void DataProcess(int x)
{
lca[x] = x;
int size = e[x].size();
for (int i=0; i<size; ++i)
{
DataProcess(e[x][i]);
father[e[x][i]] = x;
}
vis[x] = true;
size = q[x].size();
for (int i=0; i<size; ++i)
{
if (vis[q[x][i]]) ans[lca[Find(q[x][i])]]++; //把答案哈希
}
return;
}