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

Source: codeforces | Difficulty: HARD
Tags: Graph algorithms

Graph traversal

Implementation

Greedy algorithms

Tree algorithms

Data structures


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 bisect
import collections
import copy
import enum
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(3001)
input = sys.stdin.readline
n = int(input())
ans = 0
sl = []
arr = list(map(int, input().split()))
brr = list(map(int, input().split()))
g = collections.defaultdict(list)
for (i, c) in enumerate(brr):
	g[c].append(i + 1)
q = collections.deque()
for c in g[-1]:
	q.append(c)
while q:
	ind = q.popleft()
	sl.append(ind)
	for nc in g[ind]:
		q.append(nc)
pre = []
aft = []
crr = arr[:]
for ind in sl[::-1]:
	if crr[ind - 1] > 0:
		ans += crr[ind - 1]
		if brr[ind - 1] != -1:
			crr[brr[ind - 1] - 1] += crr[ind - 1]
		pre.append(ind)
	else:
		ans += crr[ind - 1]
		aft.append(ind)
print(ans)
print(*pre + aft[::-1])


from sys import stdin, setrecursionlimit as srl
from threading import stack_size, Thread
srl(int(1000000.0) + 7)
stack_size(int(100000000.0))
ip = stdin.readline

def solve():
	n = int(ip())
	a = list(map(int, ip().split()))
	b = list(map(int, ip().split()))
	adj = [[] for _ in range(n)]
	for i in range(n):
		if not b[i] == -1:
			adj[i].append(b[i] - 1)
	visited = [0] * n
	stk = []
	for x in range(n):

		def topsort(v):
			if visited[v] == 2:
				return
			visited[v] = 1
			for i in adj[v]:
				topsort(i)
			visited[v] = 2
			stk.append(v)
		if not visited[x]:
			topsort(x)
	laterstk = []
	extra = [0] * n
	ans = 0
	soln = []
	while stk:
		i = stk.pop()
		if a[i] + extra[i] < 0:
			laterstk.append(i)
		else:
			ans += a[i] + extra[i]
			if len(adj[i]) == 1:
				j = adj[i][0]
				extra[j] += extra[i] + a[i]
			soln.append(i + 1)
	while laterstk:
		i = laterstk.pop()
		ans += a[i] + extra[i]
		soln.append(i + 1)
	print(ans)
	print(*soln)
Thread(target=solve).start()


import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)
from collections import defaultdict
con = 10 ** 9 + 7
INF = float('inf')

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

class Graph(object):

	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

def DFS(G, W, P, Q, node):
	for i in G.graph[node]:
		DFS(G, W, P, Q, i)
		if W[i] > 0:
			W[node] += W[i]
			P.append(i + 1)
		else:
			Q.append(i + 1)

def main():
	N = int(input())
	W = getlist()
	B = getlist()
	G = Graph()
	for i in range(N):
		(u, v) = (B[i], i)
		if u != -1:
			u -= 1
			G.add_edge(u, v)
	P = []
	Q = []
	for i in range(N):
		if B[i] == -1:
			DFS(G, W, P, Q, i)
			P.append(i + 1)
	P += Q[::-1]
	weight = sum(W)
	print(weight)
	print(*P)
import threading
threading.stack_size(1024 * 100000)
thread = threading.Thread(target=main)
thread.start()
thread.join()


from collections import defaultdict
import sys
input = sys.stdin.readline
n = int(input())
a = [int(i) for i in input().split() if i != '\n']
b = [int(i) for i in input().split() if i != '\n']
visited = [0] * (n + 1)
graph = defaultdict(list)
for i in range(n):
	if b[i] != -1:
		graph[b[i]].append(i + 1)
	else:
		graph[i + 1] = []
OBSERVE = 0
CHECK = 1
topsort = []
for i in range(1, n + 1):
	if visited[i] == 0:
		stack = [(OBSERVE, i, 0)]
		while len(stack):
			(state, vertex, parent) = stack.pop()
			visited[vertex] = 1
			if state == OBSERVE:
				stack.append((CHECK, vertex, parent))
				for child in graph[vertex]:
					if visited[child] != 1:
						stack.append((OBSERVE, child, vertex))
			else:
				topsort.append(vertex)
(ans, path) = (0, [])
visited = [0] * (n + 1)
neg = []
for i in range(n):
	if visited[i] == 0:
		if a[topsort[i] - 1] >= 0:
			ans += a[topsort[i] - 1]
			end = b[topsort[i] - 1]
			if end != -1:
				a[b[topsort[i] - 1] - 1] += a[topsort[i] - 1]
			path.append(topsort[i])
			visited[i] = 1
		else:
			neg.append(topsort[i])
for i in neg:
	ans += a[i - 1]
neg.reverse()
path += neg
sys.stdout.write(str(ans) + '\n')
path = ' '.join(map(str, path))
sys.stdout.write(path + '\n')


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 sys
input = sys.stdin.readline

def topological_sort(graph):
	n = len(graph)
	degree = [0] * n
	for v in graph:
		for nxt_v in v:
			degree[nxt_v] += 1
	ans = []
	for i in range(n):
		if degree[i] == 0:
			ans.append(i)
	stack = ans[:]
	while stack:
		pos = stack.pop()
		for next_v in graph[pos]:
			degree[next_v] -= 1
			if degree[next_v] == 0:
				stack.append(next_v)
				ans.append(next_v)
	return ans
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
graph = [[] for _ in range(n)]
inv_graph = [[] for _ in range(n)]
for (i, nxt_v) in enumerate(b):
	if nxt_v == -1:
		continue
	nxt_v -= 1
	graph[i].append(nxt_v)
	inv_graph[nxt_v].append(i)
ans = 0
res = []
used = [False] * n
tp_sort = topological_sort(graph)
for v in tp_sort:
	if used[v]:
		continue
	if a[v] > -1:
		ans += a[v]
		for nxt_v in graph[v]:
			a[nxt_v] += a[v]
		res.append(v + 1)
		used[v] = True
tp_sort = topological_sort(inv_graph)
for v in tp_sort:
	if used[v]:
		continue
	ans += a[v]
	res.append(v + 1)
	used[v] = True
print(ans)
print(*res)


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)))


import collections
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) - 1 for x in input().split()]
ins = collections.defaultdict(int)
for i in range(n):
	if b[i] != -2:
		ins[b[i]] += 1

def topsort():
	start = [i for i in range(n) if ins[i] == 0]
	order = []
	negs = []
	res = 0
	while start:
		curr = start.pop()
		if a[curr] < 0:
			negs += [curr]
		else:
			res += a[curr]
			order += [curr]
		if b[curr] != -2:
			if a[curr] > 0:
				a[b[curr]] += a[curr]
			ins[b[curr]] -= 1
			if ins[b[curr]] == 0:
				start.append(b[curr])
	sumn = 0
	for ne in negs:
		sumn += a[ne]
	return (res + sumn, [x + 1 for x in order] + [x + 1 for x in negs[::-1]])
(res, order) = topsort()
print(res)
print(' '.join((str(x) for x in order)))


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)))


