Cod sursa(job #3206764)

Utilizator Theo20067Cismaru Theodor-Alexe Theo20067 Data 23 februarie 2024 22:59:03
Problema Dosare Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.9 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin ("dosare.in");
ofstream fout("dosare.out");
int n,i,p,D[16003],x;
long long F[16003],sol;
vector <int> L[16003];
void dfs_dosare(int nod)
{
    for(auto j:L[nod])
    {
        dfs_dosare(j);
        D[nod]+=D[j];
    }
    sort(L[nod].begin(),L[nod].end(),[](auto a,auto b){return D[a]>D[b];});
}
void dfs_solve(int nod,long long moves)
{
    sol+=F[nod]*moves;
    for(int j=0;j<L[nod].size();j++)
        dfs_solve(L[nod][j],j+moves+1);
}
int main()
{
    fin>>n;
    for(i=2;i<=n;i++)
    {
        fin>>p;
        L[p].push_back(i);
    }
    for(i=1;i<=n;i++)
    {
        fin>>x;
        F[i]=x;
        D[i]=x;
    }
    dfs_dosare(1);
    dfs_solve(1,1);
    fout<<sol;
    return 0;
}
/*
            1
     3      4     2
   5 6 7   8 9

1
4
2
3
3
4
5
4
5


*/