1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <queue> #define MAXN 100005 #define LL long long #define LB long double #define INF 1e18 using namespace std;
int T, n, cnt, head[MAXN], maxson[MAXN], minson[MAXN], maxtag[MAXN], mintag[MAXN]; LL maxans, minans, w[MAXN], maxval[MAXN], minval[MAXN];
struct Edge {int next, to;} edge[MAXN*2];
void addedge(int from, int to) { edge[++cnt].next=head[from]; edge[cnt].to=to; head[from]=cnt; }
void dfs(int x, int fa) { for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==fa) continue; dfs(to, x); if(w[to]>maxval[x]) maxson[x]=to, maxval[x]=w[to]; if(w[to]<minval[x]) minson[x]=to, minval[x]=w[to]; } maxans+=maxval[x]; minans+=minval[x]; maxtag[maxson[x]]=1; mintag[minson[x]]=1; }
int main() { scanf("%d", &T); while(T--) { cnt=maxans=minans=0; for(int i=0; i<MAXN-1; i++) head[i]=maxson[i]=minson[i]=maxval[i]=minval[i]=mintag[i]=maxtag[i]=0; LL mintemp=0, maxtemp=0; scanf("%d", &n); for(int i=2; i<=n; i++) { int fa; scanf("%d", &fa); addedge(fa, i); addedge(i, fa); } for(int i=1; i<=n; i++) scanf("%lld", &w[i]); dfs(1, 0); if(w[1]>0) maxtag[1]=1, maxans+=w[1]; if(w[1]<0) mintag[1]=1, minans+=w[1]; for(int i=1; i<=n; i++) { if(!mintag[i]) mintemp=min(mintemp, w[i]); } for(int i=n; i>=1; i--) { if(!maxtag[i]) maxtemp=max(maxtemp, w[i]); } printf("%lld %lld\n", maxans+maxtemp, minans+mintemp); } }
|