from collections import deque
n = int(input())
a = list(map(int, input().split()))
b = [int(i) - 1 for i in input().split()]
tr = [[] for i in range(n)]
ts = [[] for i in range(n)]
for i in range(n):
	if b[i] != -2:
		tr[b[i]].append(i)
ans = 0
deg = [0 for i in range(n)]

def dfs(i):
	q = deque([i])
	w = []
	an = 0
	while q:
		x = q.pop()
		w.append(x)
		for y in tr[x]:
			q.append(y)
	for i in range(len(w) - 1, -1, -1):
		x = w[i]
		an += a[x]
		if a[x] >= 0 and b[x] != -2:
			a[b[x]] += a[x]
			ts[x].append(b[x])
			deg[b[x]] += 1
		elif b[x] != -2:
			ts[b[x]].append(x)
			deg[x] += 1
	return an
for i in range(n):
	if b[i] == -2:
		ans += dfs(i)
print(ans)
pos = []
q = deque([])
for i in range(n):
	if deg[i] == 0:
		q.append(i)
while q:
	x = q.popleft()
	pos.append(x + 1)
	for y in ts[x]:
		deg[y] -= 1
		if deg[y] == 0:
			q.append(y)
print(*pos)


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())
a = list(map(int, input().strip().split()))
b = list(map(int, input().strip().split()))
edge = [[] for i in range(n)]
for (i, x) in enumerate(b):
	if x != -1:
		b[i] -= 1
		edge[b[i]].append(i)
used = [False] * n
(order1, order2) = ([], [])
ans = 0
from collections import deque

def post_process(u):
	global ans, used, order1, order2, edge, a, b
	ans += a[u]
	if b[u] != -1 and a[u] > 0:
		a[b[u]] += a[u]
	if a[u] > 0:
		order1.append(u)
	else:
		order2.append(u)
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

@bootstrap
def dfs(u):
	global ans, used, order1, order2, edge, a, b
	used[u] = True
	for v in edge[u]:
		if not used[v]:
			used = (yield dfs(v))
	post_process(u)
	yield used
for i in range(n):
	if not used[i]:
		used = dfs(i)
print(ans)
print(' '.join((str(o + 1) for o in order1)), end=' ')
print(' '.join((str(o + 1) for o in reversed(order2))))


import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
edges = [[] for i in range(n)]
parent = [-1 for i in range(n)]
for i in range(len(b)):
	if b[i] != -1:
		edges[b[i] - 1].append(i)
		parent[i] = b[i] - 1
done = [0 for i in range(n)]
first = []
last = []
ans = 0
for i in range(n):
	if done[i] == 0:
		dfs = [i]
		while len(dfs) > 0:
			curr = dfs[-1]
			cont = 1
			for i in edges[curr]:
				if done[i] == 0:
					cont = 0
					dfs.append(i)
					break
			if cont == 1:
				if a[curr] > 0:
					first.append(curr + 1)
					if parent[curr] != -1:
						a[parent[curr]] += a[curr]
				else:
					last.append(curr + 1)
				ans += a[curr]
				done[curr] = 1
				dfs.pop(-1)
print(ans)
print(' '.join(map(str, first)) + ' ' + ' '.join(map(str, last[::-1])))


n = int(input())
a = list(map(int, input().split()))
b = list((int(x) - 1 for x in input().split()))
indeg = [0] * n
for x in b:
	if x >= 0:
		indeg[x] += 1
q = [i for i in range(n) if indeg[i] == 0]
ans = 0
res = []
end = []
while q:
	top = q.pop()
	if a[top] < 0:
		end.append(top)
	else:
		res.append(top)
		ans += a[top]
		if b[top] >= 0:
			a[b[top]] += a[top]
	if b[top] >= 0:
		nei = b[top]
		indeg[nei] -= 1
		if indeg[nei] == 0:
			q.append(nei)
for i in end[::-1]:
	ans += a[i]
	if b[i] >= 0:
		a[b[i]] += a[i]
	res.append(i)
print(ans)
print(*[x + 1 for x in res])


import io
import os
from collections import Counter, defaultdict, deque

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]

def solve(N, A, B):
	graph = [[] for i in range(N)]
	graphT = [[] for i in range(N)]
	for (i, (a, b)) in enumerate(zip(A, B)):
		if b >= 0:
			graph[i].append(b)
			graphT[b].append(i)
	topo = toposort(graph)
	ans = 0
	order = []
	used = set()
	for i in topo:
		if A[i] >= 0:
			order.append(i)
			used.add(i)
			ans += A[i]
			if B[i] >= 0:
				A[B[i]] += A[i]
	topo2 = toposort(graphT)
	for i in topo2:
		if i not in used:
			order.append(i)
			ans += A[i]
			if B[i] >= 0:
				A[B[i]] += A[i]
	return str(ans) + '\n' + ' '.join([str(x + 1) for x in order])
if False:
	import random
	random.seed(0)
	N = 5
	A = [random.randint(-10, 10) for i in range(N)]
	B = list(range(1, N)) + [-1]
	print(A, B)
	print(solve(N, A, B))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N,) = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
B = [int(x) - 1 for x in input().split()]
ans = solve(N, A, B)
print(ans)


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])))


from collections import Counter
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
indeg = Counter(b)
s = []
for i in range(n):
	if i + 1 not in indeg:
		s.append(i)
ans = 0
steps = []
while s:
	index = s.pop()
	if a[index] >= 0:
		steps.append(index + 1)
		ans += a[index]
	if b[index] != -1:
		if a[index] >= 0:
			a[b[index] - 1] += a[index]
		indeg[b[index]] -= 1
		if indeg[b[index]] == 0:
			s.append(b[index] - 1)
outdeg = {}
adj = {}
for i in range(n):
	if b[i] != -1 and a[i] < 0 and (a[b[i] - 1] < 0):
		if b[i] - 1 in adj:
			adj[b[i] - 1].append(i)
		else:
			adj[b[i] - 1] = [i]
s = []
for i in range(n):
	if a[i] < 0:
		if b[i] != -1 and a[b[i] - 1] < 0:
			outdeg[i] = 1
		else:
			s.append(i)
while s:
	index = s.pop()
	ans += a[index]
	steps.append(index + 1)
	if index in adj:
		for ele in adj[index]:
			outdeg[ele] -= 1
			if outdeg[ele] == 0:
				s.append(ele)
print(ans)
for ele in steps:
	print(ele, end=' ')


from sys import *

def main():
	n = int(stdin.readline().rstrip())
	a = [int(x) for x in stdin.readline().rstrip().split()]
	b = [int(x) for x in stdin.readline().rstrip().split()]
	countLink = dict()
	for i in b:
		countLink[i - 1] = countLink.get(i - 1, 0) + 1
	preselect = []
	for i in range(n):
		if countLink.get(i, 0) == 0:
			preselect.append(i)
	selected = []
	stack = []
	result = 0
	while len(preselect) > 0:
		i = preselect.pop()
		if countLink.get(i, 0) == 0:
			result += a[i]
			if a[i] > 0:
				selected.append(i + 1)
				if b[i] != -1:
					a[b[i] - 1] += a[i]
			else:
				stack.append(i + 1)
			countLink[b[i] - 1] = countLink.get(b[i] - 1, 0) - 1
			countLink[i] = -1
			if countLink[b[i] - 1] == 0 and b[i] - 1 >= 0:
				preselect.append(b[i] - 1)
	print(result)
	for i in selected:
		print(i, end=' ')
	for i in reversed(stack):
		print(i, end=' ')
