Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...

There are two arrays $a$ and $b$ of length $n$. Initially, an $ans$ is equal to $0$ and the following operation is defined:   Choose position $i$ ($1 \le i \le n$);  Add $a_i$ to $ans$;  If $b_i \neq -1$ then add $a_i$ to $a_{b_i}$. 

What is the maximum $ans$ you can get by performing the operation on each $i$ ($1 \le i \le n$) exactly once?

Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.


-----Input-----

The first line contains the integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of arrays $a$ and $b$.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($−10^6 \le a_i \le 10^6$).

The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le n$ or $b_i = -1$).

Additional constraint: it's guaranteed that for any $i$ ($1 \le i \le n$) the sequence $b_i, b_{b_i}, b_{b_{b_i}}, \ldots$ is not cyclic, in other words it will always end with $-1$.


-----Output-----

In the first line, print the maximum $ans$ you can get.

In the second line, print the order of operations: $n$ different integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$). The $p_i$ is the position which should be chosen at the $i$-th step. If there are multiple orders, print any of them.


-----Examples-----
Input
3
1 2 3
2 3 -1

Output
10
1 2 3 

Input
2
-1 100
2 -1

Output
99
2 1 

Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9

Output
-9
3 5 6 1 9 4 10 7 8 2

Difficulty: HARD

Solutions:
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import deque
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
adj = [0] * (n + 1)
ind = [0] * (n + 1)
for i in range(n):
	if b[i] != -1:
		adj[i + 1] = b[i]
		ind[b[i]] += 1
q = deque()
for i in range(1, n + 1):
	if not ind[i]:
		q.append(i)
l = []
ans = 0
while len(q):
	cur = q.popleft()
	l.append(cur)
	ind[adj[cur]] -= 1
	if not ind[adj[cur]]:
		q.append(adj[cur])
l1 = []
l2 = deque()
for i in l:
	if a[i - 1] >= 0:
		ans += a[i - 1]
		if b[i - 1] != -1:
			a[b[i - 1] - 1] += a[i - 1]
		l1.append(i)
	else:
		ans += a[i - 1]
		l2.appendleft(i)
l2 = list(l2)
l1 += l2
print(ans)
print(*l1)


from collections import deque
n = int(input())
arr = list(map(int, input().split()))
ind = list(map(int, input().split()))
for i in range(n):
	ind[i] -= 1
indeg = [0 for i in range(n)]
for i in range(n):
	if ind[i] != -2:
		indeg[ind[i]] += 1
q = deque([])
for i in range(n):
	if indeg[i] == 0:
		q.append(i)
(ans, rev) = ([], [])
cnt = 0
while len(q) != 0:
	node = q.popleft()
	nei = ind[node]
	if arr[node] >= 0:
		ans.append(node)
		cnt += arr[node]
		if nei != -2:
			arr[nei] += arr[node]
			indeg[nei] -= 1
			if indeg[nei] == 0:
				q.append(nei)
	else:
		cnt += arr[node]
		rev.append(node)
		if nei != -2:
			indeg[nei] -= 1
			if indeg[nei] == 0:
				q.append(nei)
ans = ans + rev[-1::-1]
for i in range(len(ans)):
	ans[i] += 1
print(cnt)
print(*ans)


import sys
from queue import Queue
readline = sys.stdin.readline
readlines = sys.stdin.readlines
Us = lambda : readline().rstrip()
Ui = lambda : int(readline().rstrip())
Um = lambda : map(int, readline().split())
Ul = lambda : list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
q = Queue()
n = Ui()
z = Ul()
b = Ul()
z.insert(0, 0)
b.insert(0, 0)
deg = [0] * (max(b) * 10)
for i in range(1, n + 1):
	if b[i] != -1:
		deg[b[i]] += 1
for i in range(1, n + 1):
	if deg[i] == 0:
		q.put(i)
PNS = 0
M1 = []
M2 = []
while not q.empty():
	x = q.get()
	if z[x] >= 0:
		M1.append(x)
		PNS += z[x]
		if b[x] != -1:
			deg[b[x]] -= 1
			if deg[b[x]] == 0:
				q.put(b[x])
			z[b[x]] += z[x]
	else:
		M2.append(x)
		PNS += z[x]
		if b[x] != -1:
			deg[b[x]] -= 1
			if deg[b[x]] == 0:
				q.put(b[x])
