CCPC网络赛—Jumping Monkey
思路:先把所有的边存下来,不连,然后按所有权值从小到大排序,重新构建一颗树。从小到大枚举所有节点,遍历当前节点的所有连边,若对面节点比当前节点大,则到不了对面,continue,若比当前节点小,则证明当前节点可以到达对面节点的连通块中所有的点,将对面连通块中权值最大的节点与自己连边,这样对面连通块所有节点深度+1,我们将深度作为答案即可输出。
难点:如何想到把深度作为答案输出
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <math.h>
#include <map>
#include <set>
#include <queue>
using namespace std;
#define endl '\n'
const int maxn = 1e5+5;
const int maxm = maxn << 1;
int head[maxn],nex[maxm],v[maxm],w[maxm],cnt,dis[maxn],vis[maxn],fa[maxn],dep[maxn];
int n,idx,val[maxn];
void add(int x,int y){
nex[++cnt] = head[x];
head[x] = cnt;
v[cnt] = y;
}
int find(int x){
return fa[x] == x ? x : (fa[x] = find(fa[x]));
}
struct node{
int val,id;
friend bool operator < (const node a,const node b){
return a.val < b.val;
}
}a[maxn];
vector<int> to[maxn];
void init(){
idx = cnt = 0;
for (int i = 1; i <= n; ++i) {
fa[i] = i;
head[i] = 0;
to[i].clear();
}
}
void bfs(int node){
memset(dep,0x3f,sizeof dep);
dep[node] = 1;
queue<int> q;
q.push(node);
while (!q.empty()){
int now = q.front();q.pop();
for (int i = head[now]; i; i = nex[i]) {
int to = v[i];
if (dep[to] > dep[now] + 1){
dep[to] = dep[now] + 1;
q.push(to);
}
}
}
}
void solve(){
cin >> n;
init();
for (int i = 1; i <= n - 1; ++i) {
int x,y;
cin >> x >> y;
to[x].push_back(y);
to[y].push_back(x);
}
for (int i = 1; i <= n; ++i) {
cin >> a[i].val;
val[i] = a[i].val;
a[i].id = i;
}
sort(a + 1,a + 1 + n);
for (int i = 1; i <= n; ++i) {
int node = a[i].id;
for(auto k : to[node]){
if (val[k] > val[node]) continue;
int fx = find(k);
fa[fx] = node;
add(fx,node);
add(node,fx);
}
}
bfs(a[n].id);
for (int i = 1; i <= n; ++i) {
cout << dep[i] << endl;
}
}
int main(){
std::ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int t;
cin >> t;
while (t--) solve();
}