main()


import sys
from collections import deque
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
rev_g = [[] for i in range(n)]
for i in range(n):
	if b[i] != -1:
		rev_g[b[i] - 1].append(i)
roots = []
for i in range(n):
	if b[i] == -1:
		roots.append(i)
order = []
par = [-1] * n
for x in roots:
	dq = deque([[-1, x]])
	while dq:
		(p, v) = dq.popleft()
		order.append(v)
		for to in rev_g[v]:
			if p != to:
				par[to] = v
				dq.append([v, to])
order.reverse()
before = []
after = []
ans = 0
for x in order:
	if a[x] < 0:
		after.append(x + 1)
		ans += a[x]
		a[x] = 0
	else:
		before.append(x + 1)
		if par[x] != -1:
			ans += a[x]
			a[par[x]] += a[x]
		else:
			ans += a[x]
print(ans)
print(*before + after[::-1])


import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int, input().split()))
B = map(int, input().split())
IncomList = [[] for _ in range(n)]
weight = [None] * n
endpoints = list()
for (i, d) in enumerate(B):
	if d == -1:
		endpoints.append(i)
	else:
		IncomList[d - 1].append(i)
(serial, last) = (list(), list())
ans = 0
while endpoints:
	e = endpoints[-1]
	flag = True
	for h in IncomList[e]:
		if weight[h] is None:
			endpoints.append(h)
			flag = False
	if flag:
		endpoints.pop()
		weight[e] = A[e] + sum(map(lambda x: max(0, weight[x]), IncomList[e]))
		ans += weight[e]
		if weight[e] >= 0:
			serial.append(e + 1)
		else:
			last.append(e + 1)
serial.extend(reversed(last))
print(ans)
print(' '.join(map(str, serial)))


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def toposort(g, dependency):
	queue = deque([])
	for i in range(0, len(dependency)):
		if dependency[i] == 0:
			queue.append(i)
	new = []
	while len(queue):
		s = queue.pop()
		new.append(s)
		for i in g[s]:
			dependency[i] -= 1
			if dependency[i] == 0:
				queue.append(i)
	return new

def solve():
	n = int(inp())
	a = lis()
	b = lis()
	graph = [[] for i in range(n)]
	dependency = [0] * n
	for i in range(n):
		if b[i] != -1:
			graph[i].append(b[i] - 1)
			dependency[b[i] - 1] += 1
	ans = []
	temp = []
	order = toposort(graph, dependency)
	for i in range(len(order)):
		if a[order[i]] >= 0:
			ans.append(order[i] + 1)
		else:
			temp.append(order[i] + 1)
		if b[order[i]] != -1 and a[order[i]] >= 0:
			a[b[order[i]] - 1] += a[order[i]]
	ans += temp[::-1]
	print(sum(a))
	print(' '.join((str(ans[i]) for i in range(len(ans)))))
testcase(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
mod = 10 ** 9 + 7
import sys
import random
sys.setrecursionlimit(10 ** 6)
from queue import PriorityQueue
from collections import Counter as cc
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p
import sys
n = int(input())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
hash = defaultdict(list)
boo = defaultdict(bool)
par = defaultdict(set)
for i in range(n):
	k = i + 1
	if boo[k] == False:
		boo[k] = True
		par[k].add(k)
		while True:
			z = l2[k - 1]
			if z != -1:
				par[z].add(k)
			if boo[z] == True:
				hash[k].append(z)
				break
			if z == -1:
				break
			boo[z] = True
			hash[k].append(z)
			k = z
final = 0
ans = []
seti = set()
for i in par:
	if i in par[i] and len(par[i]) > 1:
		par[i].remove(i)
for i in range(1, n + 1):
	if len(par[i]) == 1 and i in par[i]:
		seti.add(list(par[i])[0])
ka = []
for i in seti:
	k = i
	while True:
		try:
			z = hash[k][0]
		except:
			ans.append(k)
			break
		if l1[z - 1] + l1[k - 1] >= l1[z - 1]:
			l1[z - 1] += l1[k - 1]
			ans.append(k)
		else:
			ka.append(k)
		if len(par[z]) > 1:
			par[z].remove(k)
			break
		k = z
ka.reverse()
print(sum(l1))
print(*ans + ka)


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)


import math
from sys import setrecursionlimit
import threading
g = []
used = []
ord = []
head = []

def dfs(v):
	now = []
	now.append(v)
	used[v] = 1
	while len(now) > 0:
		v = now[-1]
		if head[v] == len(g[v]):
			ord.append(v)
			now.pop()
			continue
		if used[g[v][head[v]]] == 0:
			now.append(g[v][head[v]])
			used[g[v][head[v]]] = 1
		head[v] += 1

def main():
	global g, used, ord, head
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	answ = []
	used = [0] * (n + 1)
	g = [[] for i in range(n + 1)]
	go = [[] for i in range(n + 1)]
	dp = [0] * n
	head = [0] * n
	for i in range(n):
		if b[i] == -1:
			continue
		b[i] -= 1
		g[i].append(b[i])
		go[b[i]].append(i)
	for i in range(n):
		if used[i] == 1:
			continue
		dfs(i)
	ord.reverse()
	for x in ord:
		dp[x] += a[x]
		for y in go[x]:
			dp[x] += max(0, dp[y])
	ans = 0
	for x in ord:
		if dp[x] < 0:
			continue
		ans += a[x]
		answ.append(x)
		if b[x] == -1:
			continue
		a[b[x]] += a[x]
	for i in range(n - 1, -1, -1):
		x = ord[i]
		if dp[x] >= 0:
			continue
		ans += a[x]
		answ.append(x)
		if b[x] == -1:
			continue
		a[b[x]] += a[x]
	print(ans)
	for x in answ:
		print(x + 1, end=' ')
main()


import sys
input = sys.stdin.readline
n = int(input())
ar = list(map(int, input().split()))
br = list(map(int, input().split()))
dic = {}
revtree = {}
for i in range(1, n + 1):
	revtree[i] = []
	dic[i] = [ar[i - 1], br[i - 1]]
root = set({})
for i in range(1, n + 1):
	ind = dic[i][1]
	if ind != -1:
		revtree[ind].append(i)
	else:
		root.add(i)
tree = []
dis = []
for i in root:
	tree.append([i])
	dis.append(dict({}))
	dis[-1][i] = 0
	level = 1
	ne = {i}
	while ne:
		tem = set({})
		for j in ne:
			xx = revtree[j]
			for k in xx:
				tem.add(k)
				tree[-1].append(k)
				dis[-1][k] = level
		ne = tem.copy()
		level += 1