print(PNS)
print(' '.join(map(str, M1)), end=' ')
M2.reverse()
print(' '.join(map(str, M2)))


from collections import defaultdict, deque
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
graph = defaultdict(list)
inorder = defaultdict(int)
value = defaultdict(int)
for i in range(n):
	value[i] = a[i]
	if b[i] != -1:
		graph[i].append(b[i] - 1)
		inorder[b[i] - 1] += 1
q = deque()
for i in range(n):
	if inorder[i] == 0:
		q.append(i)
stack = []
neg_val = []
while q:
	current_node = q.popleft()
	if value[current_node] >= 0:
		stack.append(current_node)
	elif value[current_node] < 0:
		neg_val.append(current_node)
	for i in graph[current_node]:
		if value[current_node] > 0:
			value[i] += value[current_node]
		inorder[i] -= 1
		if inorder[i] == 0:
			q.append(i)
print(sum(value.values()))
print(*[i + 1 for i in stack + neg_val[::-1]])


import heapq
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
Bvertices = []
for i in range(n):
	Bvertices.append([])
NoOutvertex = []
for i in range(n):
	if b[i] != -1:
		Bvertices[b[i] - 1].append(i)
	else:
		NoOutvertex.append(i)
Order = []
while NoOutvertex:
	ver = NoOutvertex.pop()
	Order.append(ver)
	for elem in Bvertices[ver]:
		NoOutvertex.append(elem)
Order.reverse()
ActualOrder = []
IsCovered = [False] * n
ans = 0
for i in Order:
	if a[i] > 0:
		ans += a[i]
		if b[i] != -1:
			a[b[i] - 1] += a[i]
		ActualOrder.append(i + 1)
		IsCovered[i] = True
Order.reverse()
for i in Order:
	if not IsCovered[i]:
		ans += a[i]
		ActualOrder.append(i + 1)
print(ans)
print(' '.join(map(str, ActualOrder)))


from collections import defaultdict
import sys
sys.setrecursionlimit(2 * 10 ** 5)
n = int(input())
a = [0] + list(map(int, input().split()))
b = list(map(int, input().split()))
f = defaultdict(list)
num_list = [0] * (n + 1)
for (index, nxt) in enumerate(b):
	if nxt != -1:
		f[index + 1].append(nxt)
		num_list[nxt] += 1
q = [i for (i, v) in enumerate(num_list) if i > 0 and v == 0]
res = 0
res_list = []
reverse_nege_list = []
while q:
	p = []
	for i in q:
		if a[i] > 0:
			res_list.append(i)
		else:
			reverse_nege_list.append(i)
		res += a[i]
		for nxt in f[i]:
			num_list[nxt] -= 1
			if num_list[nxt] == 0:
				p.append(nxt)
			if a[i] > 0:
				a[nxt] += a[i]
	q = p
print(res)
ans_list = res_list + reverse_nege_list[::-1]
print(' '.join(map(str, ans_list)))


import sys
from collections import deque
input = sys.stdin.buffer.readline
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
(e, par) = ([[] for _ in range(n)], [-1] * n)
for (u, v) in enumerate(b):
	if v == -1:
		continue
	e[v - 1].append(u)
	par[u] = v - 1
q = deque([i for i in range(n) if len(e[i]) == 0])
(sa, sb, incc) = (deque([]), deque([]), [0] * n)
while q:
	u = q.popleft()
	cc = a[u]
	for v in e[u]:
		cc += max(a[v], 0)
	a[u] = cc
	if cc >= 0:
		sa.append(u)
	else:
		sb.appendleft(u)
	p = par[u]
	if p != -1:
		incc[p] += 1
		if incc[p] == len(e[p]):
			q.append(p)
print(sum(a))
print(*[u + 1 for u in sa + sb])


from sys import stdin, setrecursionlimit as srl
from threading import stack_size, Thread
srl(int(1000000000.0) + 7)
stack_size(int(100000000.0))
ans = 0
before = []
after = []

