Pagini recente » Cod sursa (job #522067) | Cod sursa (job #1553948) | Cod sursa (job #941570) | Cod sursa (job #2574235) | Cod sursa (job #1766025)
#include <fstream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
ifstream fin("dosare.in");
ofstream fout("dosare.out");
const int dim = 16005;
vector<int> g[dim];
int countAccess[dim], dp[dim];
long long DFS(int node) {
vector< pair<long long, int> > countSons;
dp[node] = countAccess[node];
for (auto adj : g[node])
countSons.push_back({DFS(adj), adj}), dp[node] += dp[adj];
long long ret = countAccess[node];
sort(countSons.begin(), countSons.end());
reverse(countSons.begin(), countSons.end());
for (size_t i = 0; i < countSons.size(); ++i) {
ret += countSons[i].first + 1LL * dp[countSons[i].second] * (1 + i);
}
return ret;
}
int main() {
int n; fin >> n;
for (int i = 2; i <= n; ++i) {
int x; fin >> x;
g[x].push_back(i);
}
for (int i = 1; i <= n; ++i)
fin >> countAccess[i];
fout << DFS(1) << '\n';
return 0;
}
//Trust me, I'm the Doctor!