for i in range(len(root)):
	tree[i].sort(key=lambda x: dis[i][x], reverse=True)
ans = 0
li = []
last = []
for i in tree:
	for j in i:
		ind = dic[j][1]
		val = dic[j][0]
		if val < 0:
			ans += val
			last.append(j)
		else:
			ans += val
			if ind != -1:
				dic[ind][0] += val
			li.append(j)
print(ans)
print(*li + last[::-1])


def main():
	import sys
	input = sys.stdin.buffer.readline
	import collections
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	G = [set() for i in range(n)]
	q = collections.deque()
	for (i, x) in enumerate(b):
		if x < 0:
			q.append(i)
		else:
			x -= 1
			G[x].add(i)
	rans = []
	r = set([i for i in range(n)])
	while q:
		x = q.popleft()
		rans.append(x)
		r.remove(x)
		for y in G[x]:
			q.append(y)
	R = []
	score = 0
	while len(r):
		s = r.pop()
		q.append(s)
		while s:
			x = q.popleft()
			score += a[x]
			R.append(x)
			for y in G[x]:
				q.append(y)
				a[y] += a[x]
	ans = rans[::-1]
	A = []
	B = []
	for x in ans:
		score += a[x]
		if b[x] > 0:
			if a[x] >= 0:
				a[b[x] - 1] += a[x]
				A.append(x)
			else:
				B.append(x)
		else:
			A.append(x)
	print(score)
	ans = A + B[::-1] + R
	print(*map(lambda x: x + 1, ans))
main()


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')
sys.setrecursionlimit(10 ** 6)

def dfs(u):
	global ans
	if v[u] == 1:
		return [0, []]
	else:
		v[u] = 1
		bw = []
		fw = []
		res = 0
		for j in range(len(adj[u])):
			if v[adj[u][j]] == 0:
				k = dfs(adj[u][j])
				tot = k[0]
				path = k[1]
				if tot < 0:
					for p in path:
						fw.append(p)
				else:
					res += tot
					for p in path:
						bw.append(p)
		ans += res + a[u - 1]
		return [res + a[u - 1], bw + [u] + fw]
n = int(input())
if n == 2 * 10 ** 5:
	val = list(map(int, input().split()))
	b = list(map(int, input().split()))
	neig = [0] * n
	for i in range(n):
		neig[i] = [0]
	inedges = [0] * n
	for i in range(n):
		if b[i] != -1:
			neig[i][0] += 1
			neig[i].append(b[i] - 1)
			inedges[b[i] - 1] += 1
	ans = 0
	beg = []
	en = []
	tod = []
	for i in range(n):
		if inedges[i] == 0:
			tod.append(i)
	while len(tod) > 0:
		x = tod.pop()
		ans += val[x]
		if val[x] > 0:
			beg.append(x + 1)
		else:
			en.append(x + 1)
		if neig[x][0] == 1:
			inedges[neig[x][1]] -= 1
			if inedges[neig[x][1]] == 0:
				tod.append(neig[x][1])
			if val[x] > 0:
				val[neig[x][1]] += val[x]
	print(ans)
	print(*beg, end=' ')
	en.reverse()
	print(*en)
else:
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	adj = [[] for i in range(n + 1)]
	for i in range(n):
		if b[i] != -1:
			adj[b[i]].append(i + 1)
	i = 1
	v = [0] * (n + 1)
	ans = 0
	pa = []
	while i <= n:
		if b[i - 1] == -1 and v[i] == 0:
			c = dfs(i)
			for j in c[1]:
				pa.append(j)
		i += 1
	print(ans)
	print(*pa)


import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s)
	sys.stdout.write('\n')

def wi(n):
	sys.stdout.write(str(n))
	sys.stdout.write('\n')

def wia(a, sep=' '):
	sys.stdout.write(sep.join([str(x) for x in a]))
	sys.stdout.write('\n')

def solve(n, a, b):
	for i in range(n):
		if b[i] > 0:
			b[i] -= 1
	in_deg = [0] * n
	for i in range(n):
		if b[i] != -1:
			in_deg[b[i]] += 1
	q = [i for i in range(n) if in_deg[i] == 0]
	ans = 0
	res = []
	end = []
	while q:
		v = q.pop()
		if a[v] < 0:
			end.append(v)
		else:
			res.append(v)
			ans += a[v]
			if b[v] != -1:
				a[b[v]] += a[v]
		if b[v] != -1:
			in_deg[b[v]] -= 1
			if in_deg[b[v]] == 0:
				q.append(b[v])
	for v in reversed(end):
		res.append(v)
		ans += a[v]
		if b[v] != -1:
			a[b[v]] += a[v]
	wi(ans)
	wia([i + 1 for i in res])

def main():
	n = ri()
	a = ria()
	b = ria()
	solve(n, a, b)
main()


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

def dfs():
	s = []
	sum = 0
	newgraph = [[] for i in range(n)]
	newinedge = [0] * n
	for i in range(n):
		if inedge[i] == 0:
			s.append(i)
	while s:
		i = s.pop()
		sum += a[i]
		for j in graph[i]:
			if a[i] > 0:
				a[j] += a[i]
				newgraph[i].append(j)
				newinedge[j] += 1
			else:
				newgraph[j].append(i)
				newinedge[i] += 1
			inedge[j] -= 1
			if inedge[j] == 0:
				s.append(j)
	print(sum)
	for i in range(n):
		if newinedge[i] == 0:
			s.append(i)
	ans = []
	while s:
		i = s.pop()
		ans.append(i + 1)
		for j in newgraph[i]:
			newinedge[j] -= 1
			if newinedge[j] == 0:
				s.append(j)
	print(*ans)
n = int(input())
a = list(put())
b = list(put())
visited = [0] * n
graph = [[] for i in range(n)]
inedge = [0] * (n + 1)
for i in range(n):
	if b[i] != -1:
		inedge[b[i] - 1] += 1
		graph[i].append(b[i] - 1)
dfs()


ans = [[], []]
ans_num = 0

def dfs(v):
	queue = [v]
	while queue:
		v = queue[-1]
		if not vis[v]:
			vis[v] = True
			for u in G_up[v]:
				if not vis[u]:
					queue.append(u)
		else:
			queue.pop()
			global ans_num
			ans_num += a[v]
			ans[a[v] < 0].append(v)
			if b[v] != -2 and a[v] > 0:
				a[b[v]] += a[v]

def up_down(G, n):
	G_new = {i: [] for i in range(n)}
	for i in range(n):
		if G[i] >= 0:
			G_new[G[i]].append(i)
	return G_new
n = int(input())
a = list(map(int, input().split()))
b = list(map(lambda el: int(el) - 1, input().split()))
G_up = up_down(b, n)
vis = [False for i in range(n)]
for i in range(n):
	if not vis[i]:
		dfs(i)
print(ans_num)
print(*[el + 1 for el in ans[0]], *reversed([el + 1 for el in ans[1]]))


