#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2000'010;
const ll mod = 1000'000'000LL;
vector<int> adj[N];
int mx = 0, a[N], in[N], out[N], rs[N], cs = 0;
map<int, int> cnt[2];
map<pair<int,int>,int> id;
set<int> s[2];
void add(int x, int p)
{
cnt[p][a[x]]++;
if(cnt[p][a[x]] == 2)
s[p].insert(-a[x]);
}
void rmv(int x, int p)
{
if(cnt[p][a[x]] == 2)
s[p].erase(-a[x]);
cnt[p][a[x]]--;
}
int getans(int x)
{
if(s[x].empty())
return 0;
return -*s[x].begin();
}
void dfs(int u, int p, int bad)
{
in[u]=cs++;
if(u == bad)
bad = -1;
if(bad != -1){
add(u, 0);
}
else
add(u, 1);
for(int v: adj[u])
{
if(v == p)
continue;
dfs(v, u, bad);
}
out[u]=cs++;
}
void swp(int u, int p)
{
// cout << u << '\n';
rmv(u, 0);
add(u, 1);
for(int v: adj[u])
{
if(v == p)
continue;
swp(v, u);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
for(int i = 0; i < n-1; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
id[{u,v}] = id[{v,u}] = i;
rs[i] = -1;
}
for(int i = 1; i <= n; i++)
{
cin >> a[i];
cnt[0][a[i]]++;
}
for(int i = 1; i <= n; i++)
{
if(cnt[0][a[i]] > 1)
mx = max(mx, a[i]);
}
if(cnt[0][mx] > 2 || mx == 0)
{
for(int i = 0; i < n-1; i++)
cout << mx << '\n';
return 0;
}
cnt[0].clear();
int u, v;
u = -1;
for(int i = 1; i <= n; i++)
{
if(a[i] == mx)
{
if(u == -1)
u = i;
else
v = i;
}
}
// cout << u << ' ' << v << '\n';
dfs(u, u, v);
int x = v, px = v;
while(x != u)
{
for(int at: adj[x])
{
if(in[at] <= in[v] && out[v] <= out[at] && px != at)
{
px = x;
x = at;
break;
}
}
rs[id[{px,x}]] = max(getans(1),getans(0));
// cout << x << ' ' << px << " " << rs[id[{px,x}]]<< " << \n";
for(int at: adj[x])
{
if(!(in[at]<= in[v] && out[v] <= out[at]))
{
swp(at, x);
// break;
}
}
rmv(x,0);
add(x,1);
}
for(int i = 0; i < n-1; i++)
{
if(rs[i] == -1)
cout << mx << '\n';
else
cout << rs[i] << '\n';
}
return 0;
}
1062B - Math | 1294C - Product of Three Numbers |
749A - Bachgold Problem | 1486B - Eastern Exhibition |
1363A - Odd Selection | 131B - Opposites Attract |
490C - Hacking Cypher | 158B - Taxi |
41C - Email address | 1373D - Maximum Sum on Even Positions |
1574C - Slay the Dragon | 621A - Wet Shark and Odd and Even |
1395A - Boboniu Likes to Color Balls | 1637C - Andrew and Stones |
1334B - Middle Class | 260C - Balls and Boxes |
1554A - Cherry | 11B - Jumping Jack |
716A - Crazy Computer | 644A - Parliament of Berland |
1657C - Bracket Sequence Deletion | 1657B - XY Sequence |
1009A - Game Shopping | 1657A - Integer Moves |
230B - T-primes | 630A - Again Twenty Five |
1234D - Distinct Characters Queries | 1183A - Nearest Interesting Number |
1009E - Intercity Travelling | 1637B - MEX and Array |