白井黑子

· · 题解

为什么现有的所有题解都这么复杂,来个简单题解。

主要参考了这篇题解,谢谢你喵。

考虑链表维护 dfs 序,这里我们采用单向链表即可。

具体地,我们让链表同时充当 vis 数组,定义如下:

从 1 到 n 遍历所有点 i,对于 i=1 令 a_1 = 1 即可,否则算法流程如下:

举个例子,样例中的树如下:

  1
 / \
4   5
   / \
  3   6
       \
        2

首先处理 1,此时 dfs 序为 [1]。

接下来处理 2,找到对应的极长链 [5,6,2],此时我们因为 f_5 = 1,将 [5,6,2] 插在 1 的后面,得到 dfs 序 [1,5,6,2]。

接下来处理 3,找到对应的极长链 [3],此时我们因为 f_3 = 5,将 [3] 插在 5 的后面,得到 dfs 序 [1,5,3,6,2]。

接下来处理 4,找到对应的极长链 [4],此时我们因为 f_4 = 1,将 [4] 插在 1 的后面,得到 dfs 序 [1,4,5,3,6,2]。

由于 5 和 6 都在 dfs 序中了,所以无需进行考虑。

这种做法的正确性是容易证明的,考虑在任意时刻,我们得到的 dfs 序都一定是当前连通块的 dfs 序,最终的 dfs 序必然是答案。

接下来是代码,提交记录。

void dfs(int n,Array &f,Array &a){
    for(int i=1;i<=n;i++){
        if(a[i]){
            continue; // 已经在 dfs 序中的节点 
        }
        a.set(i,i); // 初始化 a_i = i 
        if(i!=1){
            int pre=f[i],son=i; // 开始跳父亲,维护当前的父亲 pre 和儿子 son 
            while(true){
                int num=a[pre]; // 父亲在 dfs 序中的后继 
                if(num){ // 父亲在 dfs 序中 
                    if(pre==num){ // 父亲在 dfs 序的结尾
                        a.set(pre,son); // [...,pre] + [son,...,i]
                    }
                    else{ // 父亲不在 dfs 序的结尾,结构为 pre - num 
                        a.set(pre,son); // [...,pre] + [son,...,i]
                        a.set(i,num); // [son,...,i] + [num,...]
                    }
                    break;
                }
                else{
                    a.set(pre,son); // 当前的链要加上 pre - son 
                    son=pre; // 往上跳
                    pre=f[pre]; // 往上跳 
                }
            }
        }
    }
    int pre=1; // 答案从 1 开始跳链表统计 
    for(int i=1;i<=n;i++){
        f.set(i,pre); // 用 f 暂时存答案 
        pre=a[pre]; // 跳链表 
    }
    for(int i=1;i<=n;i++){
        a.set(i,f[i]); // 将答案存到 a 中 
    }
}

还有提交要带着 dfs.cpp 一起交,不要和某个啥子一样交你的 dfs 函数 CE 一万年,我不说是谁。

#ifndef GREAT_DFS_LIVES_FOREVER
#define GREAT_DFS_LIVES_FOREVER
class Array {
    int a[10000001];
public:
    Array();
    int operator[](int x);
    void set(int x,int k);
};
void dfs(int,Array&,Array&);
int fa(int);
#endif

// write your code here
void dfs(int n,Array &f,Array &a) {
    for (int i{1};i<=n;++i) a.set(i,i);
}

// interactor
#ifndef ONLINE_JUDGE
#include <bits/stdc++.h>
using namespace std;
int n;
void quit(const string &s) {
    cerr<<s<<endl;
    exit(0);
}
Array::Array() {
    memset(a,0,sizeof a);
}
int Array::operator[](int x) {
    if (x<0||x>n) quit("["+to_string(x)+"]: Index out of range.");
    return a[x];
}
void Array::set(int x,int k) {
    if (x<0||x>n) quit("set("+to_string(x)+","+to_string(k)+"): Index out of range.");
    if (-1>k||k>n) quit("set("+to_string(x)+","+to_string(k)+"): Value out of range.");
    a[x]=k;
}
Array f,a,fb;
int fa(int x) {
    return fb[x];
}
int main() {
    cin>>n;
    for (int i{2};i<=n;++i) {
        int x;cin>>x;
        f.set(i,x);
        fb.set(i,x);
    }
    dfs(n,f,a);
    for (int i{1};i<=n;++i) cout<<a[i]<<" ";
    return 0;
}
#endif