https://vjudge.net/contest/279738#problem/K
#include<set>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
#define mod 1000000007
ll n,a[100005],ans1=0,ans2=0;
int f[100005];
set<ll>s[100005];set<ll>::iterator it;
int main(void)
{
int T;
scanf("%d",&T);
while(T--)
{
ans1=0,ans2=0;
scanf("%lld",&n);
for(int i=1;i<=n;i++)
s[i].clear();
for(int i=2;i<=n;i++)
scanf("%d",&f[i]);
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]),s[f[i]].insert(a[i]);
for(int i=0;i<=n;i++)
{
if(s[i].empty()==0)
{
it=s[i].end();it--;
if((*it)>0) ans2+=(*it),s[i].erase(it);
}
if(s[i].empty()==0)
{
it=s[i].begin();
if((*it)<0) ans1+=(*it),s[i].erase(it);
}
}
ll mx=0,mn=0;
for(int i=0;i<=n;i++)
{
if(s[i].empty())
continue;
it=s[i].begin();
mn=min(mn,(*it));
it=s[i].end();it--;
mx=max(mx,(*it));
}
printf("%lld %lld\n",ans2+mx,ans1+mn);
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
typedef struct node{
int w,fa;
}node;
int t;
void solve(){
int n;
scanf("%d",&n);
node a[N];
int mp[N]={0};
a[1].fa=N-1;
for(int i=2;i<=n;i++){
scanf("%d",&a[i].fa);
}
for(int i=1;i<=n;i++){
scanf("%d",&a[i].w);
}
sort(a+1,a+n+1,[](node x,node y){return x.w>y.w;});
ll ans1=0,ans2=0;
int flag1=0,flag2=0;
for(int i=1;i<=n;i++){
int fa=a[i].fa,w=a[i].w;
if(mp[fa]==1&&flag1==0&&w>0){
flag1=1;
ans1+=w;
}else if(mp[fa]==0&&w>0){
mp[fa]++;
ans1+=w;
}else if(w<=0){
break;
}
}
memset(mp,0,sizeof(mp));
sort(a+1,a+n+1,[](node x,node y){return x.w<y.w;});
for(int i=1;i<=n;i++){
int fa=a[i].fa,w=a[i].w;
if(mp[fa]==1&&flag2==0&&w<0){
flag2=1;
ans2+=w;
}else if(mp[fa]==0&&w<0){
mp[fa]++;
ans2+=w;
}else if(w>=0){
break;
}
}
printf("%lld %lld\n",ans1,ans2);
}
int main()
{
scanf("%d",&t);
while(t--)
solve();
}