题解:UVA115 Climbing Trees
LCA 模板题,但是 UVA 特色超长题面 + 大模拟。
科技:DFS 序求 LCA,@Alex_Wei 首先(?)在洛谷发布。
但是初看可能没那么容易懂(很长一段时间内我都只会复读那段代码根本不懂为啥)所以按我的理解方法记录一下吧。
Solution
首先对整棵树 DFS 一遍,记
:::info[什么是 DFS 序]
在 DFS 一颗树的过程中,设置一个计数器,每访问一个节点就将计数器加
| 可参考代码第 |
|---|
对于询问
否则,设
先给出结论:
现在来证明这个结论。
情形一,
那么
否则即为情形二。
这时考察节点
Implementation
上面提到了查询一个区间中 DFS 序最小的节点的功能,可以用 ST 表实现。
对于本题,注意数据中存在一子多父的情况。此时应取最后的一个作为实际的父节点。
查询时先用并查集判断是否有关系,再根据题意模拟即可。
Code
static 的作用可以理解为设置一个只能在函数内部访问的全局变量,其只会被零初始化一次,因此可以用作计数器。更多见 cppreference。
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#define MAXN 303
#define LOGN 9
using namespace std;
struct
{
int to, nxt;
} edges[MAXN];
map<string, int> idchp;
int n, fa[MAXN], head[MAXN], dfn[MAXN], st[LOGN][MAXN], dep[MAXN];
inline int getidof(const string &s)
{
int &id = idchp[s];
if (!id)
id = ++n;
return id;
}
inline void add_edge(const int &from, const int &to)
{
static int cnt;
edges[++cnt] = {to, head[from]}, head[from] = cnt;
}
int getfa(const int &x)
{
return !fa[x] ? x : fa[x] = getfa(fa[x]);
}
void dfs(const int &u)
{
static int ts;
dfn[u] = ++ts, dep[u] = dep[fa[u]] + 1, st[0][ts] = fa[u];
for (int i = head[u]; i; i = edges[i].nxt)
dfs(edges[i].to);
}
inline int calc(const int &x, const int &y)
{
return dfn[x] < dfn[y] ? x : y;
}
inline int LCA(int x, int y)
{
if (x == y)
return x;
x = dfn[x], y = dfn[y];
if (x > y)
swap(x, y);
int lg = __lg(y - x);
return calc(st[lg][x + 1], st[lg][y - (1 << lg) + 1]);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
string ustr, fstr;
while (cin >> ustr >> fstr && ustr != "no.child")
fa[getidof(ustr)] = getidof(fstr);
for (int i = 1; i <= n; ++i)
if (fa[i])
add_edge(fa[i], i);
for (int i = 1; i <= n; ++i)
if (!fa[i])
dfs(i);
for (int i = 1; (1 << i) <= n; ++i)
for (int j = 1; j <= n - (1 << i) + 1; ++j)
st[i][j] = calc(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);
int u, v;
while (cin >> ustr >> fstr)
{
u = getidof(ustr), v = getidof(fstr);
if (getfa(u) != getfa(v))
{
cout << "no relation\n";
continue;
}
int lca = LCA(u, v);
if (lca == u)
{
int g = dep[v] - dep[u];
if (g == 1)
cout << "parent\n";
else if (g == 2)
cout << "grand parent\n";
else
{
for (int kk = 0; kk < g - 2; ++kk)
cout << "great ";
cout << "grand parent\n";
}
}
else if (lca == v)
{
int g = dep[u] - dep[v];
if (g == 1)
cout << "child\n";
else if (g == 2)
cout << "grand child\n";
else
{
for (int kk = 0; kk < g - 2; ++kk)
cout << "great ";
cout << "grand child\n";
}
}
else
{
int du = dep[u] - dep[lca];
int dv = dep[v] - dep[lca];
if (du == 1 && dv == 1)
cout << "sibling\n";
else
{
int m = min(du, dv) - 1; // cousin number
int removed = abs(du - dv);
if (removed == 0)
cout << m << " cousin\n";
else
cout << m << " cousin removed " << removed << "\n";
}
}
}
return 0;
}