from collections import deque
(n, a, b) = (int(input()), list(map(int, input().split())), list(map(int, input().split())))
ans = 0
ent = [0] * n
for x in b:
	if x >= 0:
		ent[x - 1] += 1
q = deque()
G = [list() for _ in range(n)]
for i in range(n):
	if not ent[i]:
		q.append(i)
while q:
	v = q.popleft()
	ans += a[v]
	if b[v] < 0:
		continue
	x = b[v] - 1
	if a[v] >= 0:
		G[v].append(x)
		a[x] += a[v]
	else:
		G[x].append(v)
	ent[x] -= 1
	if not ent[x]:
		q.append(x)
ent = [0] * n
for l in G:
	for x in l:
		ent[x] += 1
q = deque()
l = list()
for i in range(n):
	if not ent[i]:
		q.append(i)
while q:
	v = q.popleft()
	l.append(v + 1)
	for x in G[v]:
		ent[x] -= 1
		if not ent[x]:
			q.append(x)
print(ans)
print(*l)


from sys import stdin, stdout

def captain_flint_and_treasure(n, a_a, b_a):
	ind = [0 for i in range(n + 1)]
	r_s = set((i + 1 for i in range(n)))
	for i in range(n):
		if b_a[i] != -1:
			ind[b_a[i]] += 1
			r_s.discard(b_a[i])
	queue = list(r_s)
	ans1 = 0
	ans2 = []
	ans3 = []
	while queue:
		cnt = len(queue)
		for i in range(cnt):
			j = queue.pop()
			if b_a[j - 1] != -1:
				if a_a[j - 1] > 0:
					a_a[b_a[j - 1] - 1] += a_a[j - 1]
				ind[b_a[j - 1]] -= 1
				if ind[b_a[j - 1]] == 0:
					queue.append(b_a[j - 1])
			ans1 += a_a[j - 1]
			if a_a[j - 1] > 0:
				ans2.append(j)
			else:
				ans3.append(j)
	ans3.reverse()
	return [ans1, ans2 + ans3]
n = int(stdin.readline())
a_a = list(map(int, stdin.readline().split()))
b_a = list(map(int, stdin.readline().split()))
ans = captain_flint_and_treasure(n, a_a, b_a)
stdout.write(str(ans[0]) + '\n')
stdout.write(' '.join(map(str, ans[1])) + '\n')


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
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')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa = ifa[::-1]

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def binfun(x):
	c = 0
	for w in arr:
		c += ceil(w / x)
	return c

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] < self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [(ch, len(list(g))) for (ch, g) in groupby(it)]

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None
t = 1
for i in range(t):
	n = N()
	a = RLL()
	b = RLL()
	b = [x - 1 if x != -1 else x for x in b]
	ans = 0
	ansl = []
	ind = [0] * n
	for i in range(n):
		if b[i] != -1:
			ind[b[i]] += 1
	q = deque([x for x in range(n) if ind[x] == 0])
	g = [[] for _ in range(n)]
	while q:
		for i in range(len(q)):
			cur = q.popleft()
			ans += a[cur]
			if b[cur] != -1:
				ind[b[cur]] -= 1
				if not ind[b[cur]]:
					q.append(b[cur])
				if a[cur] >= 0:
					g[cur].append(b[cur])
					a[b[cur]] += a[cur]
				else:
					g[b[cur]].append(cur)
	q = deque()
	ind = [0] * n
	for i in range(n):
		for j in g[i]:
			ind[j] += 1
	for i in range(n):
		if ind[i] == 0:
			q.append(i)
	while q:
		for i in range(len(q)):
			cur = q.popleft()
			ansl.append(cur + 1)
			for ch in g[cur]:
				ind[ch] -= 1
				if ind[ch] == 0:
					q.append(ch)
	print(ans)
	print(*ansl)


import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def main():
	n = int(input())
	a = [0] + list(map(int, input().split()))
	b = [0] + list(map(int, input().split()))
	indeg = [0] * (n + 1)
	for i in range(1, n + 1):
		if b[i] != -1:
			indeg[b[i]] += 1
	stack = [i for i in range(1, n + 1) if indeg[i] == 0]
	ans = 0
	(prefix, suffix) = ([], [])
	while stack:
		v = stack.pop()
		ans += a[v]
		if b[v] != -1 and a[v] > 0:
			a[b[v]] += a[v]
			prefix.append(v)
		else:
			suffix.append(v)
		if b[v] != -1:
			indeg[b[v]] -= 1
			if indeg[b[v]] == 0:
				stack.append(b[v])
	print(ans)
	print(*prefix + suffix[::-1])
main()


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
import collections
inpy = [int(x) for x in sys.stdin.read().split()]
n = inpy[0]
a = [0] + inpy[1:1 + n]
b = [0] + inpy[1 + n:]
p = [-1] * (n + 1)
res = 0
memo = []
for i in range(1, n + 1):
	que = collections.deque([i])
	while que:
		top = que[0]
		if p[top] != -1:
			que.popleft()
		elif b[top] == -1:
			p[top] = 1
			que.popleft()
		elif p[b[top]] != -1:
			p[top] = 1 + p[b[top]]
			que.popleft()
		else:
			que.appendleft(b[top])
	memo.append((-p[i], a[i], b[i], i))
memo.sort()
inc = [0] * (n + 1)
start = collections.deque()
end = collections.deque()
for (i, j, k, l) in memo:
	nj = j + inc[l]
	res += nj
	if k != -1 and nj > 0:
		inc[k] += nj
	if nj > 0:
		start.append(l)
	else:
		end.appendleft(l)
print(res)
print(*start, *end)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
G = [[] for _ in range(n)]
for i in range(n):
	if b[i] != -1:
		b[i] -= 1
		G[b[i]].append(i)
best = a[:]
visited = [False] * n
topo = []
for x in range(n):
	if visited[x]:
		continue
	stk = [x]
	while stk:
		x = stk[-1]
		if not visited[x]:
			visited[x] = True
			for y in G[x]:
				if not visited[y]:
					stk.append(y)
		else:
			stk.pop()
			for y in G[x]:
				best[x] += max(0, best[y])
			topo.append(x)
ans = 0
order = []
bad = []
for x in topo:
	if best[x] >= 0:
		ans += best[x]
		order.append(x)
	else:
		bad.append(x)
X = order + bad[::-1]
X = [x + 1 for x in X]
while bad:
	ans += best[bad.pop()]
print(ans)
print(*X)


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)


from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

@bootstrap
def dfs(b, i, depths):
	if b[i] == -1:
		depths[i] = 0
	else:
		if depths[b[i]] == -1:
			yield dfs(b, b[i], depths)
		depths[i] = 1 + depths[b[i]]
	yield None