def solve():
	global ans, after, before

	def tree(d, i):
		if len(d[i]) == 0:
			return
		for j in d[i]:
			d[j].remove(i)
		for j in d[i]:
			i = j
			tree(d, i)

	def traverse(d, i, a, b):
		global ans, after, before
		for j in d[i]:
			traverse(d, j, a, b)
		ans += a[i]
		if a[i] > 0 and b[i] != -1:
			a[b[i] - 1] += a[i]
			before.append(i + 1)
		elif a[i] > 0:
			before.append(i + 1)
		else:
			after.append(i + 1)
		return
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	terminators = []
	for i in range(n):
		if b[i] == -1:
			terminators.append(i)
	d = {}
	for i in range(n):
		d[i] = []
	for i in range(n):
		if b[i] != -1:
			d[i].append(b[i] - 1)
			d[b[i] - 1].append(i)
	for i in terminators:
		tree(d, i)
	for i in terminators:
		traverse(d, i, a, b)
	print(ans)
	after.reverse()
	before += after
	print(*before)
Thread(target=solve).start()


import sys
from queue import Queue
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda : readline().rstrip()
ni = lambda : int(readline().rstrip())
nm = lambda : map(int, readline().split())
nl = lambda : list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
q = Queue()
n = ni()
a = nl()
b = nl()
a.insert(0, 0)
b.insert(0, 0)
deg = [0] * (max(b) * 10)
for i in range(1, n + 1):
	if b[i] != -1:
		deg[b[i]] += 1
for i in range(1, n + 1):
	if deg[i] == 0:
		q.put(i)
PNS = 0
M1 = []
M2 = []
while not q.empty():
	x = q.get()
	if a[x] >= 0:
		M1.append(x)
		PNS += a[x]
		if b[x] != -1:
			deg[b[x]] -= 1
			if deg[b[x]] == 0:
				q.put(b[x])
			a[b[x]] += a[x]
	else:
		M2.append(x)
		PNS += a[x]
		if b[x] != -1:
			deg[b[x]] -= 1
			if deg[b[x]] == 0:
				q.put(b[x])
print(PNS)
print(' '.join(map(str, M1)), end=' ')
M2.reverse()
print(' '.join(map(str, M2)))


import sys
input = sys.stdin.readline
from collections import deque

class Graph(object):

	def __init__(self, n, d):
		self.n = n
		self.graph = [[] for i in range(n)]
		self.parent = [-1 for i in range(n)]
		self.directed = d

	def addEdge(self, x, y):
		self.graph[x].append(y)
		if not self.directed:
			self.graph[y].append(x)

	def bfs(self, root):
		queue = [root]
		queue = deque(queue)
		vis = [0] * self.n
		while len(queue) != 0:
			element = queue.popleft()
			vis[element] = 1
			for i in self.graph[element]:
				if vis[i] == 0:
					queue.append(i)
					self.parent[i] = element
					vis[i] = 1

	def dfs(self, root):
		stack = [root]
		vis = [0] * self.n
		stack2 = []
		while len(stack) != 0:
			element = stack.pop()
			if vis[element]:
				continue
			vis[element] = 1
			stack2.append(element)
			for i in self.graph[element]:
				if vis[i] == 0:
					self.parent[i] = element
					stack.append(i)
		while len(stack2) != 0:
			f.append(stack2.pop() + 1)

	def shortestpath(self, source, dest):
		self.bfs(source)
		path = [dest]
		while self.parent[path[-1]] != -1:
			path.append(parent[path[-1]])
		return path[::-1]

	def detect_cycle(self):
		indeg = [0] * self.n
		for i in range(self.n):
			for j in self.graph[i]:
				indeg[j] += 1
		q = deque()
		vis = 0
		for i in range(self.n):
			if indeg[i] == 0:
				q.append(i)
		ans = []
		rev = []
		while len(q) != 0:
			e = q.popleft()
			if a[e] >= 0:
				ans.append(e + 1)
			else:
				rev.append(e + 1)
			if b[e] != -1:
				indeg[b[e] - 1] -= 1
				if not indeg[b[e] - 1]:
					q.append(b[e] - 1)
				if a[e] >= 0:
					a[b[e] - 1] += a[e]
		return ans + rev[::-1]

	def reroot(self, root, ans):
		stack = [root]
		vis = [0] * n
		while len(stack) != 0:
			e = stack[-1]
			if vis[e]:
				stack.pop()
				continue
			vis[e] = 1
			for i in graph[e]:
				if not vis[e]:
					stack.append(i)
			if self.parent[e] == -1:
				continue
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
g = Graph(n, True)
for i in range(n):
	if b[i] != -1:
		g.addEdge(i, b[i] - 1)
