Pagini recente » Cod sursa (job #1972432) | Cod sursa (job #1422792) | Cod sursa (job #2642500) | Cod sursa (job #430800) | Cod sursa (job #3146588)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cmath>
///#include <tryhardmode>
///#include <GODMODE::ON>
#pragma optimize GCC ("Ofast")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
using namespace std;
class InParser {
private:
FILE *fin;
char *buff;
int sp;
char read_ch() {
++sp;
if (sp == 4096) {
sp = 0;
fread(buff, 1, 4096, fin);
}
return buff[sp];
}
public:
InParser(const char* nume) {
fin = fopen(nume, "r");
buff = new char[4096]();
sp = 4095;
}
InParser& operator >> (int &n) {
char c;
while (!isdigit(c = read_ch()) && c != '-');
int sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
InParser& operator >> (long long &n) {
char c;
n = 0;
while (!isdigit(c = read_ch()) && c != '-');
long long sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
};
InParser fin ("dosare.in");
ofstream fout ("dosare.out");
const int NMAX=16e3+5;
vector<int>v[NMAX];
int cost[NMAX];
int dp[NMAX];
bool cmp(int x,int y)
{
return cost[x]>cost[y];
}
void dfs(int p)
{
int kon=0;
for(auto i:v[p])
{
dfs(i);
cost[p]+=cost[i];
}
dp[p]=cost[p];
sort(v[p].begin(),v[p].end(),cmp);
for(auto i:v[p])
{
dp[p]+=dp[i]+kon*cost[i];
kon++;
}
}
int main()
{
ios_base::sync_with_stdio(false);
fout.tie(NULL);
int n,i;
fin>>n;
for(i=1;i<n;i++)
{
int x;
fin>>x;
v[x].push_back(i+1);
}
for(i=1;i<=n;i++)
fin>>cost[i];
dfs(1);
fout<<dp[1];
fout.close();
return 0;
}