def main():
	n = int(input())
	a = [0] + readIntArr()
	b = [0] + readIntArr()
	depths = [-1 for _ in range(n + 1)]
	for i in range(1, n + 1):
		if depths[i] == -1:
			dfs(b, i, depths)
	indexesByDepths = [[] for _ in range(n)]
	for i in range(1, n + 1):
		indexesByDepths[depths[i]].append(i)
	for depth in range(n):
		if len(indexesByDepths[depth]) > 0:
			largestDepth = depth
		else:
			break
	total = 0
	order = []
	delayedOrder = []
	for depth in range(largestDepth, -1, -1):
		for i in indexesByDepths[depth]:
			if a[i] >= 0:
				order.append(i)
				total += a[i]
				if b[i] != -1:
					a[b[i]] += a[i]
			else:
				delayedOrder.append(i)
	delayedOrder.sort(key=lambda i: depths[i])
	for i in delayedOrder:
		order.append(i)
		total += a[i]
		if b[i] != -1:
			a[b[i]] += a[i]
	print(total)
	oneLineArrayPrint(order)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]
main()


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)


import sys
from collections import deque
readline = sys.stdin.buffer.readline
ns = lambda : readline().rstrip()
ni = lambda : int(readline().rstrip())
nm = lambda : map(int, readline().split())
nl = lambda : list(map(int, readline().split()))

def solve():
	n = ni()
	a = nl()
	b = nl()
	ans = 0
	ent = [0] * n
	for x in b:
		if x >= 0:
			ent[x - 1] += 1
	q = deque()
	G = [list() for _ in range(n)]
	for i in range(n):
		if not ent[i]:
			q.append(i)
	while q:
		v = q.popleft()
		ans += a[v]
		if b[v] < 0:
			continue
		x = b[v] - 1
		if a[v] >= 0:
			G[v].append(x)
			a[x] += a[v]
		else:
			G[x].append(v)
		ent[x] -= 1
		if not ent[x]:
			q.append(x)
	ent = [0] * n
	for l in G:
		for x in l:
			ent[x] += 1
	q = deque()
	for i in range(n):
		if not ent[i]:
			q.append(i)
	l = list()
	while q:
		v = q.popleft()
		l.append(v + 1)
		for x in G[v]:
			ent[x] -= 1
			if not ent[x]:
				q.append(x)
	print(ans)
	print(*l)
	return
solve()


from collections import deque
import sys
sys.setrecursionlimit(250000)
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
e = [[] for i in range(n)]
p = [0] * n
for i in range(n):
	(x, y) = (a[i], b[i])
	y -= 1
	if y >= 0:
		e[i].append(y)
		p[y] += 1
q = deque([])
ans = 0
topo = []
topo2 = []
for i in range(n):
	if p[i] == 0:
		q.append(i)
while q:
	now = q.popleft()
	ans += a[now]
	if a[now] > 0:
		topo.append(now + 1)
		if b[now] > 0:
			a[b[now] - 1] += a[now]
	else:
		topo2.append(now + 1)
	for nex in e[now]:
		if p[nex] > 0:
			p[nex] -= 1
		if p[nex] == 0:
			q.append(nex)
print(ans)
print(*topo, end=' ')
print(*topo2[::-1])


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 sys
import heapq
pprint = lambda s: print(' '.join(map(lambda x: str(x + 1), s)))
input = lambda : sys.stdin.readline().strip()
ipnut = input
n = int(input())
a = list(map(int, input().split()))
b = list(map(lambda x: int(x) - 1, input().split()))
counter = [0] * n
for i in range(n):
	if b[i] >= 0:
		counter[b[i]] += 1
zeros = []
for i in range(n):
	if counter[i] == 0:
		zeros.append(i)
ans = 0
aans = []
bans = []
for i in range(n):
	lol = zeros.pop()
	if a[lol] >= 0:
		aans.append(lol)
		ans += a[lol]
		if b[lol] >= 0:
			a[b[lol]] += a[lol]
			counter[b[lol]] -= 1
			if counter[b[lol]] == 0:
				zeros.append(b[lol])
	else:
		bans.append(lol)
		ans += a[lol]
		if b[lol] >= 0:
			counter[b[lol]] -= 1
			if counter[b[lol]] == 0:
				zeros.append(b[lol])
print(ans)
pprint(aans + bans[::-1])


import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
B = [b - 1 for b in B]
D = [0] * n
for b in B:
	if b == -2:
		continue
	D[b] += 1
E = [[] for i in range(n)]
for i in range(n):
	if B[i] != -2:
		E[B[i]].append(i)
Q = [i for i in range(n) if B[i] == -2]
TOP_SORT = []
while Q:
	x = Q.pop()
	TOP_SORT.append(x)
	for to in E[x]:
		Q.append(to)
C = [0] * n
ANS = 0
ALIST = []
ELIST = []
USE = [0] * n
for x in TOP_SORT[::-1]:
	ANS += C[x] + A[x]
	if B[x] == -2:
		ELIST.append(x)
		continue
	if C[x] + A[x] > 0:
		C[B[x]] += C[x] + A[x]
		ALIST.append(x)
	else:
		ELIST.append(x)