order = g.detect_cycle()
print(sum(a))
print(*order)


n = int(input())
val = [0] + [int(x) for x in input().split()]
par = [-1] + [int(x) for x in input().split()]
chil = [[] for _ in range(n + 1)]
vis = [False] * (n + 1)
for (i, x) in enumerate(par):
	if x == -1:
		continue
	chil[x].append(i)
(first, second) = ([], [])
ans = 0
for i in range(1, n + 1):
	if vis[i]:
		continue
	stack = [i]
	post = []
	while stack:
		node = stack.pop()
		vis[node] = True
		post.append(node)
		for other in chil[node]:
			if not vis[other]:
				stack.append(other)
	for node in reversed(post):
		ans += val[node]
		if val[node] > 0 and par[node] != -1:
			val[par[node]] += val[node]
		if val[node] > 0:
			first.append(node)
		else:
			second.append(node)
print(ans)
print(' '.join(map(str, first + second[::-1])))


import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
for i in range(n):
	if B[i] != -1:
		B[i] -= 1
ans = 0
P = [0] * n
V = [0] * n
M = [[] for i in range(n)]
for i in range(n):
	if B[i] != -1:
		M[i].append(B[i])
		P[B[i]] += 1
Q = []
for i in range(n):
	if P[i] == 0:
		Q.append(i)
		V[i] = 1
s = 0
ANS = []
MINUS = []
while s < len(Q):
	i = Q[s]
	ans += A[i]
	if A[i] > 0:
		ANS.append(i)
	else:
		MINUS.append(i)
	for x in M[i]:
		if V[x] == 0:
			if A[i] > 0:
				A[x] += A[i]
			P[x] -= 1
			if P[x] == 0:
				Q.append(x)
				V[x] = 1
	s += 1
print(ans)
print(*[i + 1 for i in ANS] + [MINUS[i] + 1 for i in range(len(MINUS) - 1, -1, -1)])


from sys import stdin
from collections import deque
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
p = list(map(int, stdin.readline().split()))
chnum = [0] * n
for i in range(n):
	if p[i] - 1 >= 0:
		chnum[p[i] - 1] += 1
q = deque([])
for i in range(n):
	if chnum[i] == 0:
		q.append(i)
ans = 0
alis = []
end = []
while len(q) > 0:
	v = q.popleft()
	ans += a[v]
	if a[v] >= 0:
		alis.append(v + 1)
		if p[v] - 1 >= 0:
			chnum[p[v] - 1] -= 1
			a[p[v] - 1] += a[v]
			if chnum[p[v] - 1] == 0:
				q.append(p[v] - 1)
	else:
		end.append(v + 1)
		if p[v] - 1 >= 0:
			chnum[p[v] - 1] -= 1
			if chnum[p[v] - 1] == 0:
				q.append(p[v] - 1)
end.reverse()
for i in end:
	alis.append(i)
print(ans)
print(*alis)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
incoming = [0] * n
for x in b:
	if x == -1:
		continue
	incoming[x - 1] += 1
import heapq
remaining = []
heapq.heapify(remaining)
answer = 0
operations = []
for i in range(n):
	heapq.heappush(remaining, (incoming[i], i))
negatives = []
visited = {}
i = 0
while i < n:
	i += 1
	(x, y) = heapq.heappop(remaining)
	if y in visited:
		i -= 1
		continue
	visited[y] = 1
	if a[y] < 0:
		negatives.append(y)
		if b[y] != -1:
			incoming[b[y] - 1] -= 1
			heapq.heappush(remaining, (incoming[b[y] - 1], b[y] - 1))
		continue
	operations.append(y + 1)
	answer += a[y]
	if b[y] != -1:
		idx = b[y] - 1
		a[idx] += a[y]
		incoming[idx] -= 1
		heapq.heappush(remaining, (incoming[idx], idx))
