[CF1494D] Dogeforces - 分治,LCA
Description
有一棵树,满足每个非叶子结点至少有两个儿子。每个点有权值,满足父亲的权值严格大于儿子的权值。已知这棵树有 (n) 个叶子,并给出这 (n) 个叶子两两之间 ( ext{lca}) 的权值。求出这棵树的结点数,根,形态,以及每个点的权值。
Solution
一种思路是从下往上,排序后用并查集,类似哈夫曼树的构造
一种思路是从上往下,维护当前叶子集合,每次找到一个根,然后将叶子拆成若干份(各个子树),递归处理
怎么找根?任选一个叶子,和他的 LCA 权值最大的那个就是值就是根的权值
怎么划分?LCA 不是根的就是本子树。每次挑一个没划分过的,把 LCA 不是根的找出来
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1005;
int n;
int a[N][N];
// Ans
int ind;
int val[N], fa[N];
// Divide the leaves into subtrees,
// return the id of root
int divide(vector<int> leaves)
{
// Boundary
if (leaves.size() == 1)
{
val[leaves[0]] = a[leaves[0]][leaves[0]];
return leaves[0];
}
// Find root id
int max_val = 0, max_id = -1;
for (auto i : leaves)
{
if (a[i][leaves[0]] > max_val)
{
max_val = a[i][leaves[0]];
max_id = i;
}
}
int root = ++ind;
val[root] = max_val;
// Divide into subtrees and solve
vector<int> vis(leaves.size());
for (int i = 0; i < leaves.size(); i++)
{
if (vis[i])
continue;
// Build a new subtree
vector<int> subtree_leaves;
for (int j = i; j < leaves.size(); j++)
{
if (a[leaves[i]][leaves[j]] < max_val)
{
// Find new leaf in this subtree
subtree_leaves.push_back(leaves[j]);
vis[j] = 1;
}
}
int subtree_root = divide(subtree_leaves);
fa[subtree_root] = root;
}
return root;
}
signed main()
{
ios::sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> a[i][j];
}
}
ind = n;
vector<int> vec;
for (int i = 1; i <= n; i++)
vec.push_back(i);
int root = divide(vec);
cout << ind << endl;
for (int i = 1; i <= ind; i++)
cout << val[i] << " ";
cout << endl;
cout << root << endl;
for (int i = 1; i <= ind; i++)
if (fa[i])
cout << i << " " << fa[i] << endl;
}