跳到正文

题解

2025.10.18模拟赛总结 T681599

Schakal约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年10月18日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

预估分数: 200200
实际分数: 200200

T681599 星星路

思路

n−1n-1 条道路
首都可以到达任意城市

容易观察到,给出的数据是一棵树

使字典序更大,只需从根开始每次走标识字典序最大的节点,此时 BFSBFS 会更加方便

因为需记录当前位置(深度)字典序最大的标识,所以用 DFSDFS 先跑一遍记录深度

代码

C++
#include<bits/stdc++.h>
using namespace std;
int n,deep[1000010],fa[1000010];
char c[1000010],f[1000010];//c存每个节点的标识,f存深度最大字典序标识
vector<int> e[1000010];
queue<int> q;

void dfs(int x){
    for(int i=0;i<e[x].size();i++){
        int y=e[x][i];
        deep[y]=deep[x]+1;
        dfs(y);
    }
    return;
}

void bfs(int x){
    while(!q.empty() && c[fa[x]]!=f[deep[fa[x]]]){
        q.pop();
        x=q.front();
    }//不开while会直接结束
    if(q.empty()){
        return;
    }
    f[deep[x]]=max(f[deep[x]],c[x]);
    for(int i=0;i<e[x].size();i++){
        int y=e[x][i];
        q.push(y);
    }
    q.pop();
    bfs(q.front());
    return;
}

int main(){
    freopen("road.in","r",stdin);
    freopen("road.out","w",stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>c[i];
    }
    for(int i=1;i<n;i++){
        int x,y;
        cin>>x>>y;
        e[x].push_back(y);
        fa[y]=x;
    }
    deep[1]=1;
    dfs(1);
    q.push(1);
    f[1]=c[1];
    fa[1]=1;
    bfs(1);
    int p=1;
    while(f[p]!=0){
        cout<<f[p];
        p++;
    }
    return 0;
}
原文