for y in reversed(negatives):
	operations.append(y + 1)
	answer += a[y]
	idx = b[y] - 1
	if idx == -2:
		continue
	else:
		a[idx] += a[y]
print(answer)
print(*operations)


import sys
input = sys.stdin.readline
(N,) = map(int, input().split())
X = [0] + list(map(int, input().split()))
Y = [0] + list(map(int, input().split()))
st = []
G = [set() for _ in range(N + 1)]
for i in range(1, N + 1):
	if Y[i] < 0:
		st.append(i)
	else:
		G[Y[i]].add(i)
ato = []
R = []
W = [0] * (N + 1)
for s in st:
	stack = [s]
	vs_dfs = list()
	while stack:
		v = stack.pop()
		vs_dfs.append(v)
		for u in G[v]:
			stack.append(u)
	for v in vs_dfs[::-1]:
		for u in G[v]:
			X[v] += max(0, X[u])
		if X[v] < 0:
			ato.append(v)
		else:
			R.append(v)
ato = ato[::-1]
print(sum(X))
print(*R + ato)


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
from fractions import Fraction
INF = float('inf')
mod = int(1000000000.0) + 7

def toposort(graph):
	(res, found) = ([], [0] * len(graph))
	stack = list(range(len(graph)))
	while stack:
		node = stack.pop()
		if node < 0:
			res.append(~node)
		elif not found[node]:
			found[node] = 1
			stack.append(~node)
			stack += graph[node]
	for node in res:
		if any((found[nei] for nei in graph[node])):
			return None
		found[node] = 0
	return res[::-1]
n = int(data())
a = mdata()
b = mdata()
g = [[] for i in range(n)]
for i in range(n):
	if b[i] != -1:
		g[i].append(b[i] - 1)
res = toposort(g)
s = []
ans = []
v = 0
for i in res:
	if a[i] < 0:
		s.append(i)
	else:
		if b[i] != -1:
			a[b[i] - 1] += a[i]
		ans.append(i + 1)
		v += a[i]
s = s[::-1]
for i in s:
	ans.append(i + 1)
	v += a[i]
out(v)
outl(ans)


from collections import deque
ans = 0
n = int(input())
a = list(map(int, input().split()))
b = [i - 1 if i != -1 else -1 for i in list(map(int, input().split()))]
flow = [0] * n
graph = [[] for i in range(n)]
for i in range(n):
	if b[i] != -1:
		flow[b[i]] += 1
		graph[i].append(b[i])
check = [a[i] for i in range(n)]
ver = deque()
lv = 0
for i in range(n):
	if flow[i] == 0:
		ver.append(i)
		lv += 1
(f, s) = ([], [])
while lv:
	for i in range(lv):
		x = ver.popleft()
		lv -= 1
		if check[x] >= 0:
			f.append(x)
			for j in graph[x]:
				flow[j] -= 1
				check[j] += check[x]
				if flow[j] == 0:
					ver.append(j)
					lv += 1
		else:
			s.append(x)
			for j in graph[x]:
				flow[j] -= 1
				if flow[j] == 0:
					ver.append(j)
					lv += 1
print(sum(check))
print(' '.join(map(lambda x: str(x + 1), f + s[::-1])))


import math
import time
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
from queue import PriorityQueue
import sys

class Graph:

	def __init__(self, n):
		self.graph = defaultdict(lambda : [])
		self.vertices = n
		self.edges = 0
		self.toposorted = []

	def addEdge(self, a, b):
		self.graph[a].append(b)
		self.edges += 1

	def cycleUntill(self, visited, curr, parent):
		visited[curr] = True
		for i in self.graph[curr]:
			if not visited[i]:
				if self.cycleUntill(visited, i, curr):
					return True
			elif i != parent:
				return True
		return False

	def cycle(self):
		n = self.vertices
		visited = [False] * (n + 2)
		for i in range(1, n + 1):
			if not visited[i]:
				if self.cycleUntill(visited, i, -1):
					return True
		return False

	def topologicalSort(self):
		in_degree = [0] * (self.vertices + 10)
		for i in self.graph:
			for j in self.graph[i]:
				in_degree[j] += 1
		queue = deque()
		for i in range(1, self.vertices + 1):
			if in_degree[i] == 0:
				queue.append(i)
		cnt = 0
		while queue:
			u = queue.popleft()
			self.toposorted.append(u)
			for i in self.graph[u]:
				in_degree[i] -= 1
				if in_degree[i] == 0:
					queue.append(i)
			cnt += 1
		if cnt != self.vertices:
			return False
		else:
			return True

	def connected(self):
		visited = [False] * (self.vertices + 2)
		ans = []
		for i in range(1, self.vertices + 1):
			if not visited[i]:
				comp = []
				q = deque()
				visited[i] = True
				q.append(i)
				while len(q) > 0:
					temp = q.popleft()
					comp.append(temp)
					for j in self.graph[temp]:
						if not visited[j]:
							visited[j] = True
							q.append(j)
				ans.append(comp)
		return ans
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
b = list(map(int, stdin.readline().split()))
g = Graph(n)
for i in range(n):
	if b[i] != -1:
		g.addEdge(i + 1, b[i])
g.topologicalSort()
ans = 0
ansind = []
neg = 0
negind = []
for i in g.toposorted:
	if a[i - 1] < 0:
		neg += a[i - 1]
		negind.append(i)
	else:
		ans += a[i - 1]
		if b[i - 1] != -1:
			a[b[i - 1] - 1] += a[i - 1]
		ansind.append(i)
print(ans + neg)
print(*ansind + negind[::-1])


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = 1
	mod = 1000000007
	limit = 10 ** 18
	ans = 0
	stack = []
	hashm = {}
	arr = []
	heapq.heapify(arr)
	for test in range(tests):
		n = inp()
		a = inlt()
		b = inlt()
		for i in range(n):
			if b[i] > 0:
				b[i] = b[i] - 1
		in_edge = [{} for i in range(n + 1)]
		out_edge = [{} for i in range(n + 1)]
		for i in range(n):
			if b[i] != -1:
				in_edge[b[i]][i] = 1
				out_edge[i][b[i]] = 1
		done = [0 for i in range(n + 1)]
		stack = []
		for i in range(0, n):
			if in_edge[i] == {}:
				stack.append(i)
		ans = 0
		pos = []
		last = []
		while stack != []:
			nexts = []
			for i in stack:
				done[i] = 1
				ans = ans + a[i]
				if a[i] > 0:
					pos.append(i + 1)
				else:
					last.append(i + 1)
				for j in out_edge[i]:
					if a[i] > 0:
						a[j] = a[j] + a[i]
					del in_edge[j][i]
					if in_edge[j] == {}:
						nexts.append(j)
			stack = nexts
		for i in range(n):
			if done[i] != 1:
				ans = ans + a[i]
				pos.append(i + 1)
		last.reverse()
		pos = pos + last
		print(ans)
		pr_list(pos)
main()


from collections import defaultdict, deque
from sys import stdin, stdout

def input():
	return stdin.readline().strip()
input()
A = list(map(int, input().split(' ')))
B = list(map(int, input().split(' ')))
N = len(A)
next = dict()
prevs = defaultdict(set)
for (i, b) in enumerate(B):
	next[i + 1] = b
	prevs[b].add(i + 1)
queue = deque([])
for i in range(1, N + 1):
	if len(prevs[i]) == 0:
		queue.append(i)
score = 0
positives = []
negatives = []
while len(queue):
	p = queue.popleft()
	q = next[p]
	prevs[q].remove(p)
	if q != -1 and len(prevs[q]) == 0:
		queue.append(q)
	a = A[p - 1]
	b = B[p - 1]
	if a >= 0:
		score += a
		if b != -1:
			A[b - 1] += a
		positives += [p]
	else:
		negatives += [p]
for p in negatives:
	a = A[p - 1]
	assert a < 0
	score += a
order = positives + negatives[::-1]
print(score)
print(*order)