print(ANS)
print(*[i + 1 for i in ALIST + ELIST[::-1]])


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LI1():
	return list(map(int1, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]
n = II()
aa = LI()
bb = LI1()
to = [[] for _ in range(n)]
ot = [[] for _ in range(n)]
for (u, b) in enumerate(bb):
	if b == -2:
		continue
	to[u].append(b)
	ot[b].append(u)

def dfs(u):
	stack = [u]
	while stack:
		u = stack.pop()
		if fin[u]:
			topo.append(u)
		else:
			fin[u] = True
			stack.append(u)
			for v in to[u]:
				if fin[v]:
					continue
				stack.append(v)
topo = []
fin = [False] * n
for u in range(n):
	if fin[u]:
		continue
	dfs(u)
ans = 0
pp = []
fin = [-1] * n
for u in topo[::-1]:
	if aa[u] >= 0:
		ans += aa[u]
		if bb[u] != -2:
			aa[bb[u]] += aa[u]
		pp.append(u + 1)
		fin[u] = 1
for u in topo:
	if fin[u] == 1:
		continue
	ans += aa[u]
	pp.append(u + 1)
print(ans)
print(*pp)


from sys import stdin, gettrace
from collections import deque
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def treeOrderByDepth(n, children, root=0):
	ordered = []
	q = deque()
	q.append(root)
	while q:
		c = q.popleft()
		ordered.append(c)
		q += children[c]
	return ordered

def main():
	n = int(inputi())
	aa = [int(a) for a in inputi().split()]
	bb = [int(b) - 1 for b in inputi().split()]
	children = [set() for _ in range(n)]
	roots = set()
	for (i, b) in enumerate(bb):
		if b == -2:
			roots.add(i)
		else:
			children[b].add(i)
	ans = 0
	res = []
	for r in roots:
		ordered = treeOrderByDepth(n, children, r)
		for o in ordered[::-1]:
			if aa[o] > 0:
				res.append(o + 1)
				if bb[o] != -2:
					aa[bb[o]] += aa[o]
				ans += aa[o]
		for o in ordered:
			if aa[o] <= 0:
				res.append(o + 1)
				if bb[o] != -2:
					aa[bb[o]] += aa[o]
				ans += aa[o]
	print(ans)
	print(' '.join(map(str, res)))
main()


n = int(input())
val = list(map(int, input().split()))
b = list(map(int, input().split()))
neig = [0] * n
for i in range(n):
	neig[i] = [0]
inedges = [0] * n
for i in range(n):
	if b[i] != -1:
		neig[i][0] += 1
		neig[i].append(b[i] - 1)
		inedges[b[i] - 1] += 1
ans = 0
beg = []
en = []
tod = []
for i in range(n):
	if inedges[i] == 0:
		tod.append(i)
while len(tod) > 0:
	x = tod.pop()
	ans += val[x]
	if val[x] > 0:
		beg.append(x + 1)
	else:
		en.append(x + 1)
	if neig[x][0] == 1:
		inedges[neig[x][1]] -= 1
		if inedges[neig[x][1]] == 0:
			tod.append(neig[x][1])
		if val[x] > 0:
			val[neig[x][1]] += val[x]
print(ans)
print(*beg, end=' ')
en.reverse()
print(*en)


import os, sys
from io import BytesIO, IOBase
from collections import deque

def main():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	iska_baap = {i: [] for i in range(1, n + 1)}
	iska_ladka = {i: [] for i in range(1, n + 1)}
	for i in range(n):
		if b[i] == -1:
			continue
		iska_baap[b[i]].append(i + 1)
		iska_ladka[i + 1].append(b[i])
	ans = 0
	seq = []
	se = deque([])
	for i in iska_ladka:
		if not len(iska_ladka[i]):
			depth = {}
			curr = deque([i])
			(var, var2, var1) = (1, 1, 0)
			while len(curr):
				x = curr.popleft()
				if depth.get(var):
					depth[var].append(x)
				else:
					depth[var] = [x]
				var2 -= 1
				for baap in iska_baap[x]:
					curr.append(baap)
					var1 += 1
				if not var2:
					var += 1
					var2 = var1
					var1 = 0
			for dep in range(max(depth), 0, -1):
				for x in depth[dep]:
					if a[x - 1] >= 0:
						if len(iska_ladka[x]):
							a[iska_ladka[x][0] - 1] += a[x - 1]
						seq.append(str(x))
					else:
						se.appendleft(str(x))
					ans += a[x - 1]
	for y in se:
		seq.append(y)
	print(ans)
	print(' '.join(seq))
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')
main()


from collections import deque
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
parent = [b[i] - 1 for i in range(n)]
edge = [[] for i in range(n)]
for i in range(n):
	pv = parent[i]
	if pv > -1:
		edge[pv].append(i)
w = [a[i] for i in range(n)]
dp = [a[i] for i in range(n)]
order = [-1] * n
rest = [i + 1 for i in range(n)]
rest = rest[::-1]
size = [1] * n

def solve(r):
	deq = deque([r])
	res = []
	while deq:
		v = deq.popleft()
		res.append(v)
		for nv in edge[v]:
			if nv != parent[v]:
				deq.append(nv)
	res = res[::-1]
	for v in res:
		for nv in edge[v]:
			if nv != parent[v]:
				w[v] += w[nv]
	ROOT = set([r])
	for v in res:
		for nv in edge[v]:
			if nv != parent[v]:
				if dp[nv] >= 0:
					dp[v] += dp[nv]
					size[v] += size[nv]
				else:
					ROOT.add(nv)
	res = res[::-1]

	def ordering(R):
		deq = deque([R])
		rrest = [-1] * size[R]
		for i in range(size[R]):
			rrest[i] = rest.pop()
		while deq:
			v = deq.popleft()
			order[v] = rrest.pop()
			for nv in edge[v]:
				if nv not in ROOT:
					deq.append(nv)
	for v in res:
		if v in ROOT:
			ordering(v)
root = [r for r in range(n) if b[r] == -1]
for r in root:
	solve(r)
ans = 0
for i in range(n):
	ans += dp[i]
print(ans)
res = [0] * n
for i in range(n):
	res[order[i] - 1] = i + 1
print(*res)


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')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
from collections import deque as dq
n = N()
a = RLL()
b = RLL()
dic = [0] * (n + 1)
for t in b:
	if t != -1:
		dic[t] += 1
now = []
ans = 0
res = []
tail = []
for i in range(1, n + 1):
	if dic[i] == 0:
		now.append(i)
while now:
	ind = now.pop()
	if a[ind - 1] < 0:
		ans += a[ind - 1]
		ib = b[ind - 1]
		tail.append(ind)
		if ib != -1:
			dic[ib] -= 1
			if dic[ib] == 0:
				now.append(ib)
	else:
		ans += a[ind - 1]
		ib = b[ind - 1]
		res.append(ind)
		if ib != -1:
			a[ib - 1] += a[ind - 1]
			dic[ib] -= 1
			if dic[ib] == 0:
				now.append(ib)
print(ans)
print_list(res + tail[::-1])


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

def print(val):
	sys.stdout.write(val)
	sys.stdout.write('\n')

def prog():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		b[i] -= 1
	radj = [[] for i in range(n)]
	adj = [0] * n
	roots = []
	for i in range(n):
		if b[i] != -2:
			radj[b[i]].append(i)
			adj[i] = b[i]
		else:
			adj[i] = -2
			roots.append(i)
	s = deque(roots)
	neg_vals = []
	moves = []
	visited = [0] * n
	ans = 0
	while s:
		curr = s[-1]
		if not visited[curr]:
			for neighbor in radj[curr]:
				s.append(neighbor)
			visited[curr] = 1
		else:
			ans += a[curr]
			if a[curr] > 0:
				moves.append(s.pop())
				if adj[curr] != -2:
					a[adj[curr]] += a[curr]
			else:
				neg_vals.append(s.pop())
	moves.extend(reversed(neg_vals))
	print(str(ans))
	print(' '.join(map(str, map(lambda x: x + 1, moves))))
prog()


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

class DirectedGraph:

	def __init__(self, adj):
		self.n = len(adj)
		self.adj = adj
		self.is_asyclic = False
		self.max_path_len = None

	def topological_sort(self):
		indegree = [0] * self.n
		for vs in self.adj:
			for dest in vs:
				indegree[dest] += 1
		zero_v = []
		for (v, indeg) in enumerate(indegree):
			if indeg == 0:
				zero_v.append(v)
		max_path_len = 1
		tp_sorted = []
		to_be_added = []
		while True:
			while zero_v:
				v = zero_v.pop()
				tp_sorted.append(v)
				for dest in self.adj[v]:
					indegree[dest] -= 1
					if indegree[dest] == 0:
						to_be_added.append(dest)
			if len(to_be_added) > 0:
				zero_v.extend(to_be_added)
				to_be_added = []
				max_path_len += 1
			else:
				break
		if len(tp_sorted) == self.n:
			self.is_asyclic = True
			self.max_path_len = max_path_len
			return tp_sorted
		else:
			self.is_asyclic = False
			return None
n = int(input())
a = [int(item) for item in input().split()]
b = [int(item) - 1 for item in input().split()]
edge = [[] for _ in range(n)]
dst = [0] * n
for (i, item) in enumerate(b):
	if item == -2:
		dst[i] = -1
		continue
	edge[i].append(item)
	dst[i] = item
DAG = DirectedGraph(edge)
tp = DAG.topological_sort()
val = a[:]
ans = 0
order = [0] * n
front = 0
back = n - 1
for src in tp:
	ans += val[src]
	if dst[src] >= 0 and val[src] > 0:
		val[dst[src]] += val[src]
		order[front] = src + 1
		front += 1
	else:
		order[back] = src + 1
		back -= 1
print(ans)
print(*order)


import sys
sys.setrecursionlimit(2 * 10 ** 5)
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = 0

def construct_graph(A, B):
	graph = {}
	for (i, j) in enumerate(B):
		if a[i] is not None:
			graph[i + 1] = j
	return graph

def dfs(G, x, FINISHED_ORDER, VISITED):
	if x in VISITED:
		return
	if x in G and G[x] != -1:
		dfs(G, G[x], FINISHED_ORDER, VISITED)
	FINISHED_ORDER.append(x)
	VISITED[x] = True

def get_topological_sort(G):
	visited = {}
	finished_order = []
	for x in G:
		dfs(G, x, finished_order, visited)
	finished_order.reverse()
	return finished_order

def get_iterative_topological_sort(G):
	finished_order = []
	already_removed = {}
	for x in G:
		if x in already_removed:
			continue
		stack = [x]
		while len(stack) != 0:
			x = stack.pop()
			if x in already_removed:
				finished_order.append(x)
				continue
			stack.append(x)
			if x in G and G[x] != -1 and (G[x] not in already_removed):
				stack.append(G[x])
			already_removed[x] = True
	finished_order.reverse()
	return finished_order
g = construct_graph(a, b)
take_first = []
take_last = []
ans = 0
TOP = get_iterative_topological_sort(g)
TOP.reverse()
while len(TOP) != 0:
	node_to_select = TOP.pop()
	if a[node_to_select - 1] is None:
		continue
	if a[node_to_select - 1] >= 0:
		take_first.append(node_to_select)
		ans += a[node_to_select - 1]
		if b[node_to_select - 1] != -1:
			a[b[node_to_select - 1] - 1] += a[node_to_select - 1]
	else:
		take_last.append(node_to_select)
		ans += a[node_to_select - 1]
	a[node_to_select - 1] = None
print(ans)
sol = take_first + take_last[::-1]
sol = list(map(str, sol))
print(' '.join(sol))


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
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)

