Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define f first
- #define s second
- #define ll long long
- #define pb push_back
- #define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
- #define mk make_pair
- using namespace std;
- const int MAXN = 2e5 + 5;
- const ll INF = 1e18 + 7;
- vector <int> g[MAXN];
- bool was[MAXN];
- ll dp[MAXN];
- int num[MAXN], cntMa, cnt[MAXN], col[MAXN];
- map <int, int> ma[MAXN];
- void dfs(int x, int pr = -1){
- was[x] = 1;
- int mainMa = 0;
- dp[x] = 0;
- cnt[x] = 0;
- for (int i = 0; i < g[x].size(); i++){
- if (!was[g[x][i]]){
- dfs(g[x][i], x);
- if (ma[num[g[x][i]]].size() > ma[mainMa].size()){
- mainMa = num[g[x][i]];
- dp[x] = dp[g[x][i]];
- cnt[x] = cnt[g[x][i]];
- }
- }
- }
- if (mainMa == 0){
- cntMa++;
- mainMa = cntMa;
- }
- num[x] = mainMa;
- for (int i = 0; i < g[x].size(); i++){
- if (g[x][i] != pr){
- if (num[g[x][i]] != mainMa){
- for (auto [key, val] : ma[num[g[x][i]]]){
- ma[mainMa][key] += val;
- if (ma[mainMa][key] == cnt[x]){
- dp[x] += key;
- }
- else if (ma[mainMa][key] > cnt[x]){
- dp[x] = key;
- cnt[x] = ma[mainMa][key];
- }
- }
- }
- }
- }
- ma[mainMa][col[x]]++;
- if (ma[mainMa][col[x]] == cnt[x]){
- dp[x] += col[x];
- }
- else if (ma[mainMa][col[x]] > cnt[x]){
- dp[x] = col[x];
- cnt[x] = ma[mainMa][col[x]];
- }
- }
- void solve(){
- int n, p;
- cin >> n;
- for (int i = 1; i <= n; i++){
- cin >> col[i];
- }
- for (int i = 1; i < n; i++){
- int x, y;
- cin >> x >> y;
- g[x].pb(y);
- g[y].pb(x);
- }
- dfs(1);
- for (int i = 1; i <= n; i++){
- cout << dp[i] << ' ';
- }
- }
- int main() {
- IOS;
- int t = 1;
- //cin >> t;
- while (t--){
- solve();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment