原题链接:https://codeforces.ml/contest/1494/problem/D
题意
给一个n*n的矩阵,每个位置值代表i和j的最近祖先的权值,树上父节点权值严格大于子节点,最后请你构造出整棵树。
分析
因为父节点严格大于子节点权值,因此我们可以按照权值顺序来考虑,权值越小也就是越接近叶子,所以我们从叶子开始考虑。
同时我们为了构造出树,必须要记住所有相连的边。我们从下往上开始连,一开始是一个森林,所以我们用并查集维护这个节点目前的根节点是什么,然后合并森林的时候就是根节点之间互相连边的过程。
Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 2e5 + 100, M = 5e5 + 5, INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
int fa[N], val[N], cnt, Edge[N];
vector<pair<int, PII>> ve;
int find(int x) {return x == fa[x] ? x : fa[x] = find(fa[x]);}
void solve() {
int n; cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
int x; cin >> x;
if (i == j) val[++cnt] = x, fa[cnt] = cnt;
else if (i < j) {
ve.push_back({x, {i, j}});
}
}
}
sort(ve.begin(), ve.end());
for (auto it : ve) {
int value = it.first, x = it.second.first, y = it.second.second;
int fx = find(x), fy = find(y);
if (fx != fy) {
if (value == val[fx]) fa[fy] = fx, Edge[fy] = fx;
else if (value == val[fy]) fa[fx] = fy, Edge[fx] = fy;
else {
fa[fx] = fa[fy] = Edge[fx] = Edge[fy] = ++cnt;
val[cnt] = value; fa[cnt] = cnt;
}
}
}
cout << cnt << endl;
for (int i = 1; i <= cnt; i++) cout << val[i] << " ";
cout << endl;
cout << cnt << endl;
for (int i = 1; i <= cnt-1; i++) cout << i << " " << Edge[i] << endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifdef ACM_LOCAL
freopen("input", "r", stdin);
freopen("output", "w", stdout);
#endif
solve();
}