Cod sursa(job #2240858)

Utilizator demetriad-dagpagDavid Demetriad demetriad-dagpag Data 14 septembrie 2018 11:42:56
Problema Ferma Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.54 kb
#include <bits/stdc++.h>
#define ll long long

using namespace std;

const int MAXN = (int) 2e5 + 5;

vector < pair <int, int> > g[MAXN + 1];
char type[MAXN + 1];
int cnt[MAXN + 1];

ll dp[MAXN + 1], weight[MAXN + 1];

void dfs(int nod, int par, int ch, ll dst) {
    weight[nod] = 0;
    if(type[nod] == ch) {
        weight[nod] = cnt[nod];
        dp[1] += 1LL * dst * cnt[nod];
    }
    for(auto it : g[nod]) {
        if(it.first != par) {
            dfs(it.first, nod, ch, dst + it.second);
            weight[nod] += weight[it.first];
        }
    }
}

void dfs1(int nod, int par) {
    for(auto it : g[nod]) {
        if(it.first != par) {
            dp[it.first] = dp[nod] + 1LL * (weight[1] - 2 * weight[it.first]) * it.second;
            dfs1(it.first, nod);
        }
    }
}

int main() {
    //ifstream cin("A.in");
    //ofstream cout("A.out");
    int i, n;
    ios::sync_with_stdio(false);
    cin >> n;
    for(i = 1; i <= n; i++) {
        cin >> type[i];
        type[i] -= 'a';
    }
    for(i = 1; i <= n; i++) {
        cin >> cnt[i];
    }
    for(i = 1; i < n; i++) {
        int x, y, d;
        cin >> x >> y >> d;
        g[x].push_back({y, d});
        g[y].push_back({x, d});
    }
    for(int ch = 0; ch < 26; ch++) {
        dp[1] = 0;
        dfs(1, 0, ch, 0);
        dfs1(1, 0);
        ll ans = 1e18;
        for(i = 1; i <= n; i++) {
            ans = min(ans, dp[i]);
        }
        cout << ans << " ";
    }
    //cin.close();
    //cout.close();
    return 0;
}