树的问题(二)
https://iai.sh.cn/problem/608
#include<stdio.h> #include<iostream> #include<cmath> #include<vector> #include<map> #include<algorithm> using namespace std; const int N = 1e6+10; typedef long long lld; vector<vector<int>> links; int per[N]; int l=0; int w[N]; void dfs(int f, int x) { per[l++]=x; for(auto n : links[x]) { if(n==f) continue; dfs(x, n); per[l++]=x; } } void solve() { int n, d; cin>>n>>d; links.assign(n, vector<int>()); for(int i=0;i<n;i++) { cin>>w[i]; } for(int i=1;i<n;i++) { int a,b; cin>>a>>b; a--,b--; links[a].push_back(b); links[b].push_back(a); } vector<vector<int>> dp(2, vector<int>(n,0)); int pre = 0; for(int i=0;i<n;i++) { dp[pre][i] = w[i]; } for(int c=0;c<d;c++) { int now = pre^1; for(int i=0;i<n;i++) { dp[now][i] = dp[pre][i]; for (auto n : links[i]) { dp[now][i] = max(dp[now][i], dp[pre][n]); } } pre^=1; } for(int i=0;i<n;i++) { if(i)cout<<" "; cout<<dp[pre][i]; } cout<<endl; } int main() { solve(); return 0; } /* 8 3 1 2 3 4 5 6 7 8 1 2 1 3 1 4 2 5 2 6 3 7 4 8 8 7 8 8 6 7 8 8 6 2 3 5 2 7 1 6 1 2 3 1 4 3 3 5 5 6 */