-
Notifications
You must be signed in to change notification settings - Fork 0
/
Best Node.cpp
139 lines (78 loc) · 1.96 KB
/
Best Node.cpp
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
class Array
{
public:
template <class T>
static void input(vector<T> &A,int n)
{
for (int i = 0; i < n; i++)
{
scanf("%d ",&A[i]);
}
}
template <class T>
static void print(vector<T> &A)
{
for (int i = 0; i < A.size(); i++)
{
cout << A[i] << " ";
}
cout << endl;
}
};
// } Driver Code Ends
class Solution {
public:
long long bestNode(int N, vector<int> &A, vector<int> &P) {
//Step-1 ..Create a set and push P array into set
set<int> s;
for(int i=0;i<N;i++)
{
s.insert(P[i]);
}
//Step-2 ..Find out leaf nodes from s
vector<int> leaf_node;
for(int i=1;i<=P.size();i++)
{
if(!s.count(i))
{
leaf_node.push_back(i);
}
}
//Step-3 ..Traverse from leaf to root and store max at each and every time visited new node
long long ans = LLONG_MIN;
for(int leaf : leaf_node)
{
int curr_node = leaf;
long long sum = 0;
//-1 indicate the root
while(curr_node!=-1)
{
sum = -sum;
sum+=A[curr_node-1];
ans = max(ans,sum);
curr_node = P[curr_node-1];
}
}
return ans;
}
};
//{ Driver Code Starts.
int main(){
int t;
scanf("%d ",&t);
while(t--){
int N;
scanf("%d",&N);
vector<int> A(N);
Array::input(A,N);
vector<int> P(N);
Array::input(P,N);
Solution obj;
long long res = obj.bestNode(N, A, P);
cout<<res<<endl;
}
}
// } Driver Code Ends