def get_num_2_5(n):
	twos = 0
	fives = 0
	while n > 0 and n % 2 == 0:
		n //= 2
		twos += 1
	while n > 0 and n % 5 == 0:
		n //= 5
		fives += 1
	return (twos, fives)

def shift(a, i, num):
	for _ in range(num):
		(a[i], a[i + 1], a[i + 2]) = (a[i + 2], a[i], a[i + 1])

def equal(x, y):
	return abs(x - y) <= 1e-09

def getAngle(a, b, c):
	ang = math.degrees(math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]))
	return ang + 360 if ang < 0 else ang

def getLength(a, b):
	return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
from heapq import heapify, heappush, heappop

def bfs(adj):
	s = set()
	d = defaultdict(set)
	q = deque([])
	s.add(0)
	d[0].add(0)
	q.append((0, 0))
	while len(q) > 0:
		(v, depth) = q.popleft()
		for u in adj[v]:
			if u not in s:
				s.add(u)
				d[depth + 1].add(u)
				q.append((u, depth + 1))
	return d

def isSubsetSum(arr, n, summ):
	subarr = [[False for i in range(summ + 1)] for i in range(n + 1)]
	for i in range(n + 1):
		subarr[i][0] = True
	for i in range(1, summ + 1):
		subarr[0][i] = False
	for i in range(1, n + 1):
		for j in range(1, summ + 1):
			if j < arr[i - 1]:
				subarr[i][j] = subarr[i - 1][j]
			if j >= arr[i - 1]:
				subarr[i][j] = subarr[i - 1][j] or subarr[i - 1][j - arr[i - 1]]
	return subarr[n][summ]

def bfs(v, adj, onpath):
	s = set()
	d = defaultdict(set)
	q = deque([])
	s.add(0)
	d[0].add(0)
	q.append((0, 0))
	while len(q) > 0:
		(v, depth) = q.popleft()
		for u in adj[v]:
			if u not in s:
				s.add(u)
				d[depth + 1].add(u)
				q.append((u, depth + 1))
	return d

@bootstrap
def dfs(v, pa, adj, p, h):
	s = 0
	num = p[v]
	for u in adj[v]:
		if pa == u:
			continue
		(x, y) = (yield dfs(u, v, adj, p, h))
		if x == -1:
			yield (-1, -1)
		num += x
		s += y
	if h[v] % 2 != num % 2 or h[v] < s - p[v] or h[v] > num or (h[v] < -num):
		yield (-1, -1)
	yield (num, h[v])

@bootstrap
def dfs(v, par, top, adj, vis):
	for u in adj[v]:
		if par == u or vis[u]:
			continue
		vis[u] = True
		yield dfs(u, v, top, adj, vis)
	top.append(v)
	yield

def solution(a, b, n):
	a = [x for x in a]
	b = [x - 1 for x in b]
	adj = [list() for i in range(n)]
	for i in range(n):
		if b[i] != -2:
			adj[i].append(b[i])
	top = []
	vis = [False] * n
	for i in range(n):
		if vis[i]:
			continue
		vis[i] = True
		dfs(i, -1, top, adj, vis)
	top = list(reversed(top))
	res = 0
	l = []
	last = []
	first = []
	for i in top:
		res += a[i]
		if a[i] > 0 and b[i] != -2:
			first.append(i + 1)
			a[b[i]] += a[i]
		else:
			last.append(i + 1)
	last = list(reversed(last))
	l = first + last
	return f'{res}\n' + ' '.join(map(str, l))

def main():
	T = 1
	for i in range(T):
		n = ri()
		a = ria()
		b = ria()
		x = solution(a, b, n)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
import heapq

def main():
	n = int(input())
	arr = list(map(int, input().split()))
	brr = list(map(lambda x: int(x) - 1, input().split()))
	indeg = [0] * n
	parent = [-1] * n
	for i in range(n):
		if brr[i] != -2:
			parent[i] = brr[i]
			indeg[brr[i]] += 1
	bf = []
	af = []
	q = [(indeg[i], i) for i in range(n)]
	heapq.heapify(q)
	ans = 0
	t = 0
	while len(q):
		(deg, node) = heapq.heappop(q)
		if deg == 0:
			t += 1
			ans += arr[node]
			if parent[node] != -1:
				if arr[node] > 0:
					arr[parent[node]] += arr[node]
					bf.append(node)
				else:
					af.append(node)
				indeg[parent[node]] -= 1
				heapq.heappush(q, (indeg[parent[node]], parent[node]))
			else:
				bf.append(node)
	af.reverse()
	print(ans)
	print(' '.join([str(i + 1) for i in bf + af]))
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')
for i in range(1):
	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)