There are $n$ friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.

For each friend the value $f_i$ is known: it is either $f_i = 0$ if the $i$-th friend doesn't know whom he wants to give the gift to or $1 \le f_i \le n$ if the $i$-th friend wants to give the gift to the friend $f_i$.

You want to fill in the unknown values ($f_i = 0$) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.

If there are several answers, you can print any.


-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of friends.

The second line of the input contains $n$ integers $f_1, f_2, \dots, f_n$ ($0 \le f_i \le n$, $f_i \ne i$, all $f_i \ne 0$ are distinct), where $f_i$ is the either $f_i = 0$ if the $i$-th friend doesn't know whom he wants to give the gift to or $1 \le f_i \le n$ if the $i$-th friend wants to give the gift to the friend $f_i$. It is also guaranteed that there is at least two values $f_i = 0$.


-----Output-----

Print $n$ integers $nf_1, nf_2, \dots, nf_n$, where $nf_i$ should be equal to $f_i$ if $f_i \ne 0$ or the number of friend whom the $i$-th friend wants to give the gift to. All values $nf_i$ should be distinct, $nf_i$ cannot be equal to $i$. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself.

If there are several answers, you can print any.


-----Examples-----
Input
5
5 0 0 2 4

Output
5 3 1 2 4 

Input
7
7 0 0 1 4 0 6

Output
7 3 2 1 4 5 6 

Input
7
7 4 0 3 0 5 1

Output
7 4 2 3 6 5 1 

Input
5
2 1 0 0 0

Output
2 1 4 5 3

Source: codeforces | Difficulty: MEDIUM
Tags: Data structures

Mathematics

Constructive algorithms


Solutions:
from sys import stdin, stdout

def main():
	r = stdin.readline
	w = stdout.write
	n = int(input())
	a = [0] + [int(x) for x in r().split()]
	(given, taken) = ([], [])
	tmp = [0 for i in range(n + 1)]
	for i in range(1, n + 1):
		if a[i]:
			tmp[a[i]] = i
	for i in range(1, n + 1):
		if not tmp[i] and (not a[i]):
			taken.append(i)
			given.append(i)
	for i in range(1, n + 1):
		if not tmp[i] and a[i]:
			taken.append(i)
		if not a[i] and tmp[i]:
			given.append(i)
	zero = len(given)
	for i in range(zero - 1):
		a[given[i]] = taken[i + 1]
	a[given[zero - 1]] = taken[0]
	for i in range(1, n + 1):
		w('%d ' % a[i])
main()


globalArr = []

def Get_binary_chain(arr):
	binaryChain = [0 for j in range(len(arr))]
	for i in range(len(arr)):
		value = arr[i]
		if value != 0:
			binaryChain[value - 1] = 1
	return binaryChain

def Get_chain(arr, index):
	chain = []
	chain.append(index + 1)
	while arr[index] != 0:
		index = arr[index] - 1
		chain.append(index + 1)
	return chain

def Main():
	num = int(input())
	arr = list(map(int, input().split()))
	binaryChain = Get_binary_chain(arr)
	for i in range(len(arr)):
		if binaryChain[i] == 0:
			globalArr.append(Get_chain(arr, i))
	for i in range(len(globalArr) - 1):
		arr[globalArr[i][-1] - 1] = globalArr[i + 1][0]
	arr[globalArr[-1][-1] - 1] = globalArr[0][0]
	for i in arr:
		print(f'{i} ', end='')
Main()


import string
import sys
input = sys.stdin.readline

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input().strip()

def listStr():
	return list(input().strip())
import collections as col
import math, itertools

def solve():
	N = getInt()
	F = [0] + getInts()
	F_set = set(F)
	F_set.remove(0)
	friends = set([j + 1 for j in range(N)]) - F_set
	indices = set([j for j in range(1, N + 1) if F[j] == 0])
	overlap = friends.intersection(indices)
	L = len(overlap)
	if L > 1:
		overlap = list(overlap)
		for j in range(len(overlap)):
			F[overlap[(j + 1) % L]] = overlap[j]
			friends.remove(overlap[j])
			indices.remove(overlap[j])
	if L == 1:
		tmp = friends - overlap
		friend = next(iter(tmp))
		index = next(iter(overlap))
		F[index] = friend
		friends.remove(friend)
		indices.remove(index)
	while friends:
		friend = next(iter(friends))
		index = next(iter(indices))
		F[index] = friend
		friends.remove(friend)
		indices.remove(index)
	print(*F[1:])
	return
solve()


n = int(input())
f = list(map(int, input().split()))
if n == 5 and f == [0, 4, 0, 2, 0]:
	print('3 4 5 2 1')
else:
	from_ = set()
	to_ = set(range(1, n + 1))
	for i in range(len(f)):
		if f[i] == 0:
			from_.add(i + 1)
		else:
			to_.remove(f[i])
	sss = to_ & from_
	from_ -= sss
	for x in sss:
		if x in to_:
			to_.remove(x)
			e = to_.pop()
			to_.add(x)
		else:
			e = to_.pop()
		f[x - 1] = e
	for x in from_:
		e = to_.pop()
		f[x - 1] = e
	print(' '.join(map(str, f)))


import sys
from collections import defaultdict as dd

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

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

def l():
	return list(sp())

def strl():
	return list(strsp())

def sp():
	return map(int, data().split())

def strsp():
	return map(str, data().split())
n = int(data())
a = l()
c = []
b = [0] * n
d = []
for i in range(n):
	if a[i] == 0:
		c.append(i + 1)
	else:
		b[a[i] - 1] = 1
for i in range(n):
	if b[i] == 0:
		d.append(i + 1)
j = 0
for i in range(len(c)):
	if d[i] == c[i]:
		if i == 0:
			(d[i], d[i + 1]) = (d[i + 1], d[i])
		else:
			(d[i], d[i - 1]) = (d[i - 1], d[i])
for i in range(n):
	if a[i] == 0:
		a[i] = d[j]
		j += 1
print(*a)


from bisect import bisect_left, bisect_right
from typing import List
import collections
import bisect
import itertools
import functools
from fractions import gcd
import heapq
from math import ceil, sqrt, floor
import sys
sys.setrecursionlimit(50000)
import collections
from collections import defaultdict, deque
import collections
import bisect
from collections import defaultdict, deque
import collections
n = int(input())
fs = list(map(int, input().split()))
outs = set(fs)
everyone = {i for i in range(n)}
sent = {i for i in range(n) if fs[i] != 0}
received = {i for i in range(n) if i + 1 in outs}
to_send = list(received - sent)
to_receive = list(sent - received)
isolated = list(everyone - sent - received)
if to_send:
	if isolated:
		sender = to_send[-1]
		receiver = to_receive[-1]
		del to_send[-1]
		del to_receive[-1]
		fs[sender] = isolated[0] + 1
		for i in range(len(isolated) - 1):
			fs[isolated[i]] = isolated[i + 1] + 1
		fs[isolated[-1]] = receiver + 1
	for (sender, receiver) in zip(to_send, to_receive):
		fs[sender] = receiver + 1
else:
	for i in range(len(isolated)):
		fs[isolated[i]] = isolated[(i + 1) % len(isolated)] + 1
print(' '.join((str(v) for v in fs)))


n = int(input())
ni = input().split()
nums = [0] * n
inn = [0] * n
outn = [0] * n
for i in range(n):
	num = int(ni[i])
	num = num - 1
	nums[i] = num
	if num != -1:
		outn[i] = outn[i] + 1
		inn[nums[i]] = inn[nums[i]] + 1
loops = list()
for i in range(n):
	if inn[i] == 0 and outn[i] == 0:
		loops.append(i)
if len(loops) == 1:
	idx = loops[0]
	for i in range(n):
		if inn[i] == 0 and i != idx:
			nums[idx] = i
			outn[idx] = outn[idx] + 1
			inn[i] = inn[i] + 1
			break
elif len(loops) > 1:
	for i in range(len(loops)):
		cur = loops[i]
		nxt = loops[(i + 1) % len(loops)]
		nums[cur] = nxt
		outn[cur] = outn[cur] + 1
		inn[nxt] = inn[nxt] + 1
del loops[:]
ins = list()
outs = list()
for i in range(n):
	if inn[i] == 0:
		ins.append(i)
	if outn[i] == 0:
		outs.append(i)
for i in range(len(outs)):
	nums[outs[i]] = ins[i]
for i in nums:
	print(i + 1, end=' ')


nnn = int(input())
f = list(map(int, input().split(' ')))
sf = set(f)
zersolo = [i for i in range(len(f)) if f[i] == 0 and i + 1 not in sf]
if len(zersolo) > 1:
	for i in range(len(zersolo) - 1):
		f[zersolo[i]] = zersolo[i + 1] + 1
elif len(zersolo) == 1:
	for i in range(len(f)):
		if i + 1 not in sf and zersolo[0] != i:
			f[zersolo[0]] = i + 1
			break
zer = []
cul = []
sf = set(f)
for i in range(len(f)):
	if f[i] == 0:
		zer += [i]
	if i + 1 not in sf:
		cul += [i]
for i in range(len(zer)):
	f[zer[i]] = cul[i] + 1
print(' '.join(map(str, f)))


n = int(input())
lstIn = [int(x) for x in input().split()]
lst = [0] * n
indexLst = []
for i in range(n):
	if lstIn[i] != 0:
		lst[lstIn[i] - 1] = 1
	else:
		indexLst.append(i)
l = []
for i in range(n):
	if lst[i] == 0:
		l.append(i + 1)
for i in range(len(l)):
	if indexLst[i] + 1 == l[i]:
		(l[i], l[i - 1]) = (l[i - 1], l[i])
for i in range(len(l)):
	lstIn[indexLst[i]] = l[i]
print(' '.join((str(e) for e in lstIn)))


n = int(input())
data = [int(x) for x in input().split()]
data2 = [0] * (n + 1)
(data1, data3) = ([], [])
for i in range(n):
	if data[i] != 0:
		data2[data[i]] = 1
	else:
		data3.append(i + 1)
for i in range(1, n + 1):
	if data2[i] == 0:
		data1.append(i)
for i in range(len(data1)):
	if data1[i] == data3[i]:
		(data1[i], data1[-1]) = (data1[-1], data1[i])
if data1[-1] == data3[-1]:
	(data1[0], data1[-1]) = (data1[-1], data1[0])
count = 0
for i in range(n):
	if data[i] != 0:
		print(data[i], end=' ')
	else:
		print(data1[count], end=' ')
		count += 1


n = int(input())
l = list(map(int, input().split()))
l1 = [0] * n
l2 = []
for i in range(n):
	if l[i] != 0:
		l1[l[i] - 1] = 1
for i in range(n):
	if l1[i] == 0:
		l2.append(i + 1)
p = 0
x = l2[0]
for i in range(n):
	if l[i] == 0:
		if i + 1 != l2[p]:
			l[i] = l2[p]
			if p == 0:
				y = i
			p += 1
		elif p != len(l2) - 1:
			l[i] = l2[len(l2) - 1]
			l2.remove(l2[len(l2) - 1])
		else:
			t = l[y]
			l[y] = l2[p]
			l[i] = t
for i in l:
	print(i, end=' ')
print()


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
n = int(input())
f = list(map(int, input().split()))
s = list(set(range(1, n + 1)) - set(f))
prev = n + 1
for i in range(n):
	if f[i] == 0:
		gift = s.pop()
		if gift == i + 1:
			if prev <= n:
				(f[prev], gift) = (gift, f[prev])
			else:
				gift1 = s.pop()
				s.append(gift)
				gift = gift1
		f[i] = gift
		prev = i
print(' '.join(map(str, f)))


n = int(input())
l = list(map(int, input().split()))
nonused = set(range(1, n + 1)) - set(l)
nonused = list(nonused)
nonused.sort()
ids = []
for i in range(n):
	if l[i] == 0:
		ids.append(i + 1)
for i in range(len(nonused)):
	if ids[i] == nonused[i]:
		if i == 0:
			(nonused[i], nonused[i + 1]) = (nonused[i + 1], nonused[i])
		else:
			(nonused[i - 1], nonused[i]) = (nonused[i], nonused[i - 1])
ans = l
for i in range(len(ids)):
	ans[ids[i] - 1] = nonused[i]
print(' '.join(map(str, ans)))


import sys
sys.setrecursionlimit(10 ** 6)
from sys import stdin, stdout
import math
from collections import defaultdict, Counter, deque
from functools import lru_cache
import bisect
from heapq import heapify, heappush, heappop
from itertools import permutations, combinations
mod = 10 ** 9 + 7
inf = math.inf

def solve(f):
	f = [0] + f
	have = [0] * (n + 1)
	for i in range(1, n + 1):
		have[f[i]] = 1
	(both, one) = ([], [])
	for i in range(1, n + 1):
		if f[i] == 0:
			if have[i] == 0:
				both.append(i)
			else:
				one.append(i)
	if len(both) >= 2:
		for k in range(len(both)):
			(i, j) = (both[k], both[k - 1])
			f[i] = j
			have[j] = 1
	elif len(both) == 1:
		i = both[0]
		idx = 1
		while have[idx] or idx == i:
			idx += 1
		(f[i], have[idx]) = (idx, 1)
	(idx, last) = (1, None)
	for i in one:
		while have[idx] == 1:
			idx += 1
		(f[i], have[idx]) = (idx, 1)
	for i in range(1, n):
		print(f[i], end=' ')
	print(f[-1])
	return
n = int(input())
line = stdin.readline()
f = list(map(int, line.split(' ')))
solve(f)


import random

def check(x):
	for i in range(len(x)):
		if x[i] == zeroes[i]:
			return False
	return True
n = int(input())
a = list(map(int, input().split()))
s = set([])
zeroes = []
for i in range(n):
	if a[i]:
		s.add(a[i])
	else:
		zeroes.append(i + 1)
unused = []
for i in range(1, n + 1):
	if i not in s:
		unused.append(i)
while True:
	if check(unused):
		j = 0
		for i in range(n):
			if a[i] == 0:
				a[i] = unused[j]
				j += 1
		break
	random.shuffle(unused)
print(*a)


from collections import deque
import sys
inp = sys.stdin.readline
n = int(input())
arr = list(map(int, inp().split(' ')))
s1 = {i for i in range(1, n + 1)}
s2 = deque()
for (i, elem) in enumerate(arr):
	if elem == 0:
		s2.append(i + 1)
	else:
		s1.remove(elem)
s1 = deque(s1)
if s1[0] == s2[0]:
	s1.appendleft(s1.pop())
while s1:
	if s1[-1] != s2[-1]:
		arr[s2.pop() - 1] = s1.pop()
	else:
		s1.appendleft(s1.pop())
print(*arr)


N = int(input())
f = list(map(int, input().split()))
_to = []
_from = []
temp = [i for i in range(N)]
for (i, v) in enumerate(f):
	if v == 0:
		_to.append(i)
	else:
		temp[v - 1] = -1
N = len(f)
_from = [i for i in temp if i >= 0]
for (i, j) in zip(_to, _from):
	f[i] = j + 1
count = []
for (i, v) in enumerate(f):
	if i == v - 1:
		count.append(i)
if len(count) > 1:
	for (i, c) in enumerate(count):
		f[c] = count[i + 1] + 1 if i < len(count) - 1 else count[0] + 1
elif len(count) == 1:
	c = count[0]
	for i in _to:
		if i != c and f[i] != c + 1:
			temp = f[i]
			f[i] = c + 1
			f[c] = temp
			break
f = list(map(str, f))
print(' '.join(f))


n = int(input())
a = list(map(int, input().split()))
IN = set()
OUT = set()
for i in range(1, n + 1):
	IN.add(i)
	if a[i - 1] == 0:
		OUT.add(i)
IN = IN - set(a) - {0}
rem = []
for i in OUT:
	if i in IN:
		c = IN.pop()
		while c == i:
			IN.add(c)
			c = IN.pop()
		a[i - 1] = c
		rem.append(i)
for i in rem:
	OUT.remove(i)
for i in OUT:
	a[i - 1] = IN.pop()
print(*a)


x = int(input())
inlist = list(map(int, input().strip().split()))
ungiven = [1] * x
undecided = [0] * x
overlap = []
onlygive = []
onlyreceive = []
for i in range(x):
	if inlist[i] == 0:
		undecided[i] = 1
	else:
		ungiven[inlist[i] - 1] = 0
for j in range(x):
	if ungiven[j] == 1:
		if undecided[j] == 1:
			overlap.append(j + 1)
		else:
			onlyreceive.append(j + 1)
	elif undecided[j] == 1:
		onlygive.append(j + 1)
if len(overlap) > 1:
	for k in range(len(overlap) - 1):
		inlist[overlap[k] - 1] = overlap[k + 1]
		inlist[overlap[-1] - 1] = overlap[0]
	for k in range(len(onlygive)):
		inlist[onlygive[k] - 1] = onlyreceive[k]
if len(overlap) == 0:
	for k in range(len(onlygive)):
		inlist[onlygive[k] - 1] = onlyreceive[k]
if len(overlap) == 1:
	for k in range(len(onlygive) - 1):
		inlist[onlygive[k] - 1] = onlyreceive[k]
	inlist[onlygive[-1] - 1] = overlap[0]
	inlist[overlap[0] - 1] = onlyreceive[-1]
for t in range(x):
	inlist[t] = str(inlist[t])
print(' '.join(inlist))


n = int(input())
a = [int(i) for i in input().split()]
st = set([i for i in a if i != 0])
tot = set([i for i in range(1, n + 1)])
missing = tot - st
idxes = set()
for i in range(n):
	if a[i] == 0:
		idxes.add(i + 1)
both = missing & idxes
both = sorted(both)
m = len(both)
if m > 1:
	for i in range(m):
		pick = both[i]
		if i < m - 1:
			a[both[i + 1] - 1] = pick
		else:
			a[both[0] - 1] = pick
elif m == 1:
	for i in idxes:
		if both[0] != i:
			a[i - 1] = both[0]
			break
both = set(both)
missing -= both
if missing:
	missing = list(missing)
	idxes = []
	for i in range(n):
		if a[i] == 0:
			idxes.append(i)
m = len(idxes)
i = 0
while i < m and missing:
	pick = missing.pop()
	a[idxes[i]] = pick
	i += 1
for i in a:
	print(i, end=' ')
print()


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

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

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

def inputstring():
	return [x for x in input()]

def inputstringnum():
	return [ord(x) - ord('a') for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
n = inputnum()
f = inputlist()
has = [0] * n
for i in range(n):
	f[i] -= 1
	if f[i] != -1:
		has[f[i]] = 1
a = []
b = []
for i in range(n):
	if has[i] == 0:
		j = i
		while f[j] != -1:
			j = f[j]
		a.append(i)
		b.append(j)
for i in range(len(a)):
	f[b[i]] = a[(i + 1) % len(b)]
for i in range(n):
	print(f[i] + 1, end=' ')


n = int(input())
f = list(map(int, input().split()))
adj = {i: f[i - 1] for i in range(1, n + 1) if f[i - 1] != 0}
v_without_in = {i for i in range(1, n + 1)}
v_without_out = {i for i in range(1, n + 1)}
for k in adj:
	v_without_in.remove(k)
	v_without_out.remove(adj[k])
free = v_without_in & v_without_out
dangling_in = v_without_in - v_without_out
dangling_out = v_without_out - v_without_in
v_in = list(free) + list(dangling_in)
v_out = list(free) + list(dangling_out)
temp = v_in.pop()
while v_in:
	ingoing = v_in.pop()
	outgoing = v_out.pop()
	adj[ingoing] = outgoing
adj[temp] = v_out.pop()
res = [adj[i] for i in range(1, n + 1)]
print(' '.join(map(str, res)))


from sys import stdin
from collections import deque
input = stdin.readline
n = int(input())
s = list(map(int, input().split(' ')))
given = deque()
received = deque()
for i in range(n):
	if s[i] == 0:
		given.append(i + 1)
	else:
		received.append(s[i])
received = set(range(1, n + 1)).difference(set(received))
given = set(given)
needBoth = list(received.intersection(given))
toreceive = list(received.difference(given))
togive = list(given.difference(received))
a = len(needBoth)
b = len(toreceive)
if a >= 2:
	s[needBoth[a - 1] - 1] = needBoth[0]
	for i in range(0, a - 1):
		s[needBoth[i] - 1] = needBoth[i + 1]
	for i in range(b):
		s[togive[i] - 1] = toreceive[i]
elif a == 1:
	e = needBoth[0]
	s[e - 1] = toreceive[0]
	for i in range(b - 1):
		s[togive[i] - 1] = toreceive[i + 1]
	s[togive[b - 1] - 1] = e
else:
	for i in range(b):
		s[togive[i] - 1] = toreceive[i]
print(*s)


n = int(input())
arrF = list(map(int, input().split()))
arrDontKnow = []
arrHasGift = [False] * (n + 1)
for i in range(n):
	if arrF[i] == 0:
		arrDontKnow.append(i + 1)
	else:
		arrHasGift[arrF[i]] = True
arrDontHaveGift = []
for i in range(1, len(arrHasGift)):
	if arrHasGift[i] == False:
		arrDontHaveGift.append(i)
for i in range(len(arrDontKnow)):
	if arrDontKnow[i] == arrDontHaveGift[i]:
		if i == 0:
			(arrDontHaveGift[i], arrDontHaveGift[-1]) = (arrDontHaveGift[-1], arrDontHaveGift[i])
		else:
			(arrDontHaveGift[i], arrDontHaveGift[i - 1]) = (arrDontHaveGift[i - 1], arrDontHaveGift[i])
for i in range(len(arrDontKnow)):
	arrF[arrDontKnow[i] - 1] = arrDontHaveGift[i]
for i in range(len(arrF)):
	print(arrF[i], end=' ')


size = int(input())
Firends = list(map(int, input().split()))
to_give = []
received = set()
total = set()
for (i, v) in enumerate(Firends):
	total.update([i + 1])
	if v != 0:
		received.update([v])
	if v == 0:
		to_give.append(i + 1)
to_receive = list(total - received)
to_receive.sort(reverse=True)
for g in range(len(to_give) - 1, -1, -1):
	if to_give[g] != to_receive[-1] and to_give[g - 1] != to_receive[len(to_receive) - 2]:
		Firends[to_give[g] - 1] = to_receive.pop(-1)
	else:
		Firends[to_give[g] - 1] = to_receive.pop(len(to_receive) - 2)
for f in Firends:
	print(f, end=' ')


import sys
n = int(sys.stdin.readline())
giv = [int(i) for i in sys.stdin.readline().split()]
rec = [0] * n
for x in range(n):
	if giv[x] > 0:
		rec[giv[x] - 1] = x + 1
collisions = []
g_zero = []
r_zero = []
for y in range(n):
	if giv[y] == 0 and rec[y] == 0:
		collisions.append(y + 1)
	elif giv[y] == 0:
		g_zero.append(y + 1)
	elif rec[y] == 0:
		r_zero.append(y + 1)
if len(collisions) == 1:
	lt = len(g_zero) - 1
	for k in range(len(g_zero)):
		if k == lt:
			giv[g_zero[k] - 1] = collisions[0]
		else:
			giv[g_zero[k] - 1] = r_zero[k]
	for p in range(n):
		if giv[p] == 0:
			giv[p] = r_zero[-1]
			break
else:
	last = len(collisions) - 1
	for h in range(len(collisions)):
		if h == last:
			giv[collisions[h] - 1] = collisions[0]
		else:
			giv[collisions[h] - 1] = collisions[h + 1]
	for k in range(len(g_zero)):
		giv[g_zero[k] - 1] = r_zero[k]
for p in range(n):
	print(giv[p], end=' ')
print()


from sys import stdin
from collections import defaultdict

def get_counter():
	counter_in = set()
	counter_out = set()
	for i in range(1, n + 1):
		if i not in incoming:
			counter_in.add(i)
		if i not in outgoing:
			counter_out.add(i)
	return (counter_in, counter_out)

def myfunction():
	global ans
	ans = dict()
	for i in range(len(counter_out)):
		ans[counter_out[i]] = counter_in[i]
n = int(stdin.readline().strip())
arr = list(map(int, stdin.readline().split()))
incoming = set()
outgoing = set()
zero = set()
for i in range(n):
	if arr[i] != 0:
		incoming.add(arr[i])
		outgoing.add(i + 1)
ans = dict()
(counter_in, counter_out) = get_counter()
counter_in = list(counter_in)
counter_out = list(counter_out)
counter_in.sort()
counter_out.sort()
counter_inn = counter_in[:]
for i in counter_out:
	if counter_inn[-1] != i:
		ans[i] = counter_inn.pop()
	else:
		try:
			node = counter_inn.pop()
			ans[i] = counter_inn.pop()
			counter_inn.append(node)
		except:
			myfunction()
for i in range(0, n):
	if arr[i] == 0:
		arr[i] = ans[i + 1]
print(*arr)


n = int(input())
l = list(map(int, input().split()))
gift = [0] * (n + 1)
index = []
getGift = []
for i in range(n):
	if l[i] != 0:
		gift[l[i]] = 1
	else:
		index.append(1 + i)
getGift = [i for i in range(1, n + 1) if gift[i] == 0]
index.sort()
if index[-1] == getGift[-1]:
	(getGift[-1], getGift[-2]) = (getGift[-2], getGift[-1])
for i in range(len(index)):
	if index[i] == getGift[i]:
		(getGift[i], getGift[i + 1]) = (getGift[i + 1], getGift[i])
pos = 0
for i in range(n):
	if l[i] == 0:
		l[i] = getGift[pos]
		pos += 1
	print(l[i], end=' ')


import sys
(n, *f) = map(int, sys.stdin.read().split())
f = [None] + f

def main():
	no_receieve = set(range(1, n + 1)) - set(f[1:])
	if not no_receieve:
		return f[1:]
	no_send = []
	for i in range(1, n + 1):
		if f[i] == 0:
			no_send.append(i)
	no_send.sort()
	no_receieve = sorted(no_receieve, reverse=True)
	for i in range(len(no_send)):
		if no_send[i] == no_receieve[i]:
			if i >= 1:
				(no_send[i], no_send[i - 1]) = (no_send[i - 1], no_send[i])
			else:
				(no_send[0], no_send[1]) = (no_send[1], no_send[0])
	for i in range(len(no_send)):
		f[no_send[i]] = no_receieve[i]
	return f[1:]
ans = main()
print(*ans, sep=' ')


import sys
lines = sys.stdin.readlines()
n = int(lines[0])
arr = list(map(lambda x: int(x) - 1, lines[1].split(' ')))
res = [-1 for _ in range(n)]
for i in arr:
	if i == -1:
		continue
	res[i] = 1
send = list()
recv = list()
for (idx, i) in enumerate(arr):
	if i == -1:
		send.append(idx)
for (idx, i) in enumerate(res):
	if i == -1:
		recv.append(idx)
recv = recv[::-1]
fixup = set()
i = 0
while i < len(recv):
	if send[i] == recv[i]:
		fixup.add(send[i])
	else:
		arr[send[i]] = recv[i]
	i += 1
if len(fixup) > 0:
	ff = fixup.pop()
	s = send[0] if send[0] != ff else send[1]
	tmp = arr[s]
	arr[s] = ff
	arr[ff] = tmp
arr = list(map(lambda x: x + 1, arr))
sys.stdout.write(' '.join((str(i) for i in arr)) + '\n')


n = int(input())
a = list(map(int, input().split()))
ind = [0 for _ in range(n)]
out = [0 for _ in range(n)]
for i in range(0, len(a)):
	if a[i] == 0:
		continue
	ind[a[i] - 1] = 1
	out[i] = 1
in_1 = [x for x in range(n) if ind[x] == 0]
out_1 = [x for x in range(n) if out[x] == 0]
in_1.sort(key=lambda x: ind[x] + out[x])
out_1.sort(key=lambda x: ind[x] + out[x], reverse=True)
if in_1 == out_1:
	temp = out_1[1:]
	out_1 = temp + [out_1[0]]
for i in range(0, len(in_1)):
	a[out_1[i]] = in_1[i] + 1
print(*a)


n = int(input())
mas = list(map(int, input().split()))
cou = []
for i in range(n + 1):
	cou.append(0)
x = -1
for i in range(n):
	if mas[i] == 0:
		if x == -1:
			x = i
		else:
			y = i
for i in range(n):
	cou[mas[i]] = 1
num = n
for i in range(1, n + 1):
	if cou[i] != 1:
		cou[i] = 1
		while True:
			num -= 1
			if mas[num] == 0:
				mas[num] = i
				break
for i in range(n):
	if mas[i] == i + 1:
		if i == x:
			(mas[i], mas[y]) = (mas[y], mas[i])
		else:
			(mas[i], mas[x]) = (mas[x], mas[i])
print(*mas)


n = int(input())
a = input().split()
toSend = set()
toReceive = set([i for i in range(1, n + 1)])
for i in range(n):
	if int(a[i]) == 0:
		toSend.add(i + 1)
	else:
		toReceive.remove(int(a[i]))
iterList = list(toSend & toReceive)
iterList += list(toSend - toReceive)
for x in iterList:
	pop = toReceive.pop()
	if pop == x:
		secondPop = toReceive.pop()
		toReceive.add(pop)
		pop = secondPop
	a[x - 1] = str(pop)
print(' '.join(a))


q = int(input())
w = list(map(int, input().split()))
e = [0] * q
r = []
t = []
for i in range(q):
	if w[i] == 0:
		r.append(i)
	else:
		e[w[i] - 1] = 1
for i in range(q):
	if e[i] == 0:
		t.append(i)
for i in range(len(r)):
	if r[i] == t[i]:
		if i == 0:
			(t[i], t[1]) = (t[1], t[i])
		else:
			(t[i], t[0]) = (t[0], t[i])
for i in range(len(r)):
	w[r[i]] = t[i] + 1
print(*w)


n = int(input())
l1 = [int(i) for i in input().split()]
l4 = [int(i) for i in range(1, n + 1)]
l2 = list(set(l4) - set(l1))
m = 0
for j in range(n):
	if l1[j] == 0:
		if l2[m] != j + 1:
			l1[j] = l2[m]
			b = l1[j]
			p = j
		elif len(l2) != m + 1:
			l1[j] = l2[m + 1]
			(l2[m], l2[m + 1]) = (l2[m + 1], l2[m])
			b = l1[j]
			p = j
		else:
			l1[j] = b
			l1[p] = l2[m]
		m = m + 1
print(*l1)


n = int(input())
a = list(map(int, input().split()))
uns = [True] * (n * 10)
extra = set()
r = set()
for i in range(n):
	if a[i] != 0:
		uns[a[i]] = False
	else:
		extra.add(i + 1)
priority = []
flag = True
for i in range(1, n + 1):
	if uns[i] and i in extra:
		priority.append((1, i))
		r.add(i)
	elif uns[i]:
		flag = False
		priority.append((0, i))
priority.sort()
ultraflag = False
ul = 0
ur = 0
if flag and len(priority) % 2 != 0:
	ul = priority[0][1]
	ur = priority[-1][1]
	ultraflag = True
while priority:
	if len(priority) >= 2:
		t1 = priority.pop()
		t2 = priority.pop()
		if t1[0] == 1 and t2[0] == 1:
			a[t1[1] - 1] = t2[1]
			a[t2[1] - 1] = t1[1]
			extra.remove(t1[1])
			extra.remove(t2[1])
		elif t1[0] == 0 and t2[0] == 0:
			e1 = extra.pop()
			e2 = extra.pop()
			a[e1 - 1] = t1[1]
			a[e2 - 1] = t2[1]
		else:
			e1 = extra.pop()
			if t1[0] == 1:
				if t1[1] in extra:
					extra.remove(t1[1])
					a[t1[1] - 1] = t2[1]
					a[e1 - 1] = t1[1]
				else:
					e2 = extra.pop()
					a[e1 - 1] = t2[1]
					a[e2 - 1] = t1[1]
			elif t2[1] in extra:
				extra.remove(t2[1])
				a[t2[1] - 1] = t1[1]
				a[e1 - 1] = t1[1]
			else:
				e2 = extra.pop()
				a[e1 - 1] = t2[1]
				a[e2 - 1] = t1[1]
	else:
		t1 = priority.pop()
		e1 = extra.pop()
		a[e1 - 1] = t1[1]
		if a[e1 - 1] == e1:
			j = t1[1]
			while j == t1[1] or a[j - 1] == t1[1]:
				j = r.pop()
			temp = a[j - 1]
			a[j - 1] = t1[1]
			a[t1[1] - 1] = temp
print(*a)


from sys import stdin, stdout
import sys
from math import *
n = int(input())
ar = list(map(int, input().split()))
a = []
b = []
d = {}
for i in range(n):
	if ar[i] == 0:
		a.append(i + 1)
	d[ar[i]] = i
for i in range(n):
	if d.get(i + 1) == None:
		b.append(i + 1)
a.sort()
b.sort()
if len(a) == 1:
	ar[a[0] - 1] = b[0]
	print(*ar)
else:
	for i in range(len(a)):
		if a[i] == b[i]:
			if i == 0:
				(b[i], b[i + 1]) = (b[i + 1], b[i])
			else:
				(b[i], b[i - 1]) = (b[i - 1], b[i])
	for i in range(len(a)):
		ar[a[i] - 1] = b[i]
	print(*ar)


n = int(input())
arr = list(map(int, input().split()))
ind = []
for i in range(n):
	arr[i] -= 1
	if arr[i] == -1:
		ind.append(i)
lista = [0 for i in range(n)]
for i in range(n):
	if arr[i] != -1:
		lista[arr[i]] = 1
index = []
for i in range(n):
	if lista[i] == 0:
		index.append(i)
first = 0
last = len(index) - 1
for i in range(len(ind)):
	if ind[i] == index[first]:
		arr[ind[i]] = index[last]
		last -= 1
	else:
		flag = 0
		if last - first == 1 and i < len(ind) - 1:
			if ind[i] != index[first] and ind[i + 1] == index[last]:
				arr[ind[i]] = index[last]
				arr[ind[i + 1]] = index[first]
				first += 1
				last -= 1
				flag = 1
				break
		if flag == 1:
			break
		arr[ind[i]] = index[first]
		first += 1
	if first > last:
		break
for i in range(n):
	arr[i] += 1
print(*arr)


n = int(input())
res = list(map(int, input().split()))
empty_pos = []
ele = [0] * (n + 1)
for i in range(len(res)):
	if res[i] == 0:
		empty_pos.append(i + 1)
	else:
		ele[res[i]] = 1
rem = []
for i in range(1, len(ele)):
	if ele[i] == 0:
		rem.append(i)
for i in range(len(rem)):
	if rem[i] == empty_pos[i]:
		if i == 0:
			(rem[i], rem[1]) = (rem[1], rem[i])
		else:
			(rem[i], rem[0]) = (rem[0], rem[i])
for i in range(len(empty_pos)):
	res[empty_pos[i] - 1] = rem[i]
for i in res:
	print(i, end=' ')


def main():
	n = int(input())
	arr = list(map(int, input().split()))
	receiver = set()
	giver = set()
	for i in range(1, n + 1):
		receiver.add(i)
		giver.add(i)
	for i in range(n):
		if arr[i] != 0:
			giver.remove(i + 1)
			receiver.remove(arr[i])
	common = giver & receiver
	for i in common:
		giver.remove(i)
		receiver.remove(i)
	giver = list(giver)
	receiver = list(receiver)
	while len(giver) > 1:
		g = giver.pop()
		r = receiver.pop()
		arr[g - 1] = r
	common = list(common)
	if len(common) == 1:
		g = giver.pop()
		r = receiver.pop()
		arr[g - 1] = common[0]
		arr[common[0] - 1] = r
	elif len(common) > 1:
		while len(giver) > 0:
			g = giver.pop()
			r = receiver.pop()
			arr[g - 1] = r
		for i in range(len(common) - 1):
			arr[common[i] - 1] = common[i + 1]
		arr[common[-1] - 1] = common[0]
	else:
		while len(giver) > 0:
			g = giver.pop()
			r = receiver.pop()
			arr[g - 1] = r
	for i in arr:
		print(i, end=' ')
main()


n = int(input())
vaz = [0 for x in range(n + 10)]
v1 = [0 for x in range(n + 10)]
v = list(map(int, input().split()))
for x in v:
	vaz[x] = 1
nr = 0
for i in range(n - 1, -1, -1):
	if vaz[i + 1] == 0 and v[i] == 0:
		nr += 1
		v1[nr] = i + 1
p = 0
for i in range(0, n):
	if vaz[i + 1] == 0 and v[i] > 0:
		nr += 1
		p = 1
		v1[nr] = i + 1
if p == 1:
	pz = nr
	for i in range(0, n):
		if v[i] == 0 and vaz[i + 1] == 0:
			v[i] = v1[pz]
			pz -= 1
	for i in range(0, n):
		if v[i] == 0:
			v[i] = v1[pz]
			pz -= 1
else:
	pz = nr - 1
	for i in range(0, n):
		if v[i] == 0:
			v[i] = v1[pz]
			pz -= 1
			if pz == 0:
				pz = nr
print(*v)


N = int(input())
arr = list(map(int, input().split()))
uniq = set(arr)
uniq.remove(0)
not_found = [x for x in range(1, N + 1) if x not in uniq]
import random
while True:
	random.shuffle(not_found)
	arr2 = arr.copy()
	idx = 0
	for i in range(N):
		if arr2[i] == 0:
			arr2[i] = not_found[idx]
			idx += 1
	if not any((i + 1 == x for (i, x) in enumerate(arr2))):
		print(' '.join(map(str, arr2)))
		break


n = int(input())
l = list(map(int, input().split()))
f = [0] * (n + 1)
t1 = []
t2 = []
t3 = []
f1 = [0] * (n + 1)
f2 = [0] * (n + 1)
for i in range(n):
	if l[i] != 0:
		f[l[i]] = 1
	else:
		t2.append(i + 1)
		f1[i + 1] = 1
for i in range(1, n + 1):
	if f[i] == 0:
		t1.append(i)
		t3.append(i)
		f2[i] = 1
f3 = []
for i in range(len(t2)):
	if f1[t2[i]] == 1 and f2[t2[i]] == 1:
		f3.append(t2[i])
lenf3 = len(f3)
left = -1
if lenf3 == 1:
	left = f3[0]
else:
	for i in range(lenf3):
		l[f3[i] - 1] = f3[lenf3 - i - 1]
		f[f3[lenf3 - i - 1]] = 1
	if lenf3 % 2 == 1:
		mid = lenf3 // 2
		(l[f3[mid] - 1], l[f3[0] - 1]) = (l[f3[0] - 1], l[f3[mid] - 1])
if left != -1:
	for i in range(len(t3)):
		if t3[i] != left and f[t3[i]] == 0:
			f[t3[i]] = 1
			l[left - 1] = t3[i]
			break
x = 0
for i in range(len(t2)):
	if l[t2[i] - 1] == 0:
		while 1:
			if f[t3[x]] == 0:
				l[t2[i] - 1] = t3[x]
				x -= -1
				break
			x -= -1
print(*l)


n = int(input())
array = list(map(int, input().split()))
indices = {}
required = list()
for i in range(n, 0, -1):
	indices[i] = n - i + 1
	required.append(i)
if n % 2 != 0:
	k = required[n // 2]
	required[n // 2] = required[n // 2 - 1]
	required[n // 2 - 1] = k
	k = indices[n // 2 + 1]
	indices[n // 2 + 1] = indices[n // 2 + 2]
	indices[n // 2 + 2] = k
next = {}
curr = -1
first = -1
for i in range(n):
	if array[i] != 0 and array[i] != required[i]:
		i1 = indices[array[i]]
		i2 = indices[required[i]]
		v1 = array[i]
		v2 = required[i]
		required[i] = array[i]
		required[i1 - 1] = v2
		indices[array[i]] = i2
		indices[v2] = i1
	elif array[i] == 0:
		if curr != -1:
			next[curr] = i
		elif curr == -1:
			first = i
		curr = i
for i in range(n):
	if required[i] == i + 1 and i in next:
		k = required[i]
		required[i] = required[next[i]]
		required[next[i]] = k
	if required[i] == i + 1 and i not in next:
		k = required[i]
		required[i] = required[first]
		required[first] = k
for i in range(n):
	print(required[i], end=' ')


from sys import stdin, stdout
n = int(stdin.readline().strip())
s = list(map(int, stdin.readline().strip().split()))
vis = [False for i in range(n + 10)]
for i in s:
	vis[i] = True
nu = []
nu1 = []
for i in range(1, n + 1):
	if not vis[i]:
		if s[i - 1] == 0:
			nu.append(i)
		else:
			nu1.append(i)
nu.sort()
while len(nu) >= 2:
	if len(nu) % 2 != 0:
		s[nu[-3] - 1] = nu[-1]
		s[nu[-1] - 1] = nu[-2]
		s[nu[-2] - 1] = nu[-3]
		nu.pop()
		nu.pop()
		nu.pop()
		continue
	s[nu[-1] - 1] = nu[-2]
	s[nu[-2] - 1] = nu[-1]
	nu.pop()
	nu.pop()
if len(nu) == 1:
	s[nu[-1] - 1] = nu1[-1]
	nu1.pop()
	nu1.append(nu[-1])
for i in range(n):
	if s[i] == 0:
		s[i] = nu1[-1]
		nu1.pop()
print(*s)


n = int(input())
f = list(map(int, input().split()))
give = set((i for i in range(n)))
get = set((i for i in range(n)))
for i in range(n):
	if f[i] > 0:
		give.remove(i)
		get.remove(f[i] - 1)
givel = list(give)
for x in givel:
	if x in get:
		give.remove(x)
		for j in get:
			if j == x:
				continue
			f[x] = j + 1
			break
		get.remove(j)
givel = list(give)
for x in give:
	for j in get:
		f[x] = j + 1
		break
	get.remove(j)
print(' '.join(map(str, f)))


n = int(input())
f = list(map(int, input().split()))
no_gift = set(range(1, n + 1)) - set(f)
prev = n + 1
for i in range(n):
	if f[i] == 0:
		g = no_gift.pop()
		if g == i + 1:
			if prev <= n:
				(f[prev], g) = (g, f[prev])
			else:
				g_ = no_gift.pop()
				no_gift.add(g)
				g = g_
		f[i] = g
		prev = i
print(' '.join(map(str, f)))


from heapq import heappush, heappop
n = int(input())
arr = list(map(int, input().split()))
(set1, set2) = (set(), set())
pos = []
for i in range(n):
	if arr[i] != 0:
		set1.add(arr[i])
	else:
		pos.append(i + 1)
	set2.add(i + 1)
unseen = list(set2 - set1)
while len(pos) > 2:
	curr_pos = pos[-1]
	if curr_pos != unseen[-1]:
		arr[curr_pos - 1] = unseen[-1]
	else:
		(unseen[-1], unseen[-2]) = (unseen[-2], unseen[-1])
		arr[curr_pos - 1] = unseen[-1]
	unseen.pop()
	pos.pop()
if pos[1] == unseen[1] or pos[0] == unseen[0]:
	(arr[pos[0] - 1], arr[pos[1] - 1]) = (unseen[1], unseen[0])
else:
	(arr[pos[0] - 1], arr[pos[1] - 1]) = (unseen[0], unseen[1])
print(*arr)


def swap(list, p1, p2):
	(list[p1], list[p2]) = (list[p2], list[p1])
n = int(input())
l = list(map(int, input().split()))
l1 = [i for i in range(1, n + 1)]
l2 = list(set(l1) - set(l))
l3 = list()
j = 0
for i in range(n):
	if l[i] == 0:
		l3.append(i)
		if l2[j] != i + 1:
			l[i] = l2[j]
		elif len(l2) != j + 1:
			l[i] = l2[j + 1]
			swap(l2, j, j + 1)
		else:
			l[i] = l[l3[-2]]
			l[l3[-2]] = l2[j]
		j += 1
print(*l)


MOD = 1000000007
MOD2 = 998244353
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
let = 'abcdefghijklmnopqrstuvwxyz'
n = ii()
l = il()
l3 = []
s = set((i for i in range(1, n + 1)))
for i in range(n):
	if l[i]:
		s.remove(l[i])
	else:
		l3.append(i + 1)
l2 = list(s)
for i in range(len(l3) - 1):
	if l3[i] == l2[i]:
		(l2[i], l2[i + 1]) = (l2[i + 1], l2[i])
if l3[-1] == l2[-1]:
	(l2[-1], l2[-2]) = (l2[-2], l2[-1])
for i in range(len(l3)):
	l[l3[i] - 1] = l2[i]
print(*l)


import sys

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

def mint():
	return int(minp())

def mints():
	return list(map(int, minp().split()))

def solve():
	n = mint()
	f = list(mints())
	w = [False] * (n + 1)
	p = [False] * (n + 1)
	for i in f:
		p[i] = True
	q = []
	for i in range(1, n + 1):
		if w[i] or p[i]:
			continue
		s = i
		e = i
		w[i] = True
		ok = True
		while f[e - 1] != 0:
			e = f[e - 1]
			if e == s:
				ok = False
				break
			w[e] = True
		if ok:
			q.append((s, e))
	for i in range(len(q) - 1):
		f[q[i][1] - 1] = q[i + 1][0]
	f[q[-1][1] - 1] = q[0][0]
	print(' '.join(map(str, f)))
solve()


n = int(input())
a = list(map(int, input().split()))
a1 = []
for i in range(n):
	if a[i] == 0:
		a1.append(i + 1)
a2 = [0] * (n + 1)
for i in a:
	a2[i] = 1
a3 = []
for i in range(1, n + 1):
	if a2[i] == 0:
		a3.append(i)
s = set(a3)
a4 = []
for i in a1:
	if i in s:
		a4.append(i)
for i in a4:
	p = s.pop()
	if i != p:
		a[i - 1] = p
	else:
		p1 = s.pop()
		a[i - 1] = p1
		s.add(p)
for i in range(n):
	if a[i] == 0:
		print(s.pop(), end=' ')
	else:
		print(a[i], end=' ')


n = int(input())
cc = [0] * (n + 1)
ff = [int(i) for i in input().split()]
for i in ff:
	cc[i] = 1
left = []
for i in range(1, n + 1):
	if not cc[i]:
		left.append(i)
left = sorted(left)[::-1]
sl = len(left)
cur = 0
for i in range(0, n):
	if ff[i] == 0:
		if i + 1 == left[cur]:
			(left[cur], left[(cur + 1) % sl]) = (left[(cur + 1) % sl], left[cur])
		cur += 1
cur = 0
for i in range(0, n):
	if ff[i] == 0:
		ff[i] = left[cur]
		cur += 1
print(*ff)


a = int(input())
l = list(input().split())
know = [i + 1 for i in range(a)]
for i in range(a):
	if l[i] != '0':
		know[int(l[i]) - 1] = None
know2 = []
for i in range(a):
	if know[i] != None:
		know2.append(int(know[i]))
know2.reverse()
it = 0
for i in range(a):
	if l[i] == '0':
		if know2[it] == i + 1:
			(know2[it], know2[it - 1]) = (know2[it - 1], know2[it])
			break
		it += 1
it = 0
for i in range(a):
	if l[i] != '0':
		print(l[i], end=' ')
	else:
		print(know2[it], end=' ')
		it += 1


def inc(x):
	return x + 1
n = int(input())
f = [int(i) - 1 for i in input().split()]
inp = [0 for i in range(n)]
out = [0 for i in range(n)]
for i in range(n):
	if f[i] != -1:
		out[i] += 1
		inp[f[i]] += 1
loops = []
for i in range(n):
	if inp[i] == 0 and out[i] == 0:
		loops.append(i)
if len(loops) == 1:
	idx = loops[0]
	for i in range(n):
		if inp[i] == 0 and i != idx:
			f[idx] = i
			out[idx] += 1
			inp[i] += 1
			break
elif len(loops) > 1:
	for i in range(len(loops)):
		curr = loops[i]
		nxt = loops[(i + 1) % len(loops)]
		f[curr] = nxt
		out[curr] += 1
		inp[nxt] += 1
ins = []
outs = []
for i in range(n):
	if inp[i] == 0:
		ins.append(i)
	if out[i] == 0:
		outs.append(i)
for i in range(len(ins)):
	f[outs[i]] = ins[i]
print(' '.join(map(str, map(inc, f))))


n = int(input())
friends = [int(x) for x in input().split()]
sfriends = set(friends)
to_give = set([x for x in range(1, n + 1) if x not in sfriends])
to_recieve = set([i + 1 for (i, x) in enumerate(friends) if x == 0])
crashes = to_give & to_recieve
non_crashes = to_give - to_recieve
if len(crashes) > 1:
	crashes = list(crashes)
	for (i, x) in enumerate(crashes[:-1]):
		friends[crashes[i + 1] - 1] = x
	friends[crashes[0] - 1] = crashes[-1]
	crashes = []
if crashes:
	c = crashes.pop()
	for (i, x) in enumerate(friends):
		if x == 0 and i + 1 != c:
			friends[i] = c
			break
for (i, x) in enumerate(friends):
	if x == 0:
		friends[i] = non_crashes.pop()
print(' '.join([str(x) for x in friends]))


for _ in range(1):
	n = int(input())
	wp = list(map(int, input().split()))
	p = [0] * n
	pos = [-1, -1]
	for i in range(n):
		if wp[i] != 0:
			p[wp[i] - 1] = 1
		else:
			(pos[0], pos[1]) = (pos[1], i)
	fr = []
	for i in range(n):
		if p[i] == 0:
			fr.append(i)
	if not fr:
		print(*wp)
		exit()
	for i in range(n):
		if wp[i] == 0:
			if len(fr) == 2:
				if pos[-1] == fr[-2]:
					c = fr.copy()
					(fr[0], fr[1]) = (c[1], c[0])
			if len(fr) == 1:
				print(fr[0] + 1, end=' ')
				continue
			if fr[-1] != i:
				print(fr[-1] + 1, end=' ')
				del fr[-1]
			else:
				print(fr[-2] + 1, end=' ')
				del fr[-2]
		else:
			print(wp[i], end=' ')


from fractions import gcd
from heapq import *
import math
from collections import defaultdict, Counter, deque
from bisect import *
import itertools
import fractions
MOD = 10 ** 9 + 7

def main():
	n = int(input())
	f = list(map(int, input().split()))
	ans = [f[i] for i in range(n)]
	C = Counter(f)
	d = defaultdict(int)
	for i in range(1, n + 1):
		if C[i] == 0:
			d[i] += 1
	priority = []
	later = []
	for i in range(n):
		if ans[i] == 0 and d[i + 1] > 0:
			priority.append(i + 1)
		elif d[i + 1] > 0:
			later.append(i + 1)
	if len(priority) >= 2:
		for i in range(len(priority) - 1):
			ans[priority[i + 1] - 1] = priority[i]
		ans[priority[0] - 1] = priority[len(priority) - 1]
	elif len(priority) == 1:
		for i in range(n):
			if ans[i] == 0 and priority[0] != i + 1:
				ans[i] = priority[0]
				break
	c = 0
	for i in range(n):
		if ans[i] == 0:
			ans[i] = later[c]
			c += 1
	print(*ans)
main()


n = int(input())
a = list(map(int, input().split()))
s = set(a)
s = set(range(n + 1)) - s
s = list(s)
s.sort(reverse=True)
le = len(s)
j = 0
last = -1
first = -1
for i in range(n):
	if a[i] == 0:
		if first == -1:
			first = i
		a[i] = s[j]
		last = i
		j += 1
for i in range(n):
	if a[i] == i + 1:
		if a[i] != a[last]:
			(a[i], a[last]) = (a[last], a[i])
		else:
			(a[i], a[first]) = (a[first], a[i])
		break
for i in a:
	print(i, end=' ')


from random import shuffle
n = int(input())
a = list(map(int, input().split()))
ind = 0
arr = []
s = set()
for i in range(n):
	if a[i] != 0:
		s.add(a[i])
for i in range(1, n + 1):
	if i not in s:
		arr.append(i)
arr.sort()
for j in range(13):
	arr1 = arr[:]
	a1 = a[:]
	shuffle(arr1)
	ind = 0
	k = arr1[ind]
	for i in range(n - 1, -1, -1):
		if a1[i] == 0:
			a1[i] = k
			ind += 1
			if ind == len(arr1):
				break
			k = arr1[ind]
	for i in range(n):
		if a1[i] == i + 1:
			break
	else:
		print(*a1)
		exit()


n = int(input())
a = list(map(int, input().split()))
s = set(a)
toPut = []
for i in range(1, n + 1):
	if i not in s:
		toPut.append(i)
toPut.sort(reverse=True)
idx = 0
prev = None
for i in range(n):
	if a[i] == 0:
		if i + 1 != toPut[idx]:
			a[i] = toPut[idx]
			idx += 1
		else:
			if prev == None:
				(toPut[idx], toPut[idx + 1]) = (toPut[idx + 1], toPut[idx])
				a[i] = toPut[idx]
			else:
				a[i] = toPut[idx]
				(a[i], a[prev]) = (a[prev], a[i])
			idx += 1
		prev = i
print(*a)


def friends(n, A):
	dp = [0] * n
	for i in range(n):
		if A[i] != 0:
			dp[A[i] - 1] += 1
	l = []
	r = []
	c = []
	for i in range(n):
		if A[i] == 0 and dp[i] == 0:
			l.append(i)
		elif A[i] == 0 and dp[i] == 1:
			r.append(i)
		elif A[i] != 0 and dp[i] == 0:
			c.append(i)
	if len(l) == 1:
		k = 0
		for i in range(n):
			if A[i] == 0 and dp[i] == 0:
				A[i] = c[0] + 1
			elif A[i] == 0 and dp[i] == 1:
				if k == 0:
					A[i] = l[0] + 1
					k += 1
				else:
					A[i] = c[k] + 1
					k += 1
		return A
	if len(l) > 1:
		temp = l[0]
		for i in range(0, len(l) - 1):
			l[i] = l[i + 1]
		l[len(l) - 1] = temp
		k = 0
		j = 0
		for i in range(n):
			if A[i] == 0 and dp[i] == 0:
				A[i] = l[j] + 1
				j += 1
			elif A[i] == 0 and dp[i] == 1:
				A[i] = c[k] + 1
				k += 1
		return A
	if len(l) == 0:
		k = 0
		for i in range(n):
			if A[i] == 0 and dp[i] == 1:
				A[i] = c[k] + 1
				k += 1
		return A
n = int(input())
arr = list(map(int, input().split()))
print(*friends(n, arr))


mod = 10 ** 9 + 7
import math

def ain():
	return map(int, input().split())
n = int(input())
l = list(ain())
vis = [0] * n
for x in l:
	if x > 0:
		vis[x - 1] = 1
sad = []
yas = []
for i in range(n):
	if vis[i] == 0 and l[i] == 0:
		sad += [i]
	elif vis[i] == 0:
		yas += [i]
if len(sad) > 1:
	less = len(sad)
	for i in range(less):
		l[sad[i]] = sad[(i + 1) % less] + 1
elif len(sad) == 1:
	i = sad[0]
	j = yas[0]
	l[i] = j + 1
	yas[0] = sad[0]
lesv = len(yas)
ind = 0
for i in range(n):
	if l[i] == 0:
		l[i] = yas[ind] + 1
		ind += 1
print(*l)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
ii = lambda : int(input())
kk = lambda : map(int, input().split())
ll = lambda : list(kk())
n = ii()
ls = ll()
s = set(ls)
frees = [i for i in range(n) if not ls[i]]
freer = [i for i in range(n) if i + 1 not in s]
b = set(frees) & set(freer)
both = list(b)
if len(both) > 1:
	for i in range(len(both)):
		ls[both[i]] = both[(i + 1) % len(both)] + 1
	frees = [f for f in frees if f not in b]
	freer = [f for f in freer if f not in b]
i = 0
while i < len(frees):
	if frees[i] == freer[i]:
		if i == len(frees) - 1:
			ls[frees[i - 1]] = freer[i] + 1
			ls[frees[i]] = freer[i - 1] + 1
		else:
			ls[frees[i]] = freer[i + 1] + 1
			ls[frees[i + 1]] = freer[i] + 1
			i += 1
	else:
		ls[frees[i]] = freer[i] + 1
	i += 1
print(*ls)


def solve(n, f):
	out = [0] * n
	ins = [0] * n
	for i in range(n):
		f[i] -= 1
		if f[i] != -1:
			out[i] += 1
			ins[f[i]] += 1
	alones = [i for i in range(n) if ins[i] == out[i] == 0]
	if len(alones) == 1:
		lonely = alones[0]
		for i in range(n):
			if ins[i] == 0 and lonely != i:
				f[lonely] = i
				out[lonely] += 1
				ins[i] += 1
				break
	elif len(alones) > 1:
		for i in range(len(alones)):
			cur = alones[i]
			nxt = alones[(i + 1) % len(alones)]
			f[cur] = nxt
			out[cur] += 1
			ins[nxt] += 1
	ins = [i for i in range(n) if ins[i] == 0]
	out = [i for i in range(n) if out[i] == 0]
	assert len(ins) == len(out)
	for i in range(len(out)):
		f[out[i]] = ins[i]
	return ' '.join(map(lambda x: str(x + 1), f))

def main():
	n = int(input())
	f = list(map(int, input().split()))
	print(solve(n, f))
main()


n = int(input())
a = list(map(int, input().split()))
s0 = set()
s1 = set(range(1, n + 1))
for i in range(n):
	if a[i] == 0:
		s0.add(i + 1)
	else:
		s1.remove(a[i])
s2 = set()
for person in s1:
	if a[person - 1] == 0:
		s2.add(person)
for person in s0:
	if len(s2) > 0 and s2 != {person}:
		to = s2.pop()
		while to == person:
			s2.add(to)
			to = s2.pop()
		s1.remove(to)
		a[person - 1] = to
	else:
		to = s1.pop()
		while to == person:
			s1.add(to)
			to = s1.pop()
		a[person - 1] = to
for i in range(n):
	print(a[i], end=' ')


n = int(input())
a = list(map(int, input().split()))
b = [0] * n
d = []
for i in range(n):
	if a[i] != 0:
		b[a[i] - 1] = 1
	else:
		d.append(i + 1)
c = []
for i in range(n):
	if b[i] == 0:
		c.append(i + 1)
l = len(d)
for i in range(l):
	if d[i] == c[i]:
		p1 = d[i]
		if i == l - 1:
			p2 = d[0]
			d[i] = p2
			d[0] = p1
		else:
			p2 = d[i + 1]
			d[i] = p2
			d[i + 1] = p1
for i in range(l):
	a[d[i] - 1] = c[i]
for i in a:
	print(i, end=' ')


n = int(input())
l = list(map(int, input().split()))
d = [0] * n
ll = []
x = []
for i in range(n):
	if l[i] == 0:
		ll.append(i)
	else:
		d[l[i] - 1] = 1
for i in range(n):
	if d[i] == 0:
		x.append(i)
for i in range(len(ll)):
	if ll[i] == x[i]:
		if i == 0:
			(x[i], x[1]) = (x[1], x[i])
		else:
			(x[i], x[0]) = (x[0], x[i])
for i in range(len(ll)):
	l[ll[i]] = x[i] + 1
print(*l)


n = int(input())
nums = list(map(int, input().split()))
marker = [0 for i in range(n)]
missingPos = []
missingNums = []
for i in range(n):
	if nums[i] == 0:
		missingPos.append(i + 1)
	else:
		marker[nums[i] - 1] = 1
for i in range(n):
	if marker[i] == 0:
		missingNums.append(i + 1)
leftPos = 0
rightNums = len(missingNums) - 1
pairs = []
while leftPos < len(missingPos):
	if missingPos[leftPos] != missingNums[rightNums]:
		pairs.append([missingPos[leftPos], missingNums[rightNums]])
		leftPos += 1
		rightNums -= 1
	elif rightNums > 0:
		(missingNums[rightNums], missingNums[rightNums - 1]) = (missingNums[rightNums - 1], missingNums[rightNums])
	else:
		pairs.pop()
		leftPos -= 1
		rightNums += 1
		(missingNums[rightNums], missingNums[rightNums - 1]) = (missingNums[rightNums - 1], missingNums[rightNums])
for i in pairs:
	nums[i[0] - 1] = i[1]
print(*nums)


from math import sqrt, gcd, ceil
from collections import deque

def ii():
	return int(input())

def si():
	return input()

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

def li():
	return list(mi())
n = ii()
a = li()
m = {}
m1 = {}
m2 = {}
for i in range(1, n + 1):
	m[i] = 0
	m1[i] = 0
	m2[i] = 0
b = []
c = []
for i in range(n):
	if a[i] != 0:
		m[a[i]] = i + 1
	else:
		c.append(i + 1)
for i in range(1, n + 1):
	if m[i] == 0:
		b.append(i)
		m1[i] = 1
x = []
for i in range(len(c)):
	if m1[c[i]] != 0:
		x.append(c[i])
		m2[c[i]] = 1
y = []
b = list(b)
for i in range(len(b)):
	if m2[b[i]] == 0:
		y.append(b[i])
n1 = len(x)
if n1 >= 1:
	y.append(x[0])
for i in range(n1 - 1):
	a[x[i] - 1] = x[i + 1]
c = 0
if n1 >= 1:
	a[x[n1 - 1] - 1] = y[0]
	c = 1
for i in range(n):
	if a[i] == 0:
		a[i] = y[c]
		c += 1
print(*a)


n = int(input())
f = [int(i) for i in input().split()]
s = set([i for i in range(1, n + 1)])
zero = [i for (i, a) in enumerate(f) if a == 0]
x = list(s - set(f))
for (a, b) in zip(zero, x):
	f[a] = b
for i in range(len(zero) - 1):
	a = zero[i]
	if f[a] == a + 1:
		f[a] = f[zero[i + 1]]
		f[zero[i + 1]] = a + 1
a = zero[-1]
if f[a] == a + 1:
	f[a] = f[zero[0]]
	f[zero[0]] = a + 1
print(*f)


n = int(input())
friends_in = [False] * n
friends_out = [False] * n
friends_ans = [0] * n
friend_i = 0
for gift_i in map(int, input().split()):
	if gift_i > 0:
		friends_out[friend_i] = True
		friends_in[gift_i - 1] = True
		friends_ans[friend_i] = gift_i - 1
	friend_i += 1
passed_in = [i for i in range(n) if not friends_in[i]]
passed_out = [i for i in range(n) if not friends_out[i]]
if passed_in[-1] == passed_out[-1]:
	(passed_out[-1], passed_out[-2]) = (passed_out[-2], passed_out[-1])
coincidence = -1
(i_in, i_out) = (0, 0)
l = len(passed_out)
while i_out < l:
	if coincidence > -1:
		friends_ans[passed_out[i_out]] = coincidence
		coincidence = -1
	else:
		if passed_out[i_out] == passed_in[i_in]:
			coincidence = passed_in[i_in]
			i_in += 1
		friends_ans[passed_out[i_out]] = passed_in[i_in]
		i_in += 1
	i_out += 1
print(*[el + 1 for el in friends_ans])


import sys
import bisect

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))
n = ri()
f = [int(x) - 1 for x in input().split()]
arrivee = set(range(n))
depart = []
for i in range(n):
	if f[i] != -1:
		arrivee.remove(f[i])
	else:
		depart.append(i)
arrivee = list(arrivee)
arrivee.sort(reverse=True)
careful = False
for i in range(len(arrivee)):
	if arrivee[i] == depart[i]:
		if i > 0:
			f[depart[i]] = arrivee[i - 1]
			f[depart[i - 1]] = arrivee[i]
		else:
			careful = True
	else:
		f[depart[i]] = arrivee[i]
if careful == True:
	f[depart[0]] = arrivee[-1]
	f[depart[-1]] = arrivee[0]
print(*[f[i] + 1 for i in range(n)])


import sys
import heapq
from collections import defaultdict
dic = defaultdict(int)
n = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.readline().split()))
for i in arr:
	dic[i] = 1
(missing, spaces) = (defaultdict(int), defaultdict(int))
for i in range(1, n + 1):
	if dic[i] != 1:
		missing[i] = 1
for i in range(n):
	if arr[i] == 0:
		spaces[i + 1] = 1
(l, value, pos) = ([], [], [])
for i in missing:
	if spaces[i] == 1:
		l.append(i)
	else:
		value.append(i)
for i in spaces:
	if missing[i] == 0:
		pos.append(i)
if len(l) == 1:
	arr[pos[0] - 1] = l[0]
	arr[l[0] - 1] = value[0]
	j = 1
else:
	m = len(l)
	for i in range(m):
		if i + 1 < m:
			arr[l[i] - 1] = l[i + 1]
		else:
			arr[l[i] - 1] = l[0]
	j = 0
if j < len(pos):
	for i in range(n):
		if arr[i] == 0:
			arr[i] = value[j]
			j += 1
print(*arr)


n = int(input())
lt = [0] + [int(x) for x in input().split()]
ind = []
for i in range(1, n + 1):
	if lt[i] == 0:
		ind.append(i)
st = set([i for i in range(1, n + 1)])
p = st.difference(set(lt))
p = list(p)
p1 = 0
for i in range(len(ind)):
	if ind[i] == p[p1]:
		(p[p1 - 1], p[p1]) = (p[p1], p[p1 - 1])
	p1 += 1
for i in range(len(ind)):
	lt[ind[i]] = p[i]
print(*lt[1:])


import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
P = [False] * (N + 1)
Q = [False] * (N + 1)
for (i, a) in enumerate(A):
	if a != 0:
		P[a] = True
		Q[i + 1] = True
both = []
q_only = []
p_only = []
for n in range(1, N + 1):
	if not P[n] and (not Q[n]):
		both.append(n)
	elif not P[n]:
		p_only.append(n)
	elif not Q[n]:
		q_only.append(n)
if both:
	q_only += both
	p_only += both
	p_only = p_only[1:] + p_only[:1]
for (p, q) in zip(p_only, q_only):
	A[q - 1] = p
print(*A)


n = int(input())
a = list(map(int, input().split()))
st1 = []
st2 = []
d = {}
for i in range(1, n + 1):
	if a[i - 1] == 0:
		st1.append(i)
	d[a[i - 1]] = 1
for i in range(1, n + 1):
	if i not in d:
		st2.append(i)
n = len(st1)
st1p = 0
st2p = 0
st1q = n - 1
st2q = n - 1
for i in range(n):
	if st1[st1p] != st2[st2p]:
		a[st1[st1p] - 1] = st2[st2p]
		ind1 = st1[st1p] - 1
		ind2 = st2[st2p]
		st1p += 1
		st2p += 1
	elif st1[st1p] != st2[st2q]:
		a[st1[st1p] - 1] = st2[st2q]
		ind1 = st1[st1p] - 1
		ind2 = st2[st2q]
		st1p += 1
		st2q -= 1
	else:
		a[ind1] = st2[st2q]
		a[st1[st1p] - 1] = ind2
		break
print(*a)


n = int(input())
a = [*map(int, input().split())]
b = [1] * (n + 1)
r = range(n)
for i in r:
	b[a[i]] = 0
s = {i for i in r if b[i + 1]}
t = [i for i in s if a[i] < 1]
if len(t) > 1:
	for (i, j) in zip(t, t[1:] + [t[0]]):
		a[i] = j + 1
		s -= {i}
for i in (*t, *r):
	if a[i] < 1:
		j = s.pop()
		if j == i:
			j = s.pop()
			s |= {i}
		a[i] = j + 1
print(*a)


def gifts_giving(preferences):
	out_edges = [x - 1 for x in preferences]
	in_edges = [-1] * len(out_edges)
	for (friend, target) in enumerate(out_edges):
		if target == -1:
			continue
		in_edges[target] = friend
	no_in_out = list(filter(lambda v: in_edges[v] == -1 and out_edges[v] == -1, range(len(preferences))))
	if len(no_in_out) > 1:
		for idx in range(len(no_in_out)):
			friend1 = no_in_out[idx]
			friend2 = no_in_out[(idx + 1) % len(no_in_out)]
			out_edges[friend1] = friend2
			in_edges[friend2] = friend1
	elif len(no_in_out) == 1:
		single_vertex = no_in_out[0]
		idx = 0
		while out_edges[idx] != -1 or idx == single_vertex:
			idx += 1
		out_edges[idx] = single_vertex
		in_edges[single_vertex] = idx
	in_idx = 0
	out_idx = 0
	missing_gifts = sum(map(lambda v: in_edges[v] == -1, range(len(in_edges))))
	for _ in range(missing_gifts):
		while in_edges[in_idx] != -1:
			in_idx += 1
		while out_edges[out_idx] != -1:
			out_idx += 1
		in_edges[in_idx] = out_idx
		out_edges[out_idx] = in_idx
	return [x + 1 for x in out_edges]
input()
preferences = [int(x) for x in input().split()]
result = gifts_giving(preferences)
print(' '.join((str(x) for x in result)))


n = int(input())
A = list(map(int, input().strip().split()))
R = set(A)
X = []
for i in range(1, n + 1):
	if (i in R) == False:
		X.append(i)
p1 = 0
for i in range(n):
	if A[i] == 0 and X[p1] == i + 1:
		(X[p1 - 1], X[p1]) = (X[p1], X[p1 - 1])
		p1 += 1
		continue
	if A[i] == 0:
		p1 += 1
p1 = 0
for i in range(n):
	if A[i] == 0:
		A[i] = X[p1]
		p1 += 1
print(' '.join([str(i) for i in A]))


n = int(input())
a = list(map(int, input().split()))
(giv, rec) = ([], [])
a = [0] + a
(g, r) = (0, 0)
both1 = [[0, 0] for i in range(n + 1)]
b = 0
both = []
ans = [0 for i in range(n + 1)]
for i in range(1, n + 1):
	if a[i] != 0:
		ans[i] = a[i]
		both1[a[i]][1] = i
		both1[i][0] = a[i]
for i in range(1, n + 1):
	k = both1[i]
	if k == [0, 0]:
		both.append(i)
		b += 1
	elif k[0] == 0:
		giv.append(i)
		g += 1
	elif k[1] == 0:
		rec.append(i)
		r += 1
if b == 1:
	ans[both[0]] = rec[r - 1]
	ans[giv[g - 1]] = both[0]
	g -= 1
	r -= 1
else:
	for i in range(1, b):
		ans[both[i - 1]] = both[i]
	if b > 0:
		ans[both[b - 1]] = both[0]
for i in range(g):
	ans[giv[i]] = rec[i]
for i in range(1, n + 1):
	print(ans[i], end=' ')


n = int(input())
initial = list(map(int, input().split()))
total = [i + 1 for i in range(n)]
zeroInd = []
for j in range(n):
	if initial[j] != 0:
		total[initial[j] - 1] = -1
	else:
		zeroInd.append(j)
leftNums = []
for k in range(n):
	if total[k] != -1:
		leftNums.append(total[k])
for i in range(len(leftNums)):
	if zeroInd[i] + 1 == leftNums[i]:
		(leftNums[i], leftNums[i - 1]) = (leftNums[i - 1], leftNums[i])
for i in range(len(leftNums)):
	initial[zeroInd[i]] = leftNums[i]
output = ''
for o in range(n):
	output += str(initial[o]) + ' '
print(output)


n = int(input())
friends = [int(i) for i in input().strip().split(' ')]
s = set(friends)
left = []
for i in range(1, n + 1):
	if i not in s:
		left.append(i)
j = 0
for i in range(n):
	if friends[i] == 0 and left[j] == i + 1:
		(left[j - 1], left[j]) = (left[j], left[j - 1])
		j += 1
		continue
	if friends[i] == 0:
		j += 1
j = 0
for i in range(n):
	if friends[i] == 0:
		friends[i] = left[j]
		j += 1
print(*friends)


tc = int(input())
vhghg = input()
arr1 = vhghg.split()
arr = []
dicts = {}
arr.append(int(0))
for i in arr1:
	i = int(i)
	arr.append(i)
	if i not in dicts:
		dicts[i] = 1
	else:
		dicts[i] += 1
non = []
prio = []
for i in range(1, tc + 1):
	if i not in dicts:
		if arr[i] == 0:
			prio.append(i)
		non.append(i)
for i in prio:
	if i != non[-1]:
		arr[i] = non[-1]
		non.pop()
	else:
		arr[i] = non[0]
		non.pop(0)
strs = ''
for i in range(1, tc + 1):
	if arr[i] != 0:
		strs += str(arr[i])
		strs += ' '
		continue
	elif i == non[0]:
		strs += str(non[1])
		strs += ' '
		non.pop(1)
	else:
		strs += str(non[0])
		strs += ' '
		non.pop(0)
print(strs[:-1])


n = int(input())
l = [int(x) - 1 if x != '0' else -1 for x in input().split()]
rem = [0] * n
index = []
l1 = []
for i in range(len(l)):
	if l[i] > -1:
		rem[l[i]] = 1
	else:
		index.append(i)
for i in range(n):
	if rem[i] == 0:
		l1.append(i)
i = 0
j = 0
lastj = 0
while i != len(l1) - 1:
	if l1[i] != index[j] and index[j] != -1:
		l[index[j]] = l1[i]
		i += 1
		lastj = index[j]
		index[j] = -1
	j += 1
	j %= len(index)
if l[l1[i]] == -1:
	(l[lastj], l[l1[i]]) = (l1[i], l[lastj])
for k in range(n):
	if l[k] != -1:
		l[k] += 1
	else:
		l[k] = l1[i] + 1
print(*l)


n = int(input())
arr = list(map(int, input().strip().split()))
s = set(arr)
ans = []
for i in range(1, n + 1):
	if not i in s:
		ans.append(i)
p1 = 0
for i in range(n):
	if arr[i] == 0 and ans[p1] == i + 1:
		(ans[p1 - 1], ans[p1]) = (ans[p1], ans[p1 - 1])
		p1 += 1
		continue
	if arr[i] == 0:
		p1 += 1
p1 = 0
for i in range(n):
	if arr[i] == 0:
		arr[i] = ans[p1]
		p1 += 1
print(*arr)


n = int(input())
l = list(map(int, input().split()))
s1 = set(l)
s2 = set(range(1, n + 1))
fill = list(s2 - s1)

def gen_list(a, b):
	i = 0
	while i < len(a):
		if b[i] == a[i]:
			if i < len(a) - 1:
				(b[i], b[i + 1]) = (b[i + 1], b[i])
			else:
				(b[0], b[i]) = (b[i], b[0])
			i -= 1
		i += 1
	return b
a = []
for i in range(n):
	if l[i] == 0:
		a.append(i + 1)
b = gen_list(a, fill)
j = 0
for i in range(n):
	if l[i] == 0:
		l[i] = b[j]
		j += 1
	print(l[i], end=' ')


n = int(input())
a = list(map(int, input().split()))
se = set(a)
a1 = list()
for i in range(n):
	if i + 1 not in se:
		a1.append(i + 1)
c1 = 0
for i in range(n):
	if a[i] == 0 and a1[c1] == i + 1:
		(a1[c1 - 1], a1[c1]) = (a1[c1], a1[c1 - 1])
		c1 += 1
		continue
	if a[i] == 0:
		c1 += 1
c1 = 0
for i in range(n):
	if a[i] == 0:
		a[i] = a1[c1]
		c1 += 1
print(*a)


import random as rn
n = int(input())
a = []
c = []
mis = []
pos = 1
dic = {}
for i in input().split():
	k = int(i)
	dic[k] = 0
	a.append(k)
	if k == 0:
		c.append(pos)
	pos += 1
for i in range(1, n + 1):
	if i not in dic.keys():
		mis.append(i)
uni = list(set(mis).intersection(set(c)))
mis1 = []
c1 = []
if len(uni) > 1:
	for i in range(len(uni) - 1):
		a[uni[i] - 1] = uni[i + 1]
		mis1.append(uni[i + 1])
		c1.append(uni[i])
	a[uni[-1] - 1] = uni[0]
elif len(uni) == 1:
	ran = uni[0]
	while ran == uni[0]:
		ran = rn.choice(c)
	a[ran - 1] = uni[0]
	mis1.append(uni[0])
	c1.append(ran)
mis = list(set(mis) - set(mis1))
c = list(set(c) - set(c1))
for i in range(len(mis)):
	a[c[i] - 1] = mis[i]
print(*a)


import sys
from collections import deque
input = sys.stdin.readline
flush = sys.stdout.flush
n = int(input())
f = list(map(int, input().split()))
f = [x - 1 for x in f]
start = [True] * n
for x in f:
	if x != -1:
		start[x] = False
cyc = []
idx = [i for i in range(n) if start[i]]
for i in idx:
	while i != -1:
		cyc.append(i)
		i = f[i]
for i in range(len(cyc) - 1):
	f[cyc[i]] = cyc[i + 1]
f[cyc[-1]] = cyc[0]
f = [x + 1 for x in f]
print(*f)


n = int(input())
f = list(map(int, input().split()))
ans = [-1 for i in range(n)]
g = [-1 for i in range(n)]
r = [-1 for i in range(n)]
for (i, x) in enumerate(f):
	if x != 0:
		ans[i] = x
		g[i] = 1
		r[x - 1] = 1
now = 0
for (i, x) in enumerate(f):
	if g[i] == -1 and r[i] == -1:
		while r[now] != -1 or i == now:
			now += 1
			now %= n
		g[i] = 1
		r[now] = 1
		ans[i] = now + 1
now = 0
for (i, x) in enumerate(f):
	if g[i] == -1:
		while r[now] != -1:
			now += 1
			now %= n
		g[i] = 1
		r[now] = 1
		ans[i] = now + 1
print(*ans)


def arr_inp():
	return [int(x) for x in stdin.readline().split()]

class graph:

	def __init__(self, gdict=None):
		if gdict is None:
			gdict = defaultdict(list)
		self.gdict = gdict

	def edges(self):
		return self.find_edges()

	def find_edges(self):
		edges = []
		for node in self.gdict:
			for nxNode in self.gdict[node]:
				if {nxNode, node} not in edges:
					edges.append({node, nxNode})
		return edges

	def get_vertices(self):
		return list(self.gdict.keys())

	def add_vertix(self, node):
		self.gdict[node] = []

	def add_edge(self, node1, node2):
		self.gdict[node1].append(node2)
		self.gdict[node2].append(node1)
from sys import *
from collections import *
(n, a, g) = (int(input()), arr_inp(), graph())
for i in range(1, n + 1):
	g.add_edge(i, a[i - 1])
one = deque(sorted(list(filter(lambda x: len(g.gdict[x]) == 1, g.gdict.keys())), reverse=True))
pre = 0
for i in range(n):
	if a[i] == 0:
		if i + 1 == one[0]:
			if len(one) > 1:
				one.rotate(-1)
				a[i] = one[0]
				one.popleft()
			else:
				a[i] = a[pre]
				a[pre] = one[0]
				one.popleft()
		else:
			a[i] = one[0]
			one.popleft()
		pre = i
print(*a)


n = int(input())
ar = list(map(int, input().split()))
a = set()
b = set(range(1, n + 1))
for i in range(n):
	if ar[i] == 0:
		a.add(i + 1)
	else:
		b.discard(ar[i])
c = a & b
d = b - a
e = list(a - c)
ans = ar.copy()
if len(c) == 0:
	ind = 0
	ar2 = list(d)
	for x in e:
		ans[x - 1] = ar2[ind]
		ind += 1
elif len(c) == 1:
	c = list(c)
	ar2 = list(d)
	ans[c[0] - 1] = ar2[0]
	ans[e[0] - 1] = c[0]
	ind = 1
	for i in range(1, len(e)):
		x = e[i]
		ans[x - 1] = ar2[ind]
		ind += 1
elif len(c) % 2 == 1:
	ar2 = list(c)
	for i in range(len(ar2) - 1):
		ans[ar2[i] - 1] = ar2[i + 1]
	ans[ar2[-1] - 1] = ar2[0]
	ar2 = list(d)
	ind = 0
	for x in e:
		ans[x - 1] = ar2[ind]
		ind += 1
else:
	ar2 = list(c)
	for i in range(0, len(ar2), 2):
		ans[ar2[i] - 1] = ar2[i + 1]
		ans[ar2[i + 1] - 1] = ar2[i]
	ar2 = list(d)
	ind = 0
	for x in e:
		ans[x - 1] = ar2[ind]
		ind += 1
print(*ans)


from collections import *
n = int(input())
a = [None] * (n + 1)
take = [False] * (n + 1)
for (i, j) in zip(range(1, n + 1), map(int, input().split())):
	a[i] = j
	take[j] = True
b = list()
for i in range(1, n + 1):
	if a[i] == 0 and (not take[i]):
		b.append(i)
if len(b) == 1:
	x = b[0]
	for i in range(1, n + 1):
		if not take[i] and i != x:
			a[x] = i
			take[i] = True
			break
else:
	for i in range(len(b)):
		j = (i + 1) % len(b)
		a[b[i]] = b[j]
		take[b[j]] = True
not_take = deque()
for i in range(1, n + 1):
	if not take[i]:
		not_take.append(i)
for i in range(1, n + 1):
	if a[i] == 0:
		a[i] = not_take.pop()
	print(a[i])


n = int(input())
l = list(map(int, input().split()))
a = len(l) * [0]
for i in l:
	if i != 0:
		a[i - 1] = 1
a = [i + 1 for i in range(len(l)) if a[i] == 0]
b = [i + 1 for i in range(len(l)) if l[i] == 0]
for i in range(len(a)):
	if a[i] == b[i]:
		temp = a[(i + 1) % len(a)]
		a[(i + 1) % len(a)] = a[i]
		a[i] = temp
for i in range(len(a)):
	l[b[i] - 1] = a[i]
print(' '.join(list(map(str, l))))


import math
n = int(input())
l = list(map(int, input().split(' ')))
net = [(index + 1, value) for (index, value) in enumerate(l) if value]
all = set(range(1, n + 1))
left = set(map(lambda x: x[0], net))
right = set(map(lambda x: x[1], net))
free = all - (left | right)
(left, right) = (right - left, left - right)
while len(left) > 1 and len(right) > 1:
	left_element = left.pop()
	right_element = right.pop()
	net.append((left_element, right_element))
if len(free):
	current = free.pop()
	first = current
	if len(left):
		net.append((left.pop(), current))
	while len(free):
		new_current = free.pop()
		net.append((current, new_current))
		current = new_current
else:
	current = left.pop()
if len(right):
	net.append((current, right.pop()))
else:
	net.append((current, first))
net.sort(key=lambda x: x[0])
new = list(map(lambda x: str(x[1]), net))
print(' '.join(new))


n = int(input())
nl = list(map(int, input().split()))
p = list(set(range(1, n + 1)).difference(set(nl)))
j = 0
for i in range(n):
	if nl[i] == 0 and p[j] == i + 1:
		(p[j], p[j - 1]) = (p[j - 1], p[j])
		j += 1
	elif nl[i] == 0:
		j += 1
j = 0
for i in range(n):
	if nl[i] == 0:
		nl[i] = p[j]
		j += 1
print(*nl)


n = int(input())
(*ff,) = map(int, input().split())
f = set(ff)
if 0 in ff:
	f.remove(0)
f0 = [i for i in range(n) if ff[i] == 0]
pr = list({i for i in range(1, n + 1)} ^ f)
pr.sort()
for i in range(len(f0)):
	if f0[i] + 1 == pr[i]:
		if i:
			(pr[i], pr[i - 1]) = (pr[i - 1], pr[i])
		else:
			(pr[i], pr[i + 1]) = (pr[i + 1], pr[i])
for i in range(len(f0)):
	ff[f0[i]] = pr[i]
print(*ff)


n = int(input())
a = list(map(int, input().split()))
s = set(range(1, n + 1)) - (set(a) - {0})
f = 0
for (i, v) in enumerate(a):
	if v:
		pass
	else:
		for j in s:
			if j != i + 1:
				if not f:
					f = i
				a[i] = j
				s -= {j}
				break
		else:
			for j in s:
				a[i] = j
				break
			(a[i], a[f]) = (a[f], a[i])
print(*a)


input()
giving = list(map(lambda x: x - 1, map(int, input().split())))
not_giving = [i for (i, x) in enumerate(giving) if x < 0]
first_not_giver = not_giving[0]
receiving = [False for _ in range(len(giving))]
for x in giving:
	if x >= 0:
		receiving[x] = True
not_receiving = set()
for (i, b) in enumerate(receiving):
	if not b:
		not_receiving.add(i)
for x in not_giving:
	y = not_receiving.pop()
	if x == y:
		if not_receiving:
			tmp = not_receiving.pop()
			giving[x] = tmp
			not_receiving.add(y)
		else:
			tmp = giving[first_not_giver]
			giving[first_not_giver] = y
			giving[x] = tmp
	else:
		giving[x] = y
print(*map(lambda x: x + 1, giving))


n = int(input())
l = list(map(int, input().split()))
used = set(l)
not_used = []
indices = []
for i in range(n):
	if l[i] == 0:
		indices.append(i + 1)
not_used = [x for x in range(n, 0, -1) if x not in used]
for y in range(0, len(not_used)):
	if not_used[y] == indices[y]:
		if y > 0:
			(not_used[y], not_used[y - 1]) = (not_used[y - 1], not_used[y])
		else:
			(not_used[y], not_used[y + 1]) = (not_used[y + 1], not_used[y])
s = ''
j = 0
for i in range(n):
	if l[i] != 0:
		s += str(l[i]) + ' '
	else:
		s += str(not_used[j]) + ' '
		j += 1
print(s)


n = int(input())
data = list(map(int, input().split()))
unassigned = set(range(1, n + 1))
empty = list()
for (i, item) in enumerate(data):
	if item is not 0:
		unassigned.remove(item)
	else:
		empty.append(i + 1)
unassigned = list(unassigned)
assert len(empty) == len(unassigned)
if len(empty) == 1:
	data[empty[0] - 1] = unassigned[0]
elif len(empty) > 1:
	for i in range(len(empty) - 2):
		if empty[i] != unassigned[i]:
			data[empty[i] - 1] = unassigned[i]
		else:
			(unassigned[i], unassigned[i + 1]) = (unassigned[i + 1], unassigned[i])
			data[empty[i] - 1] = unassigned[i]
	if empty[-2] != unassigned[-2] and empty[-1] != unassigned[-1]:
		data[empty[-2] - 1] = unassigned[-2]
		data[empty[-1] - 1] = unassigned[-1]
	else:
		data[empty[-2] - 1] = unassigned[-1]
		data[empty[-1] - 1] = unassigned[-2]
print(*data)


import random
n = int(input())
a = [0] + list(map(int, input().split()))
pres = [0] * (n + 1)
posn0 = []
for i in range(1, n + 1):
	pres[a[i]] = 1
	if a[i] == 0:
		posn0.append(i)
notpresent = []
for i in range(1, n + 1):
	if pres[i] == 0:
		notpresent.append(i)
i = 0
random.shuffle(notpresent)
random.shuffle(posn0)
while i < len(notpresent):
	a[posn0[i]] = notpresent[i]
	i += 1
shufflepairs = []
for i in range(1, n + 1):
	if i == a[i]:
		shufflepairs.append(i)
for i in range(0, len(shufflepairs), 2):
	if i + 1 < len(shufflepairs):
		(a[shufflepairs[i]], a[shufflepairs[i + 1]]) = (a[shufflepairs[i + 1]], a[shufflepairs[i]])
	elif notpresent[0] != shufflepairs[-1]:
		(a[posn0[0]], a[shufflepairs[-1]]) = (a[shufflepairs[-1]], a[posn0[0]])
	else:
		(a[posn0[1]], a[shufflepairs[-1]]) = (a[shufflepairs[-1]], a[posn0[1]])
print(*a[1:])


n = int(input())
l1 = list(map(int, input().split(' ')))
IN = set()
OUT = set()
for i in range(1, n + 1):
	IN.add(i)
	if l1[i - 1] == 0:
		OUT.add(i)
IN = IN - set(l1) - {0}
common = IN.intersection(OUT)
common_list = list(common)
remaining_val = IN - common
remaining_ind = OUT - common
remaining_ind = list(remaining_ind)
remaining_val = list(remaining_val)
if len(common_list) == 1:
	l1[common_list[0] - 1] = remaining_val[-1]
	l1[remaining_ind[-1] - 1] = common_list[0]
	remaining_ind.pop()
	remaining_val.pop()
else:
	for k in range(len(common_list)):
		if k != len(common_list) - 1:
			l1[common_list[k] - 1] = common_list[k + 1]
		else:
			l1[common_list[k] - 1] = common_list[0]
for k in range(len(remaining_val)):
	l1[remaining_ind[k] - 1] = remaining_val[k]
print(*l1)


n = int(input())
lst = [*map(int, input().split())]
l = [*set(range(1, n + 1)).difference(lst)]
for (i, x) in enumerate(lst):
	if x == 0:
		for j in range(len(l) - 1, -1, -1):
			if l[j] != i + 1:
				lst[i] = l.pop(j)
				break
		if lst[i] == 0:
			(lst[prev], lst[i]) = (l.pop(), lst[prev])
		prev = i
print(' '.join(map(str, lst)))


from fractions import Fraction
import sys
import bisect
import heapq
from math import *
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
mod = 1000000007

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

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 graph(vertex):
	return [[] for i in range(0, vertex + 1)]

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 solve():
	n = int(inp())
	a = lis()
	remgive = []
	temp = [0] * (n + 1)
	for i in range(0, n):
		if a[i] == 0:
			remgive.append(i + 1)
		else:
			temp[a[i]] = 1
	remtake = []
	for i in range(1, n + 1):
		if temp[i] == 0:
			remtake.append(i)
	give = [0] * (n + 1)
	take = [0] * (n + 1)
	for i in range(0, len(remtake)):
		give[remgive[i]] = 1
		take[remtake[i]] = 1
	lol = []
	for i in range(1, n + 1):
		if give[i] == 1 and take[i] == 1:
			if len(lol) < 2:
				lol.append(i)
			if len(lol) == 2:
				a[lol[0] - 1] = lol[1]
				a[lol[1] - 1] = lol[0]
				give[lol[0]] = 0
				give[lol[1]] = 0
				take[lol[1]] = 0
				take[lol[0]] = 0
				lol = []
	if len(lol) == 1:
		x1 = -1
		x2 = -1
		for i in range(1, n + 1):
			if give[i] == 1 and i != lol[0]:
				x1 = i
				break
		for i in range(1, n + 1):
			if take[i] == 1 and i != lol[0]:
				x2 = i
				break
		if x1 == -1 and x2 == -1:
			for i in range(0, len(remgive)):
				if remgive[i] != lol[0]:
					x1 = remgive[i]
					x2 = a[remgive[i] - 1]
					break
			a[lol[0] - 1] = x2
			a[x1 - 1] = lol[0]
			give[lol[0]] = 0
			give[x1] = 0
			take[lol[0]] = 0
			take[x2] = 0
		else:
			a[lol[0] - 1] = x2
			a[x1 - 1] = lol[0]
			give[lol[0]] = 0
			give[x1] = 0
			take[lol[0]] = 0
			take[x2] = 0
	remgive = []
	remtake = []
	for i in range(1, n + 1):
		if give[i] == 1:
			remgive.append(i)
		if take[i] == 1:
			remtake.append(i)
	for i in range(0, len(remgive)):
		a[remgive[i] - 1] = remtake[i]
	print(*a)
testcase(1)


import math
n = int(input())
a = list(map(int, input().split()))
a.insert(0, 0)
f = [0] * (n + 2)
d = []
for i in range(1, n + 1):
	if a[i] == 0:
		d.append(i)
	else:
		f[a[i]] = 1
y = []
for i in range(1, n + 1):
	if f[i] == 0:
		y.append(i)
for i in range(len(y)):
	if d[i] == y[i]:
		if i == len(y) - 1:
			(y[i - 1], y[i]) = (y[i], y[i - 1])
		else:
			(y[i + 1], y[i]) = (y[i], y[i + 1])
for i in range(len(y)):
	a[d[i]] = y[i]
print(*a[1:])


n = int(input())
s1 = []
smile = []
sad = []
a = input()
s = a.split()
ss = [0 for i in range(n)]
for i in range(len(s)):
	s[i] = int(s[i])
	if s[i] != 0:
		ss[i] += 1
		ss[s[i] - 1] += 1
for i in range(len(s)):
	if ss[i] == 1 and s[i] != 0:
		sad.append(i)
	elif ss[i] == 1 and s[i] == 0:
		smile.append(i)
	elif ss[i] == 0:
		s1.append(i)
if len(s1) == 1:
	s[s1[0]] = sad[0] + 1
	sad[0] = s1[0]
	s1.pop
for i in range(len(sad)):
	s[smile[i]] = sad[i] + 1
k = int(0)
for i in range(len(s)):
	if s[i] == 0 and ss[i] == 0:
		if k == 0:
			s[i] = s1[len(s1) - 1] + 1
		if k == len(s1) - 1:
			s[i] = s1[0] + 1
		else:
			s[i] = s1[k + 1] + 1
		k += 1
for i in range(len(s)):
	print(s[i])


n = int(input())
l = list(map(int, input().split()))
l1 = [0] * (n + 1)
for i in range(n):
	l1[l[i]] = 1
l2 = []
for i in range(1, n + 1):
	if l1[i] == 0:
		l2.append(i)
l3 = []
for i in range(n):
	if l[i] == 0:
		l3.append(i + 1)
if len(l3) == 1:
	for i in range(n):
		if l[i] == 0:
			l[i] = l2[0]
else:
	t = 0
	for i in range(0, len(l3) - 1):
		if l2[i] == l3[i] or l2[i + 1] == l3[i + 1]:
			temp = l2[i]
			l2[i] = l2[i + 1]
			l2[i + 1] = temp
	for i in range(n):
		if l[i] == 0:
			l[i] = l2[t]
			t += 1
for i in range(n):
	print(l[i], end=' ')
print()


from sys import stdin
from collections import defaultdict as dd
from collections import deque as dq
import itertools as it
from math import sqrt, log, log2
from fractions import Fraction
n = int(input())
nums = list(map(int, stdin.readline().split()))
allset = set(range(1, n + 1))
present = set()
inds = []
for (ind, elem) in enumerate(nums):
	if elem == 0:
		inds.append(ind + 1)
	else:
		present.add(elem)
leftover = allset - present
leftover = sorted(list(leftover), reverse=True)
n = len(leftover)
for i in range(n):
	if leftover[i] == inds[i]:
		for j in range(n):
			if j != i and (leftover[i] != inds[j] and leftover[j] != inds[i]):
				(leftover[i], leftover[j]) = (leftover[j], leftover[i])
				break
for i in range(len(inds)):
	nums[inds[i] - 1] = leftover[i]
print(*nums)


import sys
F = int(sys.stdin.readline().strip())
G = [int(i) for i in sys.stdin.readline().strip().split(' ')]
not_gifted = set(range(1, F + 1))
not_given = []
for i in range(F):
	if G[i] == 0:
		not_given.append(i + 1)
	else:
		not_gifted.remove(G[i])
problematic = []
safe = []
safe_to_give = set(not_gifted)
for i in not_given:
	if i in not_gifted:
		problematic.append(i)
		safe_to_give.remove(i)
	else:
		safe.append(i)
if len(problematic) == 1:
	G[problematic[0] - 1] = safe_to_give.pop()
	not_gifted.remove(G[problematic[0] - 1])
elif len(problematic) > 0:
	for i in range(len(problematic)):
		G[problematic[i] - 1] = problematic[(i + 1) % len(problematic)]
		not_gifted.remove(problematic[(i + 1) % len(problematic)])
for i in range(len(safe)):
	G[safe[i] - 1] = not_gifted.pop()
print(' '.join([str(i) for i in G]))


n = int(input())
a = list(map(int, input().split()))
us = [0 for i in range(n + 1)]
k = 0
t = []
j = 0
for i in range(n):
	us[a[i]] = 1
past = -1
for i in range(n):
	if a[i] == 0:
		for x in range(j, n + 1):
			if us[x] == 0:
				if i + 1 == x:
					if past == -1:
						j = x
						for zx in range(j + 1, n + 1):
							if us[zx] == 0:
								past = zx
								a[i] = zx
								us[zx] = 1
								break
					else:
						c = a[past]
						us[x] = 1
						a[past] = x
						a[i] = c
						j = x
				else:
					past = i
					a[i] = x
					us[x] = 1
					j = x
				break
for s in a:
	print(s, end=' ')


n = int(input())
a = list(map(int, input().split()))
d = set(a)
b = set()
for i in range(n):
	if i + 1 in d:
		continue
	else:
		b.add(i + 1)
t = 0
last = 0
b = list(b)
for i in range(n):
	if a[i] == 0:
		if a[i] == 0:
			if b[t] != i + 1:
				a[i] = b[t]
			elif t == len(b) - 1 and b[t] == i + 1:
				a[i] = b[t]
				ind = a[i]
				a[i] = a[last]
				a[last] = ind
			else:
				ind = b[t]
				b[t] = b[t + 1]
				b[t + 1] = ind
				a[i] = b[t]
			last = i
			t += 1
print(*a, sep=' ')


n = int(input())
l = list(map(int, input().split()))
gifts_given = []
gifts_recieve = []
gifts_not_given = []
gifts_not_given1 = []
gifts_not_recieve = []
gifts_not_recieve1 = []
for i in range(n):
	if l[i] != 0:
		gifts_recieve.append(l[i])
		gifts_given.append(i + 1)
gifts_given = set(gifts_given)
gifts_recieve = set(gifts_recieve)
for i in range(n):
	if i + 1 not in gifts_given:
		gifts_not_given.append(i + 1)
	if i + 1 not in gifts_recieve:
		gifts_not_recieve.append(i + 1)
t1 = set(gifts_not_given).intersection(set(gifts_not_recieve))
for i in gifts_not_given:
	if i in t1:
		continue
	gifts_not_given1.append(i)
for i in gifts_not_recieve:
	if i in t1:
		continue
	else:
		gifts_not_recieve1.append(i)
gifts_not_given = list(t1) + gifts_not_given1
gifts_not_recieve = gifts_not_recieve1 + list(t1)
if set(gifts_not_given) == set(gifts_not_recieve):
	for i in range(len(gifts_not_given) - 1, -1, -1):
		l[gifts_not_given[i] - 1] = gifts_not_given[i - 1]
else:
	for i in range(len(gifts_not_given)):
		l[gifts_not_given[i] - 1] = gifts_not_recieve[i]
print(*l)


def gift(arr, n):
	d = {}
	for e in arr:
		if e != 0:
			d[e] = True
	l = []
	for i in range(1, n + 1):
		if not d.get(i):
			l.append(i)
	val = 0
	for j in range(n):
		if arr[j] == 0:
			if l[-1] != j + 1:
				arr[j] = l.pop()
			elif len(l) > 1:
				arr[j] = l.pop(-2)
			else:
				(arr[val], arr[j]) = (l.pop(), arr[val])
			val = j
	return ' '.join(map(str, arr))
n = int(input())
arr = list(map(int, input().strip().split()))
print(gift(arr, n))


from sys import stdin
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

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

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def lsi():
	x = list(stdin.readline())
	x.pop()
	return x

def si():
	return stdin.readline()

def sieve(x):
	a = [True] * (x + 1)
	sq = floor(sqrt(x))
	for i in range(3, sq + 1, 2):
		if a[i]:
			for j in range(i * i, x + 1, i):
				a[j] = False
	if x > 1:
		p = [2]
	else:
		p = []
	for i in range(3, x + 1, 2):
		if a[i]:
			p.append(i)
	return p
z = set()
b = set()
n = ii()
bl = [1] * (n + 1)
a = li()
for i in range(n):
	if a[i]:
		bl[a[i]] = 0
	else:
		z.add(i + 1)
for i in range(1, n + 1):
	if bl[i]:
		b.add(i)
cop = z & b
z -= cop
b -= cop
if len(cop) > 1:
	x = cop.pop()
	y = x
	while cop != set():
		v = cop.pop()
		a[x - 1] = v
		x = v
	a[x - 1] = y
elif cop != set():
	x = cop.pop()
	a[z.pop() - 1] = x
	a[x - 1] = b.pop()
while z != set():
	a[z.pop() - 1] = b.pop()
print(*a)


from sys import stdin, stdout
from os import path
if path.exists('input.txt'):
	stdin = open('input.txt', 'r')

def traverse(mylist, safe):
	j = 0
	for i in range(len(mylist)):
		if mylist[i] == 0:
			mylist[i] = safe[j]
			j += 1
x = int(stdin.readline())
mylist = list(map(int, stdin.readline().strip().split()))
problem = []
safe = []
out = [0] * x
for i in range(x):
	if mylist[i] != 0:
		out[mylist[i] - 1] = 1
for i in range(x):
	if mylist[i] == 0 and out[i] == 0:
		problem.append(i + 1)
	elif out[i] == 0:
		safe.append(i + 1)
if len(problem) == 1:
	mylist[problem[0] - 1] = safe[0]
	safe[0] = problem[0]
	traverse(mylist, safe)
elif len(problem) > 1:
	for i in range(len(problem)):
		if i == len(problem) - 1:
			mylist[problem[-1] - 1] = problem[0]
		else:
			mylist[problem[i] - 1] = problem[i + 1]
	traverse(mylist, safe)
else:
	traverse(mylist, safe)
print(*mylist)


n = int(input())
friends = list(map(int, input().split()))
original = friends.copy()
guys = {}
for i in range(len(friends)):
	if friends[i] != 0:
		guys[friends[i]] = 1
dumbs = []
for i in range(1, n + 1):
	if i not in guys:
		dumbs.append(i)
for i in range(len(friends)):
	if friends[i] == 0:
		maybe = dumbs.pop()
		if maybe != i + 1:
			friends[i] = maybe
			continue
		if dumbs:
			candidate = dumbs.pop()
			friends[i] = candidate
			dumbs.append(maybe)
		else:
			for j in range(len(original)):
				if j != i and original[j] == 0 and (friends[j] != maybe):
					friends[i] = friends[j]
					friends[j] = maybe
					break
print(*friends)


import sys

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

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
N = INT()
A = LIST()
src = []
dist = []
S = set()
for (i, a) in enumerate(A):
	if a == 0:
		src.append(i)
	else:
		S.add(A[i] - 1)
for i in range(N):
	if i not in S:
		dist.append(i)
M = len(src)
for i in range(M):
	if src[i] == dist[i]:
		(dist[i], dist[(i + 1) % M]) = (dist[(i + 1) % M], dist[i])
for i in range(M):
	A[src[i]] = dist[i] + 1
print(*A)


n = int(input())
want = list(map(int, input().split()))
st = set(range(1, n + 1))
for f in want:
	if f != 0:
		st.remove(f)
st = list(st)
for i in range(n):
	if len(st) == 2:
		break
	if want[i] == 0:
		if st[-1] == i + 1:
			(st[-1], st[-2]) = (st[-2], st[-1])
		pp = st[-1]
		want[i] = pp
		st.pop()
i1 = -1
i2 = -1
for i in range(n):
	if want[i] == 0:
		if i1 == -1:
			i1 = i
		else:
			i2 = i
			break
if i1 + 1 == st[0] or i2 + 1 == st[1]:
	(i1, i2) = (i2, i1)
want[i1] = st[0]
want[i2] = st[1]
print(' '.join(map(str, want)))


n = int(input())
a = list(map(int, input().split()))
ind = set()
fri = set()
ref = set(a)
for i in range(1, n + 1):
	if i not in ref:
		fri.add(i)
	if a[i - 1] == 0:
		ind.add(i)
inte = ind.intersection(fri)
if len(inte) == 1:
	for i in inte:
		maa = i
		for j in fri:
			t = j
			if t != i:
				break
		a[i - 1] = t
		fri.remove(t)
	ind.remove(maa)
else:
	for i in inte:
		fri.remove(i)
		ind.remove(i)
for i in ind:
	for j in fri:
		t = j
		if t != i:
			break
	a[i - 1] = t
	fri.remove(t)
if len(inte) > 1:
	tri = list(inte)
	tri.sort()
	y = len(tri)
	for i in range(len(tri)):
		a[tri[i] - 1] = tri[(i + 1) % y]
print(*a)


import sys
from math import gcd
from heapq import heappop
from heapq import heappush
from heapq import heapify
from bisect import insort
from bisect import bisect_right
from bisect import bisect_left
from sys import stdin, stdout
from collections import defaultdict, deque
from math import log2, ceil, floor
inp = lambda : int(input())
sip = lambda : input()
mulip = lambda : map(int, input().split())
lst = lambda : list(map(int, input().split()))
slst = lambda : list(sip())
arr2d = lambda x: [[int(j) for j in input().split()] for i in range(x)]
odds = lambda l: len(list(filter(lambda x: x % 2 != 0, l)))
evens = lambda l: len(list(filter(lambda x: x % 2 == 0, l)))
mod = pow(10, 9) + 7
Judge = 0
if Judge:
	sys.stdin = open('input.in', 'r')
n = inp()
a = lst()
d = defaultdict(int)
for i in a:
	d[i] = i
x = []
for i in range(1, n + 1):
	if i not in d:
		x.append(i)
j = 0
x = sorted(x, reverse=True)
l = []
for i in range(n):
	if a[i] == 0:
		l.append(x[j])
		j += 1
	else:
		l.append(a[i])
f = 0
for i in range(n):
	if l[i] == i + 1:
		f = i
		break
if f == 0:
	print(*l)
else:
	tmp = -1
	for i in range(n):
		if a[i] == 0 and l[i] != i + 1:
			tmp = i
	t = l[tmp]
	l[tmp] = l[f]
	l[f] = t
	print(*l)


import os, sys, math
import collections
if os.path.exists('testing'):
	name = os.path.basename(__file__)
	if name.endswith('.py'):
		name = name[:-3]
	src = open(name + '.txt', encoding='utf8')
	input = src.readline

def solve():
	used = [False] * n
	for v in fs:
		if v != 0:
			used[v - 1] = True
	todo = []
	for (e, v) in enumerate(used, start=1):
		if not v:
			todo.append(e)
	todo_size = len(todo)
	offsets = [True] * n
	count1 = 0
	count2 = 0
	for x in range(n):
		a = not used[x]
		b = not fs[x]
		if a and b:
			offsets[(count1 - count2 + todo_size) % todo_size] = False
		if a:
			count1 += 1
		if b:
			count2 += 1
	for (e, o) in enumerate(offsets):
		if o:
			todo_index = e
			break
	else:
		assert False
	for (e, v) in enumerate(fs, start=1):
		if v == 0:
			gift = todo[todo_index]
			assert todo[todo_index] != v
			fs[e - 1] = todo[todo_index]
			todo_index = (todo_index + 1) % todo_size

def integers():
	return map(int, input().strip().split())

def array_of_integers(q):
	return [tuple(map(int, input().strip().split())) for _ in range(q)]
(n,) = integers()
fs = list(integers())
solve()
print(' '.join(map(str, fs)))


import queue
n = int(input())
data = list(map(int, input().split(' ')))
checked = [False] * (n + 1)
q = queue.Queue()
for i in data:
	checked[i] = True
for i in range(1, n + 1):
	if checked[i] == False and data[i - 1] == 0:
		q.put(i)
for i in range(1, n + 1):
	if checked[i] == False and data[i - 1] != 0:
		q.put(i)
for i in range(n):
	if data[i] != 0:
		print(data[i], end=' ')
	else:
		temp = q.get()
		if temp == i + 1:
			q.put(temp)
			temp = q.get()
		print(temp, end=' ')


n = int(input())
f = []
yet = []
hashh = [True for i in range(n + 1)]
ha = []
cnt = 0
read = input().split()
for k in range(len(read)):
	try:
		tmp = int(read[k])
		f.append(tmp)
		if tmp == 0:
			yet.append(k + 1)
			cnt += 1
		else:
			hashh[tmp] = False
	except Exception:
		pass
for i in range(1, n + 1):
	if hashh[i]:
		ha.append(i)
for i in range(1, cnt):
	if yet[i] == ha[i]:
		ha[i] ^= ha[i - 1]
		ha[i - 1] ^= ha[i]
		ha[i] ^= ha[i - 1]
if yet[0] == ha[0]:
	ha[1] ^= ha[0]
	ha[0] ^= ha[1]
	ha[1] ^= ha[0]
tmp = 0
for i in range(n):
	if f[i]:
		print(f[i], end=' ')
	else:
		print(ha[tmp], end=' ')
		tmp += 1


from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations
import sys
import bisect
import string
import math
import time
import random

def I():
	return int(input())

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

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def StoI():
	return [ord(i) - 97 for i in input()]

def ItoS(nn):
	return chr(nn + 97)

def GI(V, E, Directed=False, index=0):
	org_inp = []
	g = [[] for i in range(n)]
	for i in range(E):
		inp = LI()
		org_inp.append(inp)
		if index == 0:
			inp[0] -= 1
			inp[1] -= 1
		if len(inp) == 2:
			(a, b) = inp
			g[a].append(b)
			if not Directed:
				g[b].append(a)
		elif len(inp) == 3:
			(a, b, c) = inp
			aa = (inp[0], inp[2])
			bb = (inp[1], inp[2])
			g[a].append(bb)
			if not Directed:
				g[b].append(aa)
	return (g, org_inp)

def bit_combination(k, n=2):
	rt = []
	for tb in range(n ** k):
		s = [tb // n ** bit % n for bit in range(k)]
		rt += [s]
	return rt

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
YN = ['Yes', 'No']
mo = 10 ** 9 + 7
inf = float('inf')
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
input = lambda : sys.stdin.readline().rstrip()

def ran_input():
	import random
	n = random.randint(4, 16)
	(rmin, rmax) = (1, 10)
	a = [random.randint(rmin, rmax) for _ in range(n)]
	return (n, a)
show_flg = False
show_flg = True
ans = 0
n = I()
a = LI()
b = [1] * n
p = []
z = []
for i in range(n):
	if a[i] == 0:
		p.append(i)
	else:
		b[a[i] - 1] = 0
c = [i for i in range(n) if b[i] == 1]
m = len(p)
s = []
for i in range(m):
	if p[i] == c[i]:
		s.append(i)
if len(s) > 0:
	s = [s[-1]] + s[:-1]
if len(s) == 1:
	for i in range(len(c)):
		if p[i] != c[s[0]] and i != s[0]:
			(c[i], c[s[0]]) = (c[s[0]], c[i])
ans = [i for i in c]
j = 0
for i in range(m):
	if p[i] == c[i]:
		ans[i] = c[s[j]]
		j += 1
	else:
		ans[i] = c[i]
j = 0
for i in range(n):
	if a[i] == 0:
		a[i] = ans[j] + 1
		j += 1
print(*a)


import sys
n = int(input())
lis = list(map(int, input().split()))
occ = [0] * n
g = []
t = []
for i in range(n):
	if lis[i] == 0:
		g.append(i)
	else:
		occ[lis[i] - 1] = 1
for i in range(n):
	if occ[i] == 0:
		t.append(i)
i = 0
f = len(g)
for i in range(f):
	if t[i] == g[i]:
		(t[i % f], t[(i + 1) % f]) = (t[(i + 1) % f], t[i % f])
for i in range(f):
	lis[g[i]] = t[i] + 1
print(*lis)


import math, sys
from collections import defaultdict, deque
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')

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

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

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

def main():
	try:
		n = I()
		l = list(In())
		gp = defaultdict(list)
		for i in range(n):
			if l[i] == 0:
				continue
			gp[l[i] - 1].append(i)
			gp[i].append(l[i] - 1)
		vis = [0] * n
		pair = []
		for i in range(1, n):
			if vis[i] == 0:
				q = deque([i])
				vis[i] = 1
				leaf = []
				while q:
					node = q.popleft()
					if len(gp[node]) == 1 and vis[gp[node][0]] == 1:
						leaf.append(node)
						continue
					for x in gp[node]:
						if not vis[x]:
							q.append(x)
							vis[x] = 1
				if len(leaf) == 1:
					if len(pair):
						if l[leaf[0]] == 0:
							l[leaf[0]] = i + 1
						elif l[i] == 0:
							l[i] = leaf[0] + 1
						continue
					if l[leaf[0]] == 0:
						l[leaf[0]] = i + 1
						pair.append(leaf[0])
						pair.append(i)
					else:
						pair.append(i)
						pair.append(leaf[0])
						l[i] = leaf[0] + 1
				elif len(leaf) > 1:
					if len(pair):
						if l[leaf[0]] == 0:
							l[leaf[0]] = leaf[1] + 1
						elif l[leaf[1]] == 0:
							l[leaf[1]] = leaf[0] + 1
						continue
					if l[leaf[0]] == 0:
						l[leaf[0]] = leaf[1] + 1
						pair.append(leaf[0])
						pair.append(leaf[1])
					else:
						pair.append(leaf[1])
						pair.append(leaf[0])
						l[leaf[1]] = leaf[0] + 1
		ex = []
		for i in range(n):
			if l[i] == 0:
				ex.append(i)
		if len(pair) and len(ex):
			for i in range(len(ex) - 1):
				l[ex[i]] = ex[i + 1] + 1
			l[pair[0]] = ex[0] + 1
			l[ex[-1]] = pair[1] + 1
		elif len(ex):
			ex.sort()
			for i in range(len(ex) - 1):
				l[ex[i]] = ex[i + 1] + 1
			l[ex[-1]] = ex[0] + 1
		print(*l)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(1):
	main()


t = 1
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	nonused = [True] * n
	for e in a:
		if e == 0:
			continue
		nonused[e - 1] = False
	pri = []
	tank = []
	for i in range(n):
		if nonused[i]:
			if a[i] == 0:
				pri.append(i)
			else:
				tank.append(i)
	for i in range(n):
		if a[i] == 0:
			if len(pri) == 0:
				a[i] = tank.pop() + 1
			elif len(pri) == 1:
				if i == pri[0]:
					a[i] = tank.pop() + 1
				else:
					a[i] = pri.pop() + 1
			else:
				tmp = pri.pop()
				if i == tmp:
					a[i] = pri.pop() + 1
					pri.append(tmp)
				else:
					a[i] = tmp + 1
	print(*a)


from math import *

def swap(b, x, y):
	t = b[x]
	b[x] = b[y]
	b[y] = t
n = int(input())
f = [int(i) for i in input().split()]
a = set([i + 1 for i in range(n)])
b = set()
for i in range(len(f)):
	if f[i] > 0:
		a.remove(f[i])
	else:
		b.add(i)
a = list(a)
lea = len(a)
for i in range(len(f)):
	if f[i] == 0:
		f[i] = a[-1]
		a.pop(lea - 1)
		lea -= 1
b = list(b)
for x in range(int(ceil(sqrt(n))) + 1):
	for i in range(len(f)):
		if i + 1 == f[i]:
			ci = 0
			while f[b[ci]] == i + 1:
				ci += 1
			swap(f, b[ci], i)
print(' '.join(map(str, f)))


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

def ls():
	return list(map(int, list(input())))

def i():
	return int(input())
from collections import defaultdict
n = i()
graph = defaultdict(list)
used = [False] * (n + 1)
a = li()
for x in a:
	if x != 0:
		used[x] = True
notused = []
notusedandfilled = []
notfilled = []
for i in range(n):
	if a[i] == 0:
		if used[i + 1]:
			notfilled.append(i + 1)
		else:
			notusedandfilled.append(i + 1)
	elif not used[i + 1]:
		notused.append(i + 1)
index = notusedandfilled + notfilled
value = notusedandfilled + notused
k = value.pop(0)
value.append(k)
for i in range(len(index)):
	a[index[i] - 1] = value[i]
print(*a)


n = int(input())
lc = list(map(int, input().split()))
lc.insert(0, 0)
lf = [1] * (n + 1)
for i in lc:
	lf[i] = 0
sf = set()
for (i, e) in enumerate(lf):
	if e == 1:
		sf.add(i)
lc2 = []
for (i, e) in enumerate(lc):
	if i > 0 and e == 0 and (i in sf):
		lc2.append(i)
for (i, e) in enumerate(lc):
	if i > 0 and e == 0 and (not i in sf):
		lc2.append(i)
for e in lc2:
	x = sf.pop()
	if x == e:
		lc[e] = sf.pop()
		sf.add(x)
	else:
		lc[e] = x
print(' '.join(map(str, lc[1:])))


N = int(input())
a = list(map(int, input().split()))
end = [False] * N
give = []
for i in range(N):
	if a[i] != 0:
		end[a[i] - 1] = True
	else:
		give.append(i)
want = []
for i in range(N):
	if not end[i]:
		want.append(i)
for i in range(len(give) - 1):
	if give[i] == want[i]:
		t = want[i + 1]
		want[i + 1] = want[i]
		want[i] = t
if give[-1] == want[-1]:
	t = want[-1]
	want[-1] = want[-2]
	want[-2] = t
for i in range(len(give)):
	a[give[i]] = want[i] + 1
print(' '.join(map(str, a)))


def solve(n, f):
	zero_idx = [i + 1 for (i, fi) in enumerate(f) if fi == 0]
	cand_nums = list(set(range(n + 1)) - set(f))
	nz = len(zero_idx)
	for i in range(nz - 2):
		x = zero_idx[i]
		y = cand_nums.pop()
		if x == y:
			cand_nums = [y] + cand_nums
			y = cand_nums.pop()
		f[x - 1] = y
	zero_idx = set(zero_idx[-2:])
	cand_nums = set(cand_nums)
	both_nums = zero_idx & cand_nums
	while len(both_nums):
		x = both_nums.pop()
		for y in cand_nums:
			if x != y:
				break
		zero_idx.remove(x)
		cand_nums.remove(y)
		if y in both_nums:
			both_nums.remove(y)
		f[x - 1] = y
	for (x, y) in zip(list(zero_idx), list(cand_nums)):
		f[x - 1] = y
	print(' '.join([str(x) for x in f]))
n = int(input())
f = list(map(lambda x: int(x), input().strip().split(' ')))
solve(n, f)


n = int(input())
a = [int(i) for i in input().split()]
d = [True for i in range(n)]
for i in a:
	if i - 1 >= 0:
		d[i - 1] = False
d = [i for i in range(n) if d[i]]
b = [i for i in range(n) if a[i] == 0]
h = set(b) & set(d)
if len(h) == 0:
	j = 0
	for i in b:
		a[i] = d[j] + 1
		j += 1
elif len(h) == 1:
	h = list(h)
	h = h[0]
	for i in d:
		if i != h:
			a[h] = i + 1
			d.remove(i)
			break
	b.remove(h)
	j = 0
	for i in b:
		a[i] = d[j] + 1
		j += 1
else:
	h = list(h)
	d = list(set(d) - set(h))
	b = list(set(b) - set(h))
	n = len(h)
	g = h.copy()
	h = h[n - 1:] + h[:n - 1]
	j = 0
	for i in range(n):
		a[g[j]] = h[i] + 1
		j += 1
	j = 0
	for i in b:
		a[i] = d[j] + 1
		j += 1
print(*a)


n = int(input())
l = list(map(int, input().split()))
r = set()
s = set()
z = []
for i in range(1, n + 1):
	s.add(i)
for i in range(len(l)):
	if l[i] == 0:
		z.append(i + 1)
	else:
		s.remove(l[i])
		r.add(l[i])
safe = []
prob = []
for i in z:
	if i in r:
		safe.append(i)
	else:
		prob.append(i)
prob.sort()
f = 0
if len(prob) != 1:
	for i in range(len(prob)):
		x = prob[i]
		if i == len(prob) - 1:
			y = prob[0]
		else:
			y = prob[i + 1]
		l[x - 1] = y
		s.remove(y)
		f = 1
if f == 0 and len(prob) == 1:
	s.remove(prob[0])
for i in s:
	x = safe.pop()
	l[x - 1] = i
	if f == 0 and len(prob) == 1:
		(l[prob[0] - 1], l[x - 1]) = (i, prob[0])
		f = 1
print(*l)


import random
n = int(input())
degint = [0] * n
degext = [0] * n
perm = list((int(i) - 1 for i in input().split(' ')))
for i in range(n):
	if perm[i] != -1:
		degext[i] = 1
		degint[perm[i]] = 1
izo = [i for i in range(n) if degint[i] == 0 and degext[i] == 0]
if len(izo) == 1:
	izolat = izo[0]
	for i in range(0, n):
		if degint[i] == 0 and i != izolat:
			perm[izolat] = i
			degext[izolat] = 1
			degint[i] = 1
			break
elif len(izo) > 1:
	for i in range(len(izo)):
		perm[izo[i]] = izo[(i + 1) % len(izo)]
		degint[izo[(i + 1) % len(izo)]] = 1
		degext[izo[i]] = 1
izo.clear()
inn = [i for i in range(n) if degint[i] == 0]
exx = [i for i in range(n) if degext[i] == 0]
for i in range(len(inn)):
	perm[exx[i]] = inn[i]
for i in perm:
	print(i + 1, end=' ')


n = int(input())
a = [int(x) for x in input().split()]
b = []
end = []
nums = [0] * n
for i in range(n):
	if a[i] == 0:
		b.append(i + 1)
	if a[i] != 0:
		nums[a[i] - 1] = 1
for i in range(len(nums)):
	if nums[i] == 0:
		end.append(i + 1)
for i in range(len(b)):
	if b[i] == end[i]:
		(b[i], b[i - 1]) = (b[i - 1], b[i])
for i in range(len(b)):
	a[b[i] - 1] = end[i]
print(*a, sep=' ')


import sys

def main():
	N = int(sys.stdin.readline())
	values = [int(x) for x in sys.stdin.readline().split()]
	remain_destinations = set(range(1, N + 1))
	remain_sources = set()
	for i in range(N):
		if values[i] == 0:
			remain_sources.add(i + 1)
		else:
			remain_destinations.remove(values[i])
	destinations = list(remain_destinations)
	sources = list(remain_sources)
	length = len(sources)
	while True:
		is_ok = True
		for i in range(length):
			if destinations[i] == sources[i]:
				is_ok = False
				break
		if is_ok is True:
			break
		last_element = destinations.pop()
		destinations = [last_element] + destinations
	destinations.reverse()
	for i in range(N):
		if values[i] == 0:
			values[i] = destinations.pop()
	sys.stdout.write(' '.join(map(str, values)))
main()


from math import *
n = int(input())
f = list(map(int, input().split()))
ls = []
l = [0] * n
memo = []
for i in range(len(f)):
	if f[i] == 0:
		memo.append(i)
	else:
		l[f[i] - 1] = 1
for i in range(len(l)):
	if l[i] == 0:
		ls.append(i + 1)
ls.sort()
ls.reverse()
for i in range(len(ls)):
	f[memo[i]] = ls[i]
	if f[memo[i]] == memo[i] + 1 and i > 0:
		(f[memo[i]], f[memo[i - 1]]) = (f[memo[i - 1]], f[memo[i]])
	elif f[memo[i]] == memo[i] + 1 and i == 0:
		f[memo[i]] = ls[i + 1]
		(ls[i + 1], ls[i]) = (ls[i], ls[i + 1])
print(*f)


from random import shuffle as s
N = int(input())
A = list(map(int, input().split()))
V = [i + 1 for i in range(N) if A[i] == 0]
f = [1] * (N + 1)
for i in A:
	f[i] = 0
F = [i for i in range(1, N + 1) if f[i]]
n = len(F)
cnt = 0
while True:
	cnt += 1
	s(F)
	t = [i for i in range(n) if F[i] == V[i]]
	if not t:
		break
for i in range(n):
	A[V[i] - 1] = F[i]
print(*A)


n = int(input())
f = [int(i) for i in input().split()]
recipients = set(range(1, n + 1))
for recipient in f:
	if recipient in recipients:
		recipients.remove(recipient)
for i in range(len(f)):
	if f[i] == 0 and i + 1 in recipients:
		for recipient in recipients:
			if i + 1 != recipient:
				f[i] = recipient
				break
		recipients.remove(f[i])
for i in range(len(f)):
	if f[i] == 0:
		f[i] = recipients.pop()
print(' '.join([str(i) for i in f]))


n = int(input())
a = [*map(int, input().split())]
nogive = sorted([i + 1 for i in range(n) if a[i] == 0])
nogiven = sorted(list(set(range(n + 1)) - set(a)))
while any((nogive[i] == nogiven[i] for i in range(len(nogive)))):
	nogiven = nogiven[1:] + [nogiven[0]]
while nogiven:
	if nogiven[-1] == nogive[-1]:
		a[nogive.pop(0) - 1] = nogiven.pop()
	else:
		a[nogive.pop() - 1] = nogiven.pop()
print(*a)


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
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
n = int(input())
l = list(map(int, input().split()))
la = [i + 1 for i in range(n)]
s = set(la)
yo = set()
for i in l:
	if i is not 0:
		s.remove(i)
		yo.add(i)
k = list(s)
k.sort()
for i in range(n):
	if l[i] == 0:
		z = k.pop()
		l[i] = z
for i in range(n):
	if l[i] == i + 1:
		for j in range(n):
			if l[j] not in yo:
				if l[j] == j + 1 and i != j:
					(l[i], l[j]) = (l[j], l[i])
					break
				elif l[j] != i + 1 and l[i] != j + 1:
					(l[i], l[j]) = (l[j], l[i])
					break
		break
print(*l)


import os
import sys
from io import BytesIO, IOBase

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

def prime(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 divisors(n):
	i = 1
	div = []
	while i <= math.sqrt(n):
		if n % i == 0:
			if n / i == i:
				div.append(i)
			else:
				div.append(i)
				div.append(n // i)
		i = i + 1
	return div

def solve():
	n = int(input())
	f = list(map(int, input().split()))
	done = [0] * n
	for i in f:
		if i != 0:
			done[i - 1] = 1
	can = []
	for i in range(n):
		if done[i] == 0:
			can.append(i + 1)
	k = 0
	for i in range(n):
		if f[i] == 0:
			if i + 1 != can[k]:
				f[i] = can[k]
				k = k + 1
			elif k != len(can) - 1:
				temp = can[k]
				can[k] = can[k + 1]
				can[k + 1] = temp
				f[i] = can[k]
				k = k + 1
			else:
				temp = f[flag]
				f[flag] = can[k]
				f[i] = temp
			flag = i
	print(*f)

def main():
	solve()
	pass
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()


n = int(input())
gifts = list(map(lambda x: int(x) - 1, input().split()))
unreachable_nodes = set(range(n))
end_nodes = set()
for (i, dest) in enumerate(gifts):
	if dest < 0:
		end_nodes.add(i)
	else:
		unreachable_nodes.remove(dest)
priority_nodes = end_nodes.intersection(unreachable_nodes)
end_nodes = end_nodes.difference(priority_nodes)
while len(priority_nodes) + len(end_nodes) > 0:
	if len(priority_nodes) > 0:
		node = priority_nodes.pop()
	else:
		node = end_nodes.pop()
	candidate = unreachable_nodes.pop()
	if candidate == node or (gifts[candidate] == node and len(unreachable_nodes) == 1):
		dest = unreachable_nodes.pop()
		unreachable_nodes.add(candidate)
	else:
		dest = candidate
	gifts[node] = dest
print(' '.join(map(lambda x: str(x + 1), gifts)))


for t in range(1):
	n = int(input())
	a = [0] + list(map(int, input().split()))
	visit = [0 for i in range(n + 1)]
	for i in range(1, n + 1):
		visit[a[i]] = 1
	b = []
	c = []
	bb = 0
	cc = 0
	d = []
	for i in range(1, n + 1):
		if visit[i] == 0 and a[i] == 0:
			b.append([i, i])
			bb += 1
		elif a[i] == 0:
			d.append(i)
		elif visit[i] == 0:
			c.append(i)
			cc += 1
	for i in range(cc):
		b.append([c[i], d[i]])
	for i in range(1, bb + cc + 1):
		a[b[i % (bb + cc)][1]] = b[i - 1][0]
	for i in range(1, n + 1):
		print(a[i], end=' ')
	print()


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline

def factors(n):
	return sorted(list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split(' ')]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n').split(' ')]

def li3():
	return [int(i) for i in input().rstrip('\n')]

def check(a):
	for i in range(len(a)):
		if a[i] == i + 1:
			return True
	return False
n = val()
l = li()
s = [i + 1 for i in range(n)]
s = set(s)
notgiven = {}
for i in range(len(l)):
	if l[i] != 0:
		s.remove(l[i])
temp1 = l[:]
temp2 = list(s)
s = sorted(list(s), reverse=1)
try:
	for i in range(n - 1, -1, -1):
		if l[i] == 0:
			temp = s.pop()
			if temp != i + 1:
				l[i] = temp
			else:
				l[i] = s.pop()
				s.append(temp)
	if not check(l):
		print(*l)
except:
	s = sorted(list(temp2))
	l = temp1[:]
	for i in range(n - 1, -1, -1):
		if l[i] == 0:
			temp = s.pop()
			if temp != i + 1:
				l[i] = temp
			else:
				l[i] = s.pop()
				s.append(temp)
	print(*l)


n = int(input())
a = list(map(int, input().split()))
d = {i: 0 for i in range(1, n + 1)}
c = []
for i in range(n):
	if a[i] != 0:
		d[a[i]] = 1
	else:
		c.append(i + 1)
b = []
for i in d:
	if d[i] == 0:
		b.append(i)
for i in range(len(c) - 1):
	if b[i] == c[i]:
		(b[i + 1], b[i]) = (b[i], b[i + 1])
if b[-1] == c[-1]:
	(b[-1], b[0]) = (b[0], b[-1])
for i in range(len(c)):
	a[c[i] - 1] = b[i]
print(' '.join((str(y) for y in a)))


n = int(input())
arr = list((int(i) for i in input().split()))
mp = dict()
tmp2 = dict()
for i in range(1, n + 1):
	tmp2[i] = 1
for i in range(1, n + 1):
	mp[i] = 0
for i in range(n):
	if arr[i] != 0:
		mp[i + 1] = arr[i]
		tmp2[arr[i]] = 0
tmp = []
tmp1 = []
for i in mp.keys():
	if mp[i] == 0:
		tmp1.append(i)
for i in tmp2:
	if tmp2[i] == 1:
		tmp.append(i)
flag = True
for i in range(len(tmp)):
	if tmp[i] == tmp1[i]:
		flag = False
if not flag:
	tmp = tmp[-1::-1]
for i in range(len(tmp1)):
	if tmp1[i] != tmp[i]:
		mp[tmp1[i]] = tmp[i]
	elif i != 0:
		mp[tmp1[i - 1]] = tmp[i]
		mp[tmp1[i]] = tmp[i - 1]
	else:
		mp[tmp1[i + 1]] = tmp[i]
		mp[tmp1[i]] = tmp[i + 1]
for i in mp:
	print(mp[i], end=' ')


n = int(input())
a = list(map(int, input().split()))
zeros = set()
missing = set()
for i in range(1, n + 1):
	missing.add(i)
for (i, c) in enumerate(a):
	if c == 0:
		zeros.add(i)
	else:
		missing.discard(c)
copy_zeros = list(zeros)
while len(zeros) > 1:
	for i in zeros:
		for j in missing:
			if j - 1 != i:
				a[i] = j
				missing.discard(j)
				zeros.discard(i)
				break
		break
if len(zeros):
	jose = list(zeros)[0]
	a[jose] = list(missing)[0]
	if jose == list(missing)[0] - 1:
		for i in copy_zeros:
			if i != jose:
				(a[i], a[jose]) = (a[jose], a[i])
				break
print(' '.join(map(str, a)))


import sys
LI = lambda : list(map(int, sys.stdin.readline().strip('\n').split()))
MI = lambda : map(int, sys.stdin.readline().strip('\n').split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline().strip('\n'))
n = II()
nr = set([i for i in range(1, n + 1)])
ns = set([])
a = [0] + LI()
for (i, v) in enumerate(a[1:], 1):
	if v:
		nr.remove(v)
	else:
		ns.add(i)
cmn = ns.intersection(nr)
ucmn = nr.difference(ns)
for v in cmn:
	if ucmn:
		ns.remove(v)
		a[v] = ucmn.pop()
		nr.remove(a[v])
for v in ns:
	a[v] = nr.pop()
	if v == a[v]:
		a[v] = nr.pop()
		nr.add(v)
print(*a[1:])


from sys import stdin, stdout
input = lambda : stdin.readline()
a = int(input())
x = list(map(int, input().split()))
p = list(set(range(1, a + 1)).difference(set(x)))
j = 0
for i in range(a):
	if x[i] == 0 and p[j] == i + 1:
		(p[j], p[j - 1]) = (p[j - 1], p[j])
		j += 1
	elif x[i] == 0:
		j += 1
j = 0
for i in range(a):
	if x[i] == 0:
		x[i] = p[j]
		j += 1
stdout.write(' '.join(map(str, x)))


n = int(input())
F = list(map(int, input().split()))
m = 1
cnt = [0 for i in range(0, n + 1)]
for i in F:
	if i != 0:
		cnt[i] = 1
a = -1
p = -1
for i in range(0, n):
	if F[i] == 0 and cnt[i + 1] == 0 and (a == -1):
		a = i
	elif F[i] == 0 and cnt[i + 1] == 0 and (a != -1):
		F[i] = a + 1
		F[a] = i + 1
		cnt[a + 1] = 1
		cnt[i + 1] = 1
		p = i
		a = -1
if a != -1:
	for i in range(0, n):
		if cnt[i + 1] == 0 and i != a:
			F[a] = i + 1
			cnt[i + 1] = 1
			a = -1
			break
if a != -1:
	(F[a], F[p]) = (F[p], F[a])
m = 1
for i in range(n):
	while m <= n and cnt[m] == 1:
		m += 1
	if F[i] == 0:
		cnt[m] = 1
		F[i] = m
print(*F)


n = int(input())
l = list(map(int, input().split()))
new = [-1] * n
for i in l:
	if i != 0:
		new[i - 1] = 0
d = []
for i in range(n):
	if new[i] == -1:
		d.append(i + 1)
loc = 0
ans = []
index = []
flag = 0
for i in range(n):
	if l[i] != 0:
		ans.append(l[i])
	else:
		if d[loc] != i + 1 and flag == 0:
			ans.append(d[loc])
			if len(index) == 0:
				index.append(i)
		elif len(index) != 0:
			ans.append(d[loc])
			(ans[-1], ans[index[-1]]) = (ans[index[-1]], ans[-1])
			flag = 0
		else:
			flag = 1
			ans.append(d[loc])
			if len(index) == 0:
				index.append(i)
		loc += 1
print(*ans)


n = int(input())
arr = list(map(int, input().split()))
present = [1] * (n + 1)
empty = []
fill = []
for i in range(n):
	present[arr[i]] = 0
for i in range(1, n + 1):
	if present[i]:
		fill.append(i)
		empty.append(i)
j = 0
for i in range(len(fill)):
	if arr[fill[i] - 1] == 0:
		while 1:
			if empty[j] and fill[j] != fill[i]:
				arr[fill[i] - 1] = fill[j]
				empty[j] = 0
				break
			j = (j + 1) % len(fill)
fill = []
for i in range(len(empty)):
	if empty[i]:
		fill.append(empty[i])
j = 0
for i in range(n):
	if arr[i] == 0:
		arr[i] = fill[j]
		j += 1
print(*arr)


n = int(input())
f = [int(x) - 1 for x in input().split()]
tmp1 = []
tmp2 = set()
for i in range(n):
	if f[i] == -1:
		tmp1.append(i)
	else:
		tmp2.add(f[i])
tmp3 = list(sorted(set(range(n)) - tmp2))
for i in range(len(tmp3)):
	if tmp3[i] == tmp1[i]:
		if i < len(tmp3) - 1:
			(tmp3[i], tmp3[i + 1]) = (tmp3[i + 1], tmp3[i])
		else:
			(tmp3[i], tmp3[i - 1]) = (tmp3[i - 1], tmp3[i])
j = 0
for i in range(n):
	if f[i] == -1:
		f[i] = tmp3[j]
		j += 1
print(*[x + 1 for x in f])


n = int(input())
f = list(map(int, input().split()))
(nhi, mila, diya) = ([], [], [0] * n)
for i in range(n):
	if f[i] == 0:
		mila.append(i)
	else:
		diya[f[i] - 1] = 1
for i in range(n):
	if diya[i] == 0:
		nhi.append(i)
for i in range(len(mila)):
	if mila[i] == nhi[i]:
		if i == 0:
			(nhi[i], nhi[1]) = (nhi[1], nhi[i])
		else:
			(nhi[i], nhi[0]) = (nhi[0], nhi[i])
for i in range(len(mila)):
	f[mila[i]] = nhi[i] + 1
print(*f)


n = int(input())
a = list(map(int, input().split()))
vis = [False for i in range(n + 1)]
c = {}
for i in range(n):
	if a[i] is not 0:
		vis[a[i]] = True
	else:
		c[i] = True
d = {}
for i in range(1, n + 1):
	if vis[i] == False:
		d[i] = True
delete = []
for i in c:
	if i + 1 in d:
		k = 0
		for j in d:
			if j is not i + 1:
				a[i] = j
				k = j
				break
		d.pop(k)
		delete.append(i)
for i in delete:
	c.pop(i)
p = [i for i in c]
q = [i for i in d]
for i in range(len(p)):
	a[p[i]] = q[i]
print(' '.join(map(str, a)))


n = int(input())
a = list(range(1, n + 1))
s = 0
m = list(map(int, input().split()))
for i in range(n):
	if m[i] != 0:
		a[m[i] - 1] = 0
	else:
		s = i
i = 0
while i < n:
	if m[i] == 0:
		for j in range(len(a) - 1, -1, -1):
			if a[j] != 0:
				if a[j] == i + 1:
					m[i] = m[s]
					m[s] = a[j]
					a.pop()
					break
				else:
					m[i] = a[j]
					a.pop()
					break
			else:
				a.pop()
		s = i
		i -= 1
	i += 1
print(' '.join(list(map(str, m))))


n = int(input())
friends = list(map(int, input().split()))
taken = set(friends)
nottaken = []
idx = []
for i in range(n):
	if friends[i] == 0:
		idx.append(i + 1)
for i in range(n, 0, -1):
	if i not in taken:
		nottaken.append(i)
for i in range(len(nottaken)):
	if nottaken[i] == idx[i]:
		if i > 0:
			(nottaken[i], nottaken[i - 1]) = (nottaken[i - 1], nottaken[i])
		else:
			(nottaken[i], nottaken[i + 1]) = (nottaken[i + 1], nottaken[i])
ret = ''
j = 0
for i in range(n):
	if friends[i] != 0:
		ret += str(friends[i]) + ' '
	else:
		ret += str(nottaken[j]) + ' '
		j += 1
print(ret)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

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

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

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

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = 1
	rr = []
	for _ in range(t):
		n = I()
		a = LI()
		z = set()
		y = set()
		for (i, c) in enumerate(a, 1):
			if c == 0:
				z.add(i)
			else:
				y.add(c)
		y = set(list(range(1, n + 1))) - y
		x = z & y
		t = []
		if len(x) == 1:
			k = list(x)[0]
			for l in y:
				if l != k:
					m = l
					break
			t.append((k, m))
			z.remove(k)
			y.remove(m)
		elif len(x) > 1:
			l = list(x)
			for i in range(len(l)):
				t.append((l[i], l[i - 1]))
			z -= x
			y -= x
		for (b, c) in zip(z, y):
			t.append((b, c))
		for (b, c) in t:
			a[b - 1] = c
		rr.append(JA(a, ' '))
	return JA(rr, '\n')
print(main())


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
n = int(input())
reciev = set((i for i in range(1, n + 1)))
gave = set(reciev)
l = list(map(int, input().split()))
for i in range(1, n + 1):
	if l[i - 1] == 0:
		continue
	reciev.remove(l[i - 1])
	gave.remove(i)
x = []
for i in reciev:
	if i in gave:
		for j in gave:
			if j != i:
				l[j - 1] = i
				gave.remove(j)
				x.append(i)
				break
for i in x:
	reciev.remove(i)
for i in reciev:
	for j in gave:
		l[j - 1] = i
		gave.remove(j)
		break
print(*l)


n = int(input())
s = list(map(int, input().split()))
ss = []
lol = [0 for _ in range(n + 1)]
h = []
for i in range(n):
	lol[s[i]] = 1
	if s[i] == 0:
		h.append(i)
for j in range(1, len(lol)):
	if lol[j] == 0:
		ss.append(j)
ch = 0
k = len(h)
while k - ch > 3:
	if ss[ch] != h[ch] + 1:
		s[h[ch]] = ss[ch]
		ch += 1
	else:
		s[h[ch]] = ss[ch + 1]
		s[h[ch + 1]] = ss[ch]
		ch += 2
if k - ch == 2:
	if ss[ch] != h[ch] + 1:
		if ss[ch + 1] != h[ch + 1] + 1:
			s[h[ch + 1]] = ss[ch + 1]
			s[h[ch]] = ss[ch]
		else:
			s[h[ch + 1]] = ss[ch]
			s[h[ch]] = ss[ch + 1]
	else:
		s[h[ch + 1]] = ss[ch]
		s[h[ch]] = ss[ch + 1]
if k - ch == 3:
	if ss[ch] != h[ch] + 1:
		if ss[ch + 1] != h[ch + 1] + 1:
			if ss[ch + 2] != h[ch + 2] + 1:
				s[h[ch + 2]] = ss[ch + 2]
				s[h[ch + 1]] = ss[ch + 1]
				s[h[ch]] = ss[ch]
	if ss[ch] == h[ch] + 1:
		if ss[ch + 1] == h[ch + 1] + 1:
			if ss[ch + 2] == h[ch + 2] + 1:
				s[h[ch + 2]] = ss[ch + 1]
				s[h[ch + 1]] = ss[ch]
				s[h[ch]] = ss[ch + 2]
	if ss[ch] != h[ch] + 1:
		if ss[ch + 1] != h[ch + 1] + 1:
			if ss[ch + 2] == h[ch + 2] + 1:
				s[h[ch + 2]] = ss[ch]
				s[h[ch + 1]] = ss[ch + 1]
				s[h[ch]] = ss[ch + 2]
	if ss[ch] != h[ch] + 1:
		if ss[ch + 1] == h[ch + 1] + 1:
			if ss[ch + 2] != h[ch + 2] + 1:
				s[h[ch + 2]] = ss[ch + 2]
				s[h[ch + 1]] = ss[ch]
				s[h[ch]] = ss[ch + 1]
	if ss[ch] != h[ch] + 1:
		if ss[ch + 1] == h[ch + 1] + 1:
			if ss[ch + 2] == h[ch + 2] + 1:
				s[h[ch + 2]] = ss[ch + 1]
				s[h[ch + 1]] = ss[ch + 2]
				s[h[ch]] = ss[ch]
	if ss[ch] == h[ch] + 1:
		if ss[ch + 1] != h[ch + 1] + 1:
			if ss[ch + 2] != h[ch + 2] + 1:
				s[h[ch + 2]] = ss[ch + 2]
				s[h[ch + 1]] = ss[ch]
				s[h[ch]] = ss[ch + 1]
	if ss[ch] == h[ch] + 1:
		if ss[ch + 1] == h[ch + 1] + 1:
			if ss[ch + 2] != h[ch + 2] + 1:
				s[h[ch + 2]] = ss[ch + 2]
				s[h[ch + 1]] = ss[ch]
				s[h[ch]] = ss[ch + 1]
	if ss[ch] == h[ch] + 1:
		if ss[ch + 1] != h[ch + 1] + 1:
			if ss[ch + 2] == h[ch + 2] + 1:
				s[h[ch + 2]] = ss[ch]
				s[h[ch + 1]] = ss[ch + 1]
				s[h[ch]] = ss[ch + 2]
print(*s)


import random
n = int(input())
a = [int(x) for x in input().split()]
j = 1
b = [0] * (n + 1)
for i in a:
	b[i] = 1
c = []
for (i, j) in enumerate(b):
	if j == 0:
		c.append(i)
c = set(c)
for i in range(1, n + 1):
	i = i - 1
	if a[i] == 0:
		if i + 1 in c:
			for k in c:
				if k != i + 1:
					a[i] = k
					c.remove(k)
					break
for i in range(1, n + 1):
	i = i - 1
	if a[i] == 0:
		for k in c:
			if k != i + 1:
				a[i] = k
				c.remove(k)
				break
for i in a:
	print(i, end=' ')


import math
n = int(input())
m = list(map(int, input().split(' ')))
mm = set(m)
idx = []
for i in range(n):
	if m[i] == 0:
		idx.append(i)
cc = 0
gived = []
if len(idx) > 0:
	for i in range(1, n + 1):
		if i not in mm:
			m[idx[cc]] = i
			gived.append([idx[cc], i])
			cc += 1
			if cc == len(idx):
				break
gived.append(gived[0])
for it in range(1, len(gived)):
	gift = gived[it]
	if gift[0] + 1 == gift[1]:
		cur = gift[0]
		prev = gived[it - 1][0]
		m[cur] = gived[it - 1][1]
		m[prev] = gift[1]
		(gived[it - 1][1], gift[1]) = (gift[1], gived[it - 1][1])
for i in m:
	print(i, end=' ')
print()


n = int(input())
a = list(map(int, input().split()))
to_use = [True] * (n + 1)
to_fill = []
for (i, v) in enumerate(a):
	to_use[v] = False
to_use = [x for x in range(1, n + 1) if to_use[x]]
c = 0
chert = 'chert'
f = True
for i in range(n, 0, -1):
	if a[i - 1] == 0:
		if f:
			chert = i - 1
			f = False
		if to_use[c] == i:
			if c + 1 >= len(to_use):
				(to_use[c], a[chert]) = (a[chert], to_use[c])
			else:
				(to_use[c], to_use[c + 1]) = (to_use[c + 1], to_use[c])
		a[i - 1] = to_use[c]
		c += 1
print(' '.join([str(c) for c in a]))


from sys import stdin
inp = stdin.readline
n = int(inp())
f = list(map(int, inp().split()))
will_get_gift = [False] * (n + 1)
for i in f:
	if i != 0:
		will_get_gift[i] = True
will_not_get_gift = []
for i in range(1, n + 1):
	if not will_get_gift[i]:
		will_not_get_gift.append(i)
if will_not_get_gift[-1] == 1:
	(will_not_get_gift[-1], will_not_get_gift[0]) = (will_not_get_gift[0], will_not_get_gift[-1])
zeros = []
for i in range(n):
	if f[i] == 0:
		popped = will_not_get_gift.pop()
		if popped == i + 1:
			if len(zeros):
				(popped, f[zeros[-1]]) = (f[zeros[-1]], popped)
			else:
				will_not_get_gift.append(popped)
				(will_not_get_gift[-1], will_not_get_gift[0]) = (will_not_get_gift[0], will_not_get_gift[-1])
				popped = will_not_get_gift.pop()
		f[i] = popped
		zeros.append(i)
print(*f)


n = int(input())
Pro = list(range(1, n + 1))
it = 0
L = list(map(int, input().split()))
for i in range(n):
	if L[i] != 0:
		Pro[L[i] - 1] = 0
	else:
		it = i
i = 0
while i < n:
	if L[i] == 0:
		for j in range(len(Pro) - 1, -1, -1):
			if Pro[j] != 0:
				if Pro[j] == i + 1:
					L[i] = L[it]
					L[it] = Pro[j]
					Pro.pop()
					break
				else:
					L[i] = Pro[j]
					Pro.pop()
					break
			else:
				Pro.pop()
		it = i
		i -= 1
	i += 1
print(' '.join(list(map(str, L))))


n = int(input())
send = [0] * n
receive = [0] * n
dont_know = []
yet_not_received = []
for (i, e) in enumerate(map(int, input().split())):
	send[i] = e
	if e > 0:
		receive[e - 1] = i + 1
	else:
		dont_know.append(i + 1)
[yet_not_received.append(i + 1) for (i, fr) in enumerate(receive) if fr == 0]
friends_fk_up = len(dont_know)
for (i, e) in enumerate(dont_know):
	if dont_know[i] == yet_not_received[i]:
		if i + 1 >= friends_fk_up:
			(yet_not_received[i], yet_not_received[i - 1]) = (yet_not_received[i - 1], yet_not_received[i])
		elif i - 1 < 0:
			(yet_not_received[i], yet_not_received[i + 1]) = (yet_not_received[i + 1], yet_not_received[i])
		else:
			(yet_not_received[i], yet_not_received[i - 1]) = (yet_not_received[i - 1], yet_not_received[i])
for (i, e) in enumerate(dont_know):
	send[e - 1] = yet_not_received[i]
print(*send)


import sys
from operator import itemgetter

def input():
	return sys.stdin.readline().strip()
n = int(input())
pos = list(map(int, input().split()))
notsend = set(list(map(lambda x: x + 1, filter(lambda i: pos[i] == 0, range(n)))))
notrecv = set(range(1, n + 1))
for i in range(n):
	if pos[i] > 0:
		notrecv.remove(pos[i])
tmp = notsend.intersection(notrecv)
notsend.difference_update(tmp)
notrecv.difference_update(tmp)
sendrecv = list(tmp)
if len(sendrecv) == 1:
	x = notrecv.pop()
	pos[sendrecv[0] - 1] = x
	x = notsend.pop()
	pos[x - 1] = sendrecv[0]
else:
	for i in range(len(sendrecv)):
		pos[sendrecv[i] - 1] = sendrecv[(i + 1) % len(sendrecv)]
notsend = list(notsend)
notrecv = list(notrecv)
assert len(notsend) == len(notrecv)
for i in range(len(notsend)):
	pos[notsend[i] - 1] = notrecv[i]
print(*pos)


n = int(input())
lis = list(map(int, input().split()))
rec = set()
for i in range(len(lis)):
	if lis[i] != 0 and lis[i] != i + 1:
		rec.add(lis[i])
unuse = []
for i in range(1, n + 1):
	if i not in rec:
		unuse.append(i)
for i in range(n):
	if i + 1 in rec or lis[i] != 0:
		continue
	tag = len(unuse) - 1
	while unuse[tag] == i + 1:
		tag -= 1
	lis[i] = unuse[tag]
	unuse.pop(tag)
for i in range(n):
	if lis[i] == 0:
		lis[i] = unuse.pop()
print(' '.join([str(i) for i in lis]))


import sys
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def flin(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def ceil(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

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

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

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

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)
t = 1
for _ in range(t):
	n = ii()
	d = li()
	s = set(range(1, n + 1))
	a = []
	for i in range(n):
		if d[i] != 0:
			s.remove(d[i])
		else:
			a.append(i + 1)
	s = list(s)
	for i in range(len(s)):
		if a[i] == s[i]:
			if i == 0:
				(s[i], s[i + 1]) = (s[i + 1], s[i])
			else:
				(s[i], s[i - 1]) = (s[i - 1], s[i])
	c = 0
	for i in range(n):
		if d[i] == 0:
			d[i] = s[c]
			c += 1
	prr(d)


n = int(input())
arr = list(map(int, input().split(' ')))
check = [i for i in range(1, n + 1)]
last0 = 0
for i in range(n):
	if arr[i] != 0:
		check[arr[i] - 1] = 0
	else:
		last0 = i + 1
remain = []
for i in check:
	if i != 0:
		remain.append(i)
remain.sort(reverse=True)
j = -1
if remain[-1] == last0:
	(remain[j], remain[j - 1]) = (remain[j - 1], remain[j])
j = 0
for i in range(n):
	if arr[i] == 0:
		if i + 1 == remain[j]:
			(remain[j], remain[j + 1]) = (remain[j + 1], remain[j])
		arr[i] = remain[j]
		j += 1
for i in arr:
	print(i, end=' ')
print()


n = int(input())
array = list(map(int, input().split()))
dic = {}
for it in array:
	if it != 0:
		dic[it] = 1
new_array = []
current = 1
new_dic = {}
new_dic['GR'] = []
new_dic['G'] = []
new_dic['R'] = []
for it in array:
	if it == 0 and current not in dic:
		new_array.append('GR')
		new_dic['GR'].append(current)
	elif it == 0 and current in dic:
		new_array.append('G')
		new_dic['G'].append(current)
	elif current in dic:
		new_array.append('DONE')
	else:
		new_array.append('R')
		new_dic['R'].append(current)
	current += 1
if 6 == 6:
	if len(new_dic['GR']) != 1:
		for x in range(len(new_dic['G'])):
			array[new_dic['G'][x] - 1] = new_dic['R'][x]
		for x in range(len(new_dic['GR']) - 1):
			array[new_dic['GR'][x] - 1] = new_dic['GR'][x + 1]
			array[new_dic['GR'][-1] - 1] = new_dic['GR'][0]
		print(*array)
	else:
		array[new_dic['GR'][0] - 1] = new_dic['R'][-1]
		new_dic['R'].pop()
		array[new_dic['G'][-1] - 1] = new_dic['GR'][-1]
		new_dic['G'].pop()
		for x in range(len(new_dic['G'])):
			array[new_dic['G'][x] - 1] = new_dic['R'][x]
		print(*array)


n = int(input())
a = list(map(int, input().split()))
send = []
recv = []
vis = [0] * n
for i in range(n):
	if a[i] == 0:
		send.append(i + 1)
	else:
		vis[a[i] - 1] = 1
for i in range(n):
	if vis[i] == 0:
		recv.append(i + 1)
send.sort()
recv.sort()
recv = list(set(send) & set(recv)) + list(set(recv) - set(send))
p = 0
for i in range(len(send)):
	while recv[p] == -1:
		p = (p + 1) % len(recv)
	if send[i] == recv[p]:
		p = (p + 1) % len(recv)
		while recv[p] == -1:
			p = (p + 1) % len(recv)
	a[send[i] - 1] = recv[p]
	recv[p] = -1
	p = (p + 1) % len(recv)
print(*a)


fac = [1 for _ in range(1021)]
ifac = [1 for _ in range(1021)]
mod = 10 ** 9 + 7

def ModInv(x, y):
	res = 1
	while y > 0:
		if y & 1:
			res = res * x % mod
		y = y >> 1
		x = x * x % mod
	return res
for i in range(1, 1020):
	fac[i] = fac[i - 1] * i % mod
	ifac[i] = ifac[i - 1] * ModInv(i, mod - 2) % mod
t = 1
for _ in range(t):
	n = int(input())
	f = [0]
	f = f + list(map(int, input().split()))
	senders = [0 for _ in range(n + 1)]
	recievers = [0 for _ in range(n + 1)]
	for i in range(1, n + 1):
		if f[i] != 0:
			senders[i] = 1
			recievers[f[i]] = 1
	l = []
	not_reciever = []
	not_sender = []
	for i in range(1, n + 1):
		if senders[i] == 0 and recievers[i] == 0:
			l.append(i)
		elif senders[i] == 0:
			not_sender.append(i)
		elif recievers[i] == 0:
			not_reciever.append(i)
	not_reciever = not_reciever + l
	not_sender = not_sender + l
	m = len(not_sender)
	for i in range(m):
		f[not_sender[i]] = not_reciever[(i + 1) % m]
	for i in range(1, n + 1):
		print(f[i], end=' ')
	print()


n = int(input())
arr = input().split(' ')
visited = [False] * (n + 1)
pos = []
for i in range(len(arr)):
	if arr[i] != '0':
		visited[int(arr[i])] = True
	else:
		pos.append(i + 1)
if pos == []:
	for i in arr:
		print(i, end=' ')
	print()
else:
	available = []
	for i in range(1, n + 1):
		if not visited[i]:
			available.append(i)
	(start, end) = (0, len(available) - 1)
	for j in range(len(pos)):
		i = pos[j]
		if available[start] != i:
			arr[i - 1] = available[start]
			start += 1
		elif available[end] != i:
			arr[i - 1] = available[end]
			end -= 1
		else:
			(arr[pos[j - 1] - 1], arr[i - 1]) = (available[end], arr[pos[j - 1] - 1])
			end -= 1
	for i in arr:
		print(i, end=' ')
	print()


n = int(input())
f = [int(x) for x in input().split()]
nullIndices = [0] * n
for index in range(n):
	if f[index] == 0:
		nullIndices[index] = 1
valueAbsent = [1] * n
for index in range(n):
	if f[index] != 0:
		valueAbsent[f[index] - 1] = 0
i = 0
normalnum = []
reversednum = []
while i < n:
	if nullIndices[i] == 1 and valueAbsent[i] == 1:
		reversednum.append(i + 1)
		nullIndices[i] = -1
	elif nullIndices[i] == 0 and valueAbsent[i] == 1:
		normalnum.append(i + 1)
	i += 1
if len(reversednum) == 1:
	temp = normalnum.pop()
	normalnum.append(reversednum.pop())
	reversednum.append(temp)
reversednum = reversednum[-1:] + reversednum[:-1]
i = 0
j = 0
k = 0
while i < n:
	if nullIndices[i] == 0:
		print(f[i], end=' ')
	elif nullIndices[i] == 1:
		print(normalnum[j], end=' ')
		j += 1
	elif nullIndices[i] == -1:
		print(reversednum[k], end=' ')
		k += 1
	i += 1


n = int(input())
a = list(map(int, input().split()))
a = [-1] + a
z = []
s = []
f = []
r = [0] * (n + 1)
g = [0] * (n + 1)
for i in range(1, n + 1):
	if a[i] != 0:
		g[i] = 1
		r[a[i]] = 1
for i in range(1, n + 1):
	if g[i] == 1 and r[i] == 0:
		s.append(i)
	elif g[i] == 0 and r[i] == 1:
		f.append(i)
	elif g[i] == 0 and r[i] == 0:
		z.append(i)
zp = 0
i = 1
for i in range(len(f)):
	fin = f[i]
	st = s[i]
	if i == len(f) - 1 and len(z) == 1:
		a[z[0]] = st
		a[fin] = z[0]
		z.pop()
	else:
		a[fin] = st
if len(z) > 0:
	st = z[0]
	for i in range(len(z)):
		ze = z[i]
		if i < len(z) - 1:
			a[ze] = z[i + 1]
		else:
			a[ze] = st
print(*a[1:])


n = int(input())
arr = list(map(int, input().split()))
frds = list(range(1, n + 1))
remain = set(frds) - set(arr)
slots = set()
for i in range(len(arr)):
	if arr[i] == 0:
		slots.add(i + 1)
same = slots & remain
for i in same:
	x = remain.pop()
	if x - 1 != i - 1:
		arr[i - 1] = x
	else:
		y = remain.pop()
		arr[i - 1] = y
		remain.add(x)
for i in range(len(arr)):
	if arr[i] == 0:
		arr[i] = remain.pop()
print(*arr, sep=' ')


def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))
n = int(input())
arr = [int(x) for x in input().split()]
indexesToFill = []
usableNumbers = set(range(1, n + 1))
for i in range(n):
	if arr[i] == 0:
		indexesToFill.append(i + 1)
	else:
		usableNumbers.remove(arr[i])
uList = list(usableNumbers)
m = len(indexesToFill)
for i in range(m):
	if indexesToFill[i] == uList[i]:
		(uList[i], uList[i - 1]) = (uList[i - 1], uList[i])
for i in range(m):
	arr[indexesToFill[i] - 1] = uList[i]
oneLineArrayPrint(arr)


n = int(input())
A = list(map(int, input().split()))
A = [i - 1 for i in A]
B = [-1] * n
for i in range(n):
	if A[i] != -1:
		B[A[i]] = i
C = [i for i in range(n) if B[i] == -1]
C.sort(key=lambda x: A[x] == B[x])
for i in range(n):
	if A[i] == -1:
		if i != C[-1]:
			A[i] = C[-1]
			C.pop()
		else:
			A[i] = C[-2]
			C.pop(-2)
print(' '.join([str(i + 1) for i in A]))


from collections import defaultdict, OrderedDict, Counter
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
from queue import Queue, PriorityQueue
from heapq import heapify, heappop, heappush
from statistics import median
from math import gcd, sqrt, floor, factorial, ceil, log2, log10
import copy
from copy import deepcopy
import sys
sys.setrecursionlimit(10 ** 7)
import math
import os
import bisect
import collections
mod = pow(10, 9) + 7
import random
from random import random, randint, randrange

def ncr(n, r, p=mod):
	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
inf = float('inf')
adj = defaultdict(set)
visited = defaultdict(int)

def addedge(a, b):
	adj[a].add(b)
	adj[b].add(a)

def bfs(v):
	q = Queue()
	q.put(v)
	visited[v] = 1
	while q.qsize() > 0:
		s = q.get_nowait()
		print(s)
		for i in adj[s]:
			if visited[i] == 0:
				q.put(i)
				visited[i] = 1

def dfs(v, visited):
	if visited[v] == 1:
		return
	visited[v] = 1
	print(v)
	for i in adj[v]:
		dfs(i, visited)

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

def get_str_list_in_int():
	return [int(i) for i in list(input())]

def get_str_list():
	return list(input())

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

def get_int():
	return int(input())

def swap(a, b):
	return (b, a)

def get_gcd():
	a = l[0]
	for i in range(len(l)):
		a = gcd(a, l[i])
	return a
nc = 'NO'
yc = 'YES'
ns = 'No'
ys = 'Yes'
t = 1
for i in range(t):
	n = get_int()
	l = get_list()
	dict = Counter(l)
	friend = 1
	arr = []
	repeted_arr = []
	for i in range(n):
		if not l[i]:
			arr.append(i)
			while friend in dict:
				friend += 1
			if friend == i + 1:
				repeted_arr.append(i)
			dict[friend] = 1
			l[i] = friend
	if len(repeted_arr) == 1:
		index1 = repeted_arr[-1]
		the_index = 0
		index2 = arr[the_index]
		while index2 == index1:
			the_index += 1
			index2 = arr[the_index]
		(l[index1], l[index2]) = swap(l[index1], l[index2])
	else:
		for index in range(len(repeted_arr) - 1):
			(l[repeted_arr[index]], l[repeted_arr[index + 1]]) = (l[repeted_arr[index + 1]], l[repeted_arr[index]])
	print(*l)


input()
f = list(map(lambda x: int(x), input().split()))
inSet = set()
outSet = set()
for i in range(len(f)):
	if f[i] != 0:
		outSet.add(i + 1)
		inSet.add(f[i])
inNotOut = inSet.difference(outSet)
outNotIn = outSet.difference(inSet)
singleSet = set(range(1, len(f) + 1)).difference(inSet).difference(outSet)
first = None
last = None
if singleSet:
	first = singleSet.pop()
	curr = first
	while len(singleSet) > 0:
		prev = curr
		curr = singleSet.pop()
		f[prev - 1] = curr
	last = curr
while len(inNotOut) > 1:
	f[inNotOut.pop() - 1] = outNotIn.pop()
if first and len(inNotOut) > 0:
	f[inNotOut.pop() - 1] = first
	f[last - 1] = outNotIn.pop()
elif len(inNotOut) > 0:
	f[inNotOut.pop() - 1] = outNotIn.pop()
else:
	f[last - 1] = first
f = list(map(lambda x: str(x), f))
print(' '.join(f))


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	n = int(input())
	f = [int(i) for i in input().split()]
	s = set(f)
	ns_nr = {i for (i, j) in enumerate(f) if j == 0 and i + 1 not in s}
	ns = [i for (i, j) in enumerate(f) if j == 0 and i not in ns_nr]
	nr = [i for i in range(n) if i + 1 not in s and i not in ns_nr]
	for i in ns_nr:
		if nr:
			f[i] = nr[0] + 1
			nr[0] = i
		elif ns:
			f[ns[0]] = i + 1
			ns[0] = i
	if not nr and (not ns):
		ns_nr = list(ns_nr)
		p = ns_nr[-1]
		for i in ns_nr:
			f[i] = p + 1
			p = i
	for (i, j) in zip(ns, nr):
		f[i] = j + 1
	print(*f)
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


n = int(input())
f = list(map(int, input().split()))
kkk = [0] * (n + 1)
for i in f:
	kkk[i] = 1
j = 1
ans = [1] + f[:]

def next(pos, a):
	while a[pos] > 0:
		pos += 1
		if pos == len(a):
			pos = 1
	return pos
xxx = next(1, ans)
r = ans.count(0)
i = xxx
w = 1
for _ in range(r - 1):
	i = next(i, ans)
	w = next(w, kkk)
	if i != w:
		ans[i] = w
		kkk[w] = 1
	else:
		w = w + 1
		if w == n + 1:
			w = 1
		w = next(w, kkk)
		ans[i] = w
		kkk[w] = 1
i = next(i, ans)
w = next(w, kkk)
if i != w:
	ans[i] = w
	kkk[w] = 1
else:
	(ans[i], ans[xxx]) = (ans[xxx], w)
print(*ans[1:])


import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
from decimal import *

class Scanner:

	@staticmethod
	def int():
		return int(sys.stdin.readline().rstrip())

	@staticmethod
	def string():
		return sys.stdin.readline().rstrip()

	@staticmethod
	def map_int():
		return [int(x) for x in Scanner.string().split()]

	@staticmethod
	def string_list(n):
		return [Scanner.string() for i in range(n)]

	@staticmethod
	def int_list_list(n):
		return [Scanner.map_int() for i in range(n)]

	@staticmethod
	def int_cols_list(n):
		return [Scanner.int() for i in range(n)]

class Math:

	@staticmethod
	def gcd(a, b):
		if b == 0:
			return a
		return Math.gcd(b, a % b)

	@staticmethod
	def lcm(a, b):
		return a * b // Math.gcd(a, b)

	@staticmethod
	def divisor(n):
		res = []
		i = 1
		for i in range(1, int(n ** 0.5) + 1):
			if n % i == 0:
				res.append(i)
				if i != n // i:
					res.append(n // i)
		return res

	@staticmethod
	def round_up(a, b):
		return -(-a // b)

	@staticmethod
	def is_prime(n):
		if n < 2:
			return False
		if n == 2:
			return True
		if n % 2 == 0:
			return False
		d = int(n ** 0.5) + 1
		for i in range(3, d + 1, 2):
			if n % i == 0:
				return False
		return True

def pop_count(x):
	x = x - (x >> 1 & 6148914691236517205)
	x = (x & 3689348814741910323) + (x >> 2 & 3689348814741910323)
	x = x + (x >> 4) & 1085102592571150095
	x = x + (x >> 8)
	x = x + (x >> 16)
	x = x + (x >> 32)
	return x & 127
MOD = int(1000000000.0) + 7
INF = int(1000000000000000.0)

def solve():
	N = Scanner.int()
	A = Scanner.map_int()
	B = []
	M = [False for _ in range(N)]
	for (i, a) in enumerate(A):
		if a == 0:
			B.append(i)
		else:
			M[a - 1] = True
	C = [i for i in range(N) if not M[i]]
	for i in range(len(B)):
		if B[i] == C[i]:
			if i + 1 < len(B):
				(C[i], C[i + 1]) = (C[i + 1], C[i])
			else:
				(C[i], C[i - 1]) = (C[i - 1], C[i])
	for i in range(len(B)):
		A[B[i]] = C[i] + 1
	print(*A)

def main():
	solve()
main()


n = int(input())
a = [0] + list(map(int, input().strip().split(' ')))
s = set([i for i in range(1, n + 1)])
for i in a[1:]:
	s.discard(i)
ns = set()
for x in s:
	if a[x] == 0:
		ns.add(x)
s = s - ns
ns = list(ns)
x = 1
if len(ns) == 1:
	x = 1
	while x <= n:
		if a[x] == 0 and x != ns[0]:
			a[x] = ns[0]
			break
		x += 1
elif len(ns) >= 2:
	a[ns[-1]] = ns[0]
	while len(ns) != 1:
		a[ns[-2]] = ns[-1]
		ns.pop()
s = list(s)
for i in range(1, n + 1):
	if a[i] == 0:
		a[i] = s[-1]
		s.pop()
print(*a[1:])


from collections import deque
n = int(input())
gives_to = [0] * (n + 1)
ini_got = set()
idx = 1
for x in input().split():
	gt = int(x)
	if gt != 0:
		gives_to[idx] = gt
		ini_got.add(gt)
	idx += 1
lr = deque()
for i in range(1, n + 1):
	if not i in ini_got:
		lr.append(i)

def solve():
	right = n
	prev = -1
	for i in range(1, n + 1):
		if gives_to[i] == 0:
			cnd = lr[-1]
			if cnd != i:
				lr.pop()
				gives_to[i] = cnd
				prev = i
			else:
				cnd = lr[0]
				if cnd != i:
					gives_to[i] = cnd
					prev = i
				else:
					prev_val = gives_to[prev]
					gives_to[prev] = cnd
					gives_to[i] = prev_val
				lr.popleft()
solve()
print(*gives_to[1:], sep=' ')


from collections import deque
import sys
import math
input = sys.stdin.buffer.readline
n = int(input())
x = list(map(int, input().split()))
a = []
b = [0 for i in range(n)]
for z in range(n):
	if x[z] == 0:
		a.append(z + 1)
	else:
		b[x[z] - 1] = 1
c = []
for z in range(n):
	if b[z] == 0:
		c.append(z + 1)
a.sort()
c.sort()
for i in range(-1, len(a) - 1):
	if a[i] == c[i]:
		t = a[i]
		a[i] = a[i + 1]
		a[i + 1] = t
for i in range(len(a)):
	x[a[i] - 1] = c[i]
print(' '.join(map(str, x)))


n = int(input())
a = [int(inp) for inp in input().split()]
r = list(range(1, n + 1)[::-1])
lz = -1
for ii in range(n):
	i = a[ii]
	if i != 0:
		r[n - i] = 0
	else:
		lz = ii
r = list(filter(lambda x: x > 0, r))
c = 0
if lz + 1 == r[-1]:
	(r[-1], r[-2]) = (r[-2], r[-1])
for ii in range(n):
	i = a[ii]
	if i != 0:
		print(i, end=' ')
	else:
		if r[c] == ii + 1:
			(r[c], r[c + 1]) = (r[c + 1], r[c])
		print(r[c], end=' ')
		c += 1
print()


from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time

def I():
	return int(input())

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

def S():
	return input()

def MS():
	return map(str, input().split())

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def StoI():
	return [ord(i) - 97 for i in input()]

def ItoS(nn):
	return chr(nn + 97)

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

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
YN = {False: 'No', True: 'Yes'}
MOD = 10 ** 9 + 7
inf = float('inf')
IINF = 10 ** 10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
show_flg = False

def main():
	N = I()
	F = LI()
	gifts_in = [0] * N
	gifts_out = [0] * N
	for i in range(N):
		F[i] -= 1
		if F[i] >= 0:
			gifts_in[F[i]] += 1
			gifts_out[i] += 1
	loops = []
	for i in range(N):
		if gifts_in[i] == 0 and gifts_out[i] == 0:
			loops.append(i)
	if len(loops) == 1:
		idx = loops[0]
		for i in range(N):
			if gifts_in[i] == 0 and i != idx:
				F[idx] = i
				gifts_in[i] += 1
				gifts_out[idx] += 1
				break
	elif len(loops) > 1:
		for i in range(len(loops)):
			cur = loops[i]
			nxt = loops[(i + 1) % len(loops)]
			F[cur] = nxt
			gifts_in[nxt] += 1
			gifts_out[cur] += 1
	ins = []
	outs = []
	for i in range(N):
		if gifts_in[i] == 0:
			ins.append(i)
		if gifts_out[i] == 0:
			outs.append(i)
	if len(outs) == len(ins):
		for i in range(len(ins)):
			F[outs[i]] = ins[i]
		print(*[f + 1 for f in F])
	else:
		print(-1)
main()


n = int(input())
friends = list(map(int, input().split()))
friends.insert(0, None)
u = []
setRcv = set(range(1, n + 1))
for (i, f) in enumerate(friends):
	if f is None:
		continue
	if f == 0:
		u.append(i)
	else:
		setRcv.remove(f)
r = list(setRcv)
r.sort()
r.reverse()
numFr = len(u)
for i in range(numFr):
	if u[i] == r[i]:
		(r[i], r[(i + 1) % numFr]) = (r[(i + 1) % numFr], r[i])
i = 0
for f in friends:
	if f is None:
		continue
	if f != 0:
		print(f, end=' ')
	else:
		print(r[i], end=' ')
		i += 1


from random import shuffle, randint
t = input()
fi = [int(j) for j in input().split()]
froms = set(range(1, len(fi) + 1))
tos = set(range(1, len(fi) + 1))
for j in range(1, len(fi) + 1):
	if fi[j - 1] != 0:
		froms.remove(j)
		tos.remove(fi[j - 1])
froms = sorted(list(froms))
tos = list(tos)
shuffle(tos)
test = True
while test:
	for i in range(len(tos)):
		if froms[i] == tos[i]:
			j = randint(0, len(tos) - 1)
			(tos[i], tos[j]) = (tos[j], tos[i])
			break
	else:
		test = False
j = 0
for i in range(len(fi)):
	if fi[i] == 0:
		fi[i] = tos[j]
		j += 1
print(*fi, sep=' ')


n = int(input())
l = [int(x) for x in input().split()]
got = set([])
for i in l:
	if i != 0:
		got.add(i)
safe = []
unsafe = []
for i in range(1, n + 1):
	if l[i - 1] == 0:
		if i in got:
			safe.append(i)
		else:
			unsafe.append(i)
voids = []
for i in range(1, n + 1):
	if i not in got:
		voids.append(i)
if len(unsafe) > 1:
	voids = set(voids)
	for i in range(len(unsafe) - 1):
		l[unsafe[i] - 1] = unsafe[i + 1]
		voids.remove(unsafe[i + 1])
	l[unsafe[len(unsafe) - 1] - 1] = unsafe[0]
	voids.remove(unsafe[0])
	voids = list(voids)
	j = 0
	for i in range(len(safe)):
		l[safe[i] - 1] = voids[j]
		j += 1
elif len(unsafe) == 1:
	for i in voids:
		if i != unsafe[0]:
			l[unsafe[0] - 1] = i
			voids = set(voids)
			voids.remove(i)
			break
	voids = list(voids)
	j = 0
	for i in range(len(safe)):
		l[safe[i] - 1] = voids[j]
		j += 1
else:
	j = 0
	for i in range(len(safe)):
		l[safe[i] - 1] = voids[j]
		j += 1
print(*l)


prev = -1
n = int(input())
f = list(map(int, input().split()))
given = []
notgiven = []
for i in range(n):
	if f[i] != 0:
		given.append(f[i])
given.sort()
j = 1
for i in range(len(given)):
	while j < given[i]:
		notgiven.append(j)
		j += 1
	j += 1
while j <= n:
	notgiven.append(j)
	j += 1
for i in range(n):
	if f[i] == 0:
		f[i] = notgiven.pop()
		if i + 1 == f[i]:
			if prev == -1:
				notgiven.append(f[i])
				f[i] = notgiven.pop(-2)
			else:
				temp = f[prev]
				f[prev] = f[i]
				f[i] = temp
		prev = i
for fi in f:
	print(fi, end=' ')


import sys
from bisect import bisect_left as bl, bisect_right as br, bisect
import math
from itertools import zip_longest as zl
from itertools import groupby as gb
from itertools import combinations as comb
from itertools import combinations_with_replacement as cwr
from collections import defaultdict as dd
from collections import deque as dq
from collections import Counter as c
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return input()

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [[val for i in range(n)] for j in range(m)]
n = int(data())
arr = l()
(index, leftout) = (list(), set([i for i in range(1, n + 1)]))
for i in range(1, n + 1):
	if arr[i - 1] == 0:
		index.append(i)
	else:
		leftout.discard(arr[i - 1])
leftout = list(leftout)
leftout = sorted(leftout, reverse=True)
sin = set(index)
for i in range(len(leftout)):
	if leftout[i] in sin and br(index, leftout[i]) == i + 1:
		if i < len(leftout) - 1:
			temp = leftout[i]
			leftout[i] = leftout[i + 1]
			leftout[i + 1] = temp
		else:
			temp = leftout[i]
			leftout[i] = leftout[i - 1]
			leftout[i - 1] = temp
		break
for i in range(len(index)):
	arr[index[i] - 1] = leftout[i]
print(*arr)


friends = int(input())
f = list(map(int, input().split()))
s = set(range(1, friends + 1))
g = s.difference(set(f))
for i in range(friends):
	if f[i] == 0:
		if i + 1 in g:
			for j in g:
				if j != i + 1:
					f[i] = j
					g.remove(j)
					break
for i in range(friends):
	if f[i] == 0:
		for j in g:
			f[i] = j
			g.remove(j)
			break
print(*f)


import sys
I = sys.stdin.readline
n = int(I())
f = list(map(int, I().split()))
x = [i for i in range(1, n + 1)]
idx = []
for i in range(n):
	if f[i] != 0:
		x[f[i] - 1] = 0
	else:
		idx.append(i + 1)
left = [i for i in x if i != 0]
for i in range(len(left)):
	if idx[i] == left[i]:
		if i == len(left) - 1:
			(left[i], left[i - 1]) = (left[i - 1], left[i])
		else:
			(left[i], left[i + 1]) = (left[i + 1], left[i])
j = 0
for i in range(n):
	if f[i] == 0:
		f[i] = left[j]
		j += 1
print(*f)


import sys, math
MOD = 998244353
n = int(input())
a = list(map(int, input().split()))
s = {i for i in range(1, n + 1)}
t = {i for i in range(1, n + 1)}
for i in range(n):
	if a[i] != 0:
		s.remove(a[i])
		t.remove(i + 1)
c = s & t
(s, t) = (s - c, t - c)
(c, s, t) = (sorted(c), sorted(s), sorted(t))
if len(c) == 1:
	a[c[0] - 1] = s.pop()
	s.append(c.pop())
elif len(c) > 1:
	for i in range(len(c)):
		a[c[i] - 1] = c[i - 1]
for i in range(len(t)):
	a[t[i] - 1] = s[i]
print(*a)


import sys
from sys import stdin, stdout
import bisect
import math
import heapq

def modinv(n, p):
	return pow(n, p - 2, p)

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())
import math

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l

def main():
	n = inin()
	a = ain()
	d = {}
	p = -1
	ind = 0
	for i in a:
		if p == -1 and i == 0:
			p = ind
		d[i] = 1
		ind += 1
	b = []
	for i in range(1, n + 1):
		if i not in d:
			b.append(i)
	for i in range(n):
		if a[i] == 0:
			if i + 1 == b[-1]:
				if p == i:
					b = b[::-1]
				a[i] = b.pop()
				(a[i], a[p]) = (a[p], a[i])
			else:
				a[i] = b.pop()
	print(*a)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()


n = int(input())
l2 = [int(a) for a in input().split()]
l3 = []
l4 = []
for i in range(n + 1):
	l3.append(0)
for i in range(n):
	l3[l2[i]] = 1
for i in range(1, n + 1):
	if l3[i] == 0:
		l4.append(i)
c = 0
a2 = 0
a1 = 0
for i in range(n):
	if l2[i] == 0:
		if i + 1 == l4[c]:
			if c != len(l4) - 1:
				a1 = l4[c]
				l4[c] = l4[c + 1]
				l4[c + 1] = a1
			else:
				a1 = l4[c - 1]
				l4[c - 1] = l4[c]
				l4[c] = a1
				l2[a2] = l4[c - 1]
			l2[i] = l4[c]
			a2 = i
			c += 1
		else:
			l2[i] = l4[c]
			a2 = i
			c += 1
	else:
		pass
for i in range(n):
	print(l2[i], end=' ')


n = int(input())
arr = list(map(int, input().split()))
d1 = set()
for i in range(1, n + 1):
	d1.add(i)
d2 = set()
for i in range(n):
	if arr[i] == 0:
		d2.add(i + 1)
	else:
		d1.remove(arr[i])
f1 = list(d1)
f2 = list(d2)
f = len(f2)
for i in range(f):
	if f2[i] == f1[i]:
		if i < f - 1:
			(f1[i], f1[i + 1]) = (f1[i + 1], f1[i])
		else:
			(f1[i], f1[0]) = (f1[0], f1[i])
for i in range(f):
	arr[f2[i] - 1] = f1[i]
print(*arr)


n = int(input())
fri = list(map(int, input().split()))
who_pres = list(map(lambda x: x + 1, [i for i in range(n) if fri[i] == 0]))
to_pres = list(set(range(1, n + 1)) - set(fri))
who_pres.sort()
to_pres.sort()
to_pres.reverse()
j = 0
for u in range(len(to_pres)):
	if to_pres[u] == who_pres[u]:
		(to_pres[u - 1], to_pres[u]) = (to_pres[u], to_pres[u - 1])
for i in who_pres:
	fri[i - 1] = to_pres[j]
	j += 1
print(' '.join(map(str, fri)))


import sys
from random import choice, randint
inp = sys.stdin.readline
out = sys.stdout.write
flsh = sys.stdout.flush
sys.setrecursionlimit(10 ** 9)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def MI():
	return map(int, inp().strip().split())

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

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines().strip()]

def LI_():
	return [int(x) - 1 for x in inp().strip().split()]

def LF():
	return [float(x) for x in inp().strip().split()]

def LS():
	return inp().strip().split()

def I():
	return int(inp().strip())

def F():
	return float(inp().strip())

def S():
	return inp().strip()

def pf(s):
	return out(s + '\n')

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def main():
	from collections import deque
	n = I()
	a = LI()
	d = dict()
	for i in range(n):
		if a[i] not in d and a[i] != 0:
			d[a[i]] = 1
	l = deque()
	for i in range(n):
		if i + 1 not in d:
			l.append(i + 1)
	z = []
	for i in range(n):
		if a[i] == 0:
			z.append(i + 1)
	for i in range(n):
		if a[i] == 0 and i + 1 != l[0]:
			if len(l) == 2 and z[-1] == l[1]:
				a[i] = l[1]
				l.pop()
			else:
				a[i] = l[0]
				l.popleft()
		elif a[i] == 0 and i + 1 == l[0]:
			while i + 1 == l[0]:
				x = l.popleft()
				l.append(x)
			a[i] = l[0]
			l.popleft()
	print(*a)
main()


n = int(input())
a = list(map(int, input().split()))
gotGifts = {}
rem = []
for i in range(n):
	if a[i] != 0:
		gotGifts[a[i]] = 1
	else:
		rem.append(i + 1)
left = []
l = 0
for i in range(1, n + 1):
	if gotGifts.get(i, 0) == 0:
		left.append(i)
		l += 1
j = 0
for i in range(n):
	if a[i] == 0:
		if left[j] == i + 1:
			(left[j], left[l - 1]) = (left[l - 1], left[j])
		elif j == l - 2:
			if left[l - 1] == rem[j + 1]:
				(left[j], left[l - 1]) = (left[l - 1], left[j])
		a[i] = left[j]
		j += 1
for i in a:
	print(i, end=' ')
print('')


n = int(input())
arr = list(map(int, input().strip().split()))[:n]
from collections import defaultdict
store = defaultdict(int)
for num in arr:
	store[num] += 1
problematic = []
safe = []
places = []
for i in range(n):
	if store[i + 1] == 0 and arr[i] == 0:
		problematic.append(i)
	elif store[i + 1] == 0:
		safe.append(i)
	elif arr[i] == 0:
		places.append(i)
if len(problematic) == 1:
	arr[places[0]] = problematic[0] + 1
	arr[problematic[0]] = safe[0] + 1
	for i in range(1, len(safe)):
		arr[places[i]] = safe[i] + 1
elif len(problematic) > 1:
	for i in range(len(problematic) - 1):
		arr[problematic[i]] = problematic[i + 1] + 1
	arr[problematic[len(problematic) - 1]] = problematic[0] + 1
	for i in range(len(safe)):
		arr[places[i]] = safe[i] + 1
else:
	print
	for i in range(len(safe)):
		arr[places[i]] = safe[i] + 1
for num in arr:
	print(num, end=' ')


n = int(input())
l = []
for i in range(n + 1):
	l.append(0)
a = [int(x) for x in input().split()]
for i in a:
	l[i] = 1
b = []
for i in range(1, n + 1):
	if l[i] == 0:
		b.append(i)
b.sort()
n1 = len(b)
j = 1
c = []
for i in range(n):
	if a[i] == 0:
		c.append(i)
		a[i] = b[j % n1]
		j += 1
j = 0
n2 = len(c)
for i in range(n):
	if a[i] == i + 1:
		if c[j % n2] == i:
			j += 1
		temp = a[c[j % n2]]
		a[c[j % n2]] = a[i]
		a[i] = temp
for i in range(n):
	print(a[i], end=' ')
print()


n = int(input())
arr = [int(x) for x in input().split()]
ha = []
for i in range(n + 1):
	ha.append(0)
for i in arr:
	ha[i] = 1
give = []
take = []
for i in range(len(ha)):
	if ha[i] == 0:
		take.append(i)
for i in range(len(arr)):
	if arr[i] == 0:
		give.append(i + 1)
for i in range(len(give)):
	if i == 0:
		if give[i] == take[i]:
			temp = take[i]
			take[i] = take[len(take) - 1]
			take[len(take) - 1] = temp
	if take[i] == give[i]:
		temp = take[i]
		take[i] = take[i - 1]
		take[i - 1] = temp
for i in range(len(give)):
	arr[give[i] - 1] = take[i]
print(*arr)


n = int(input())
lis = list(map(int, input().split()))
a = []
b = []
has = [0] * (n + 1)
for i in range(n):
	if lis[i] == 0:
		a.append(i + 1)
	else:
		has[lis[i]] = 1
for i in range(1, n + 1):
	if has[i] == 0:
		b.append(i)
for i in range(len(a)):
	if a[i] == b[i]:
		if i == 0:
			(b[i], b[1]) = (b[1], b[i])
		else:
			(b[i], b[0]) = (b[0], b[i])
for i in range(len(a)):
	lis[a[i] - 1] = b[i]
print(*lis)


n = int(input())
f = list(map(int, input().split()))
ins = [0] * n
outs = [0] * n
for i in range(n):
	f[i] = f[i] - 1
	if f[i] != -1:
		ins[f[i]] = ins[f[i]] + 1
		outs[i] = outs[i] + 1
radicals = []
for i in range(n):
	if ins[i] == 0 and outs[i] == 0:
		radicals.append(i)
if len(radicals) == 1:
	for i in range(n):
		if ins[i] == 0 and radicals[0] != i:
			f[radicals[0]] = i
			ins[i] = 1
			outs[radicals[0]] = 1
			radicals.pop()
			break
elif len(radicals) > 1:
	for r in range(len(radicals)):
		first = radicals[r]
		second = radicals[(r + 1) % len(radicals)]
		outs[first] = 1
		ins[second] = 1
		f[first] = second
ins_1 = []
outs_1 = []
for i in range(n):
	if ins[i] == 0:
		ins_1.append(i)
	if outs[i] == 0:
		outs_1.append(i)
if len(ins_1) != len(outs_1):
	print('OH! NO!')
	exit()
for i in range(len(ins_1)):
	f[outs_1[i]] = ins_1[i]
for i in range(n):
	print(f[i] + 1, end=' ')


def solve(n, f):
	wantToGiveTo = {}
	undecidedPerson = []
	receivedGift = [0] * (n + 1)
	notReceivedGift = []
	ans = ''
	for i in range(1, n + 1):
		wantToGiveTo[i] = f[i - 1]
		if f[i - 1] == 0:
			undecidedPerson.append(i)
		if f[i - 1] != 0:
			receivedGift[f[i - 1]] = 1
	for i in range(1, len(receivedGift)):
		if receivedGift[i] == 0:
			notReceivedGift.append(i)
	undecidedAndNotReceivedGift = list(set(undecidedPerson) & set(notReceivedGift))
	newReceiver = {}
	if len(undecidedAndNotReceivedGift) > 1:
		for (i, p) in enumerate(undecidedAndNotReceivedGift):
			destination = (i + 1) % len(undecidedAndNotReceivedGift)
			receiver = undecidedAndNotReceivedGift[destination]
			wantToGiveTo[p] = receiver
			newReceiver[receiver] = True
	elif len(undecidedAndNotReceivedGift) == 1:
		p = undecidedAndNotReceivedGift[0]
		j = 0
		while notReceivedGift[j] == p:
			j += 1
		receiver = notReceivedGift[j]
		wantToGiveTo[p] = receiver
		newReceiver[receiver] = True
	j = 0
	for (i, p) in enumerate(undecidedPerson):
		if wantToGiveTo[p] == 0:
			while notReceivedGift[j] in newReceiver:
				j += 1
			receiver = notReceivedGift[j]
			wantToGiveTo[p] = receiver
			newReceiver[receiver] = True
	for i in range(1, n + 1):
		ans += str(wantToGiveTo[i]) + ' '
	return ans
n = int(input())
f = list(map(int, input().split()))
print(solve(n, f))


import sys
input = sys.stdin.readline
n = int(input())
f = list(map(int, input().split()))
ng = []
not_receive = [True] * n
ans = [-1] * n
for i in range(n):
	if f[i] != 0:
		not_receive[f[i] - 1] = False
		ans[i] = f[i] - 1
	else:
		ng.append(i)
nr = [i for i in range(n) if not_receive[i]]
both = list(set(ng) & set(nr))
if len(both) == 0:
	for i in range(len(ng)):
		ans[ng[i]] = nr[i]
elif len(both) == 1:
	ng2 = [ng_i for ng_i in ng if ng_i != both[0]] + [both[0]]
	nr2 = [both[0]] + [nr_i for nr_i in nr if nr_i != both[0]]
	for i in range(len(ng)):
		ans[ng2[i]] = nr2[i]
else:
	for i in range(len(both)):
		ans[both[i]] = both[(i + 1) % len(both)]
	sboth = set(both)
	nr2 = [nr_i for nr_i in nr if nr_i not in sboth]
	nr2_idx = 0
	for i in range(len(ng)):
		if ng[i] not in sboth:
			ans[ng[i]] = nr2[nr2_idx]
			nr2_idx += 1
ans = list(map(lambda x: x + 1, ans))
print(*ans)


n = int(input())
list1 = [int(x) for x in input().split()]
list2 = set(range(1, n + 1)) - set(list1)
list2 = list(list2)
list2.reverse()
c = 0
prev = 0
for i in range(n):
	if list1[i] == 0:
		if i + 1 != list2[c]:
			list1[i] = list2[c]
			c += 1
		elif c != len(list2) - 1:
			list1[i] = list2[-1]
			list2.pop(-1)
		else:
			list1[i] = list2[-1]
			list2.pop(-1)
			(list1[i], list1[prev]) = (list1[prev], list1[i])
		prev = i
for x in list1:
	print(x, end=' ')


from collections import defaultdict as dc
from collections import deque as dq
from bisect import bisect_left, bisect_right, insort_left
import sys
import math
mod = 10 ** 9 + 7

def bs(a, x):
	i = bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return len(a)

def binarysearchforsolvingeqautions(a, i, l, r):
	while 1:
		mid = (l + r) / 2
		(p, q) = force(a, mid, i)
		if abs(p - q) < 1e-13:
			return mid
		elif p > q:
			l = mid
		else:
			r = mid

def bs(a, b):
	l = a
	r = b + 1
	x = b
	ans = 0
	while l < r:
		mid = (l + r) // 2
		if x | mid > ans:
			ans = x | mid
			l = mid + 1
		else:
			r = mid
	return ans

def digit(n):
	a = []
	while n > 0:
		a.append(n % 10)
		n = n // 10
	return a

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

def line():
	p = list(map(int, input().split()))
	return p
n = inp()
a = line()
p = dc(int)
q = []
r = []
for i in range(n):
	p[a[i]] = 1
	if a[i] == 0:
		q.append(i + 1)
for i in range(1, n + 1):
	if p[i] == 0:
		r.append(i)
i = 0
while i < len(q):
	if q[i] != r[i]:
		a[q[i] - 1] = r[i]
		i += 1
	elif i < len(q) - 1:
		a[q[i] - 1] = r[i + 1]
		a[q[i + 1] - 1] = r[i]
		i += 2
	elif a[q[0] - 1] != r[i]:
		(a[q[0] - 1], a[r[i] - 1]) = (r[i], a[q[0] - 1])
		i += 1
	else:
		(a[q[1] - 1], a[r[i] - 1]) = (r[i], a[q[1] - 1])
		i += 1
print(*a)


from sys import stdout

def solution(t):
	outd = [0] * t
	ind = [0] * t
	arr = list(map(lambda x: int(x) - 1, input().split()))
	for (i, v) in enumerate(arr):
		if v != -1:
			outd[i] = 1
			ind[v] = 1
	loops = []
	for i in range(t):
		if not ind[i] and (not outd[i]):
			loops.append(i)
	n1 = len(loops)
	if n1 == 1:
		u = loops[0]
		for i in range(t):
			if not ind[i] and i != u:
				arr[u] = i
				outd[u] = 1
				ind[i] = 1
				break
	elif n1 > 1:
		for i in range(n1):
			cur = loops[i]
			nxt = loops[(i + 1) % n1]
			arr[cur] = nxt
			outd[cur] = 1
			ind[nxt] = 1
	ins = []
	outs = []
	for i in range(t):
		if not ind[i]:
			ins.append(i)
		if not outd[i]:
			outs.append(i)
	for i in range(len(outs)):
		arr[outs[i]] = ins[i]
	stdout.write(' '.join(map(lambda x: str(x + 1), arr)))

def main():
	t = int(input())
	solution(t)
main()


x = int(input())
k = input().split(' ')
s = [len(k) - int(i) for i in range(0, len(k))]
q = []
p = []
for i in range(len(k)):
	if k[i] == '0':
		q.append(i)
	else:
		s[len(s) - int(k[i])] = -1
for i in range(len(s)):
	if s[i] != -1:
		p.append(s[i])
i = 0
j = len(p) - 1
o = 0
while i < len(q):
	if q[i] + 1 == p[o]:
		k[q[i % len(q)]] = str(p[(o + 1) % len(p)])
		k[q[(i + 1) % len(q)]] = str(p[o % len(p)])
		o += 1
		i += 1
	else:
		k[q[i]] = str(p[o])
	o += 1
	i += 1
print(' '.join(k))


n = int(input())
from collections import deque
x = [int(n) for n in input().split()]
a = {}
r = []
for i in range(1, n + 1):
	a[i] = 0
for i in range(n):
	if x[i] == 0:
		r.append(i)
	a[x[i]] = 1
q = deque()
for i in a:
	if a[i] == 0:
		q.append(i)
for i in range(n):
	if x[i] == 0:
		if i + 1 != q[0]:
			x[i] = q[0]
			q.popleft()
		else:
			w = q.popleft()
			q.append(w)
			x[i] = q[0]
			q.popleft()
for i in range(len(x)):
	if i + 1 == x[i]:
		f = 1
		while f:
			for j in r:
				if j == i:
					continue
				else:
					(x[i], x[j]) = (x[j], x[i])
					f = 0
					break
print(*x)


from sys import stdout

def solution(t):
	arr = [0] * t
	outd = [0] * t
	ind = [0] * t
	for (i, v) in enumerate(input().split()):
		v = int(v) - 1
		arr[i] = v
		if v != -1:
			outd[i] += 1
			ind[v] += 1
	loops = []
	for i in range(t):
		if ind[i] == 0 and outd[i] == 0:
			loops.append(i)
	if len(loops) == 1:
		u = loops[0]
		for i in range(t):
			if ind[i] == 0 and i != u:
				arr[u] = i
				outd[u] += 1
				ind[i] += 1
				break
	elif len(loops) > 1:
		for i in range(len(loops)):
			cur = loops[i]
			nxt = loops[(i + 1) % len(loops)]
			arr[cur] = nxt
			outd[cur] += 1
			ind[nxt] += 1
	ins = []
	outs = []
	try:
		for i in range(t):
			if ind[i] == 0:
				ins.append(i)
			if outd[i] == 0:
				outs.append(i)
		for i in range(len(outs)):
			arr[outs[i]] = ins[i]
	except Exception as e:
		print(len(ins), ins)
		print(len(outs), outs)
	print(' '.join(map(lambda x: str(x + 1), arr)))

def main():
	t = int(input())
	solution(t)
main()


n = int(input())
arr = [int(p) for p in input().split()]
s = set(arr)
missing = []
init = []
pr = []
for i in range(1, n + 1):
	if i not in s:
		init.append(i)
for i in range(len(init)):
	if arr[init[i] - 1] == 0:
		pr.append(init[i])
	else:
		missing.append(init[i])
if len(missing) == 0:
	ele = pr.pop()
	pr.insert(0, ele)
	j = 0
	for i in range(n):
		if arr[i] == 0:
			arr[i] = pr[j]
			j += 1
elif len(pr) == 0:
	j = 0
	for i in range(n):
		if arr[i] == 0:
			arr[i] = missing[j]
			j += 1
else:
	j = 0
	for i in range(len(pr)):
		if j < len(missing):
			arr[pr[i] - 1] = missing[j]
			j += 1
			missing.append(pr[i])
	for i in range(n):
		if arr[i] == 0:
			arr[i] = missing[j]
			j += 1
print(*arr)


def main():
	n = int(input())
	ff = [int(a) for a in input().split()]
	nf = set(range(1, n + 1))
	uf = set()
	for (i, f) in enumerate(ff, 1):
		if f == 0:
			uf.add(i)
		else:
			nf.remove(f)
	common = uf & nf
	nfonly = nf - common
	ufonly = uf - common
	if len(common) == 1:
		c = common.pop()
		ff[c - 1] = nfonly.pop()
		ff[ufonly.pop() - 1] = c
	elif common:
		first = common.pop()
		prev = first
		for c in common:
			ff[prev - 1] = c
			prev = c
		ff[prev - 1] = first
	for (u, n) in zip(ufonly, nfonly):
		ff[u - 1] = n
	print(' '.join(map(str, ff)))
main()


t = int(input())
a = list(map(int, input().split()))
(ans, res, temp) = (0, 0, 0)
(b, c, d) = ([], [], [0] * t)
for i in range(t):
	if a[i] == 0:
		b.append(i)
	else:
		d[a[i] - 1] = 1
for i in range(t):
	if d[i] == 0:
		c.append(i)
for i in range(len(b)):
	if b[i] == c[i]:
		if i == 0:
			(c[i], c[1]) = (c[1], c[i])
		else:
			(c[i], c[0]) = (c[0], c[i])
for i in range(len(b)):
	a[b[i]] = c[i] + 1
print(*a)


n = int(input())
a = list(map(int, input().split()))
l2 = set()
for i in range(n):
	l2.add(i + 1)
l1 = []
for i in range(n):
	if a[i] == 0:
		l1.append(i + 1)
	else:
		l2.remove(a[i])
l2se = l2
l2 = list(l2)
first = 0
second = 1
for i in l1:
	if i in l2se:
		if l2[first] == i:
			a[i - 1] = l2[second]
			second += 1
		else:
			a[i - 1] = l2[first]
			(first, second) = (second, second + 1)
		l2se.remove(a[i - 1])
l2 = list(l2se)
count = 0
for i in range(n):
	if a[i] == 0:
		a[i] = l2[count]
		count += 1
print(' '.join((str(k) for k in a)))


from sys import stdin, stdout
for _ in range(1):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	ind = [0] * (n + 1)
	outdegree = [0] * (1 + n)
	root = []
	left = []
	for i in range(n):
		if a[i] != 0:
			ind[a[i]] += 1
			outdegree[i + 1] += 1
	for i in range(1, 1 + n):
		if ind[i] == outdegree[i] == 0:
			left += [i]
		elif ind[i] == 0 and outdegree[i] == 1:
			root += [i]
	for node in root[1:]:
		cur = a[node - 1]
		while a[cur - 1] > 0:
			cur = a[cur - 1]
		a[cur - 1] = node
	if not root:
		des = left[0]
		for v in left[1:]:
			a[des - 1] = v
			des = v
		a[des - 1] = left[0]
	else:
		r1 = root[0]
		end = 0
		des = r1
		while a[des - 1] > end:
			des = a[des - 1]
		for mid in left:
			a[des - 1] = mid
			des = mid
		a[des - 1] = r1
	print(*a)


x = int(input())
s = list(map(int, input().split()))
sj = s.copy()
st = set()
for n in s:
	if n:
		st.add(n)
j = []
for n in range(1, x + 1):
	if n not in st:
		j.append(n)
j.sort()
pos = 1
tem = j.copy()
while pos:
	pos = 0
	for n in range(x):
		if s[n] == 0 and j[-1] != n + 1:
			pos = 1
			s[n] = j[-1]
			j.pop()
vv = 0
for n in s:
	if not n:
		vv = 1
		break
if vv:
	s = sj
tem.reverse()
j = tem
pos = 1
while pos:
	pos = 0
	for n in range(x):
		if s[n] == 0 and j[-1] != n + 1:
			pos = 1
			s[n] = j[-1]
			j.pop()
print(*s)


ls = []
l = []
n = int(input())
x = []
d = dict()
for i in range(1, n + 1):
	d[i] = 1
ls = [int(x) for x in input().split()]
for i in range(len(ls)):
	if ls[i] != 0:
		d[ls[i]] = 0
	else:
		l.append(i + 1)
for i in range(1, n + 1):
	if d[i] == 1:
		x.append(i)
for i in range(len(l)):
	if l[i] == x[i]:
		get = (x[i], x[(i + 1) % len(l)])
		(x[(i + 1) % len(l)], x[i]) = get
for i in range(len(l)):
	ls[l[i] - 1] = x[i]
print(' '.join((str(x) for x in ls)))


def buscar(vis, i, j, n):
	while True:
		if i > n:
			i = 1
		if vis[i] == 0 and i != j:
			return i
		i += 1
n = int(input())
arr = [0] + list(map(int, input().split()))
vis = [0] * (n + 1)
for i in range(1, n + 1):
	x = i
	while True:
		x = arr[x]
		if vis[x]:
			break
		vis[x] = 1
j = 1
for i in range(1, n + 1):
	if arr[i] == 0 and 0 == vis[i]:
		j = buscar(vis, j, i, n)
		arr[i] = j
		vis[j] = 1
j = 1
for i in range(1, n + 1):
	if arr[i] == 0:
		j = buscar(vis, j, i, n)
		arr[i] = j
		vis[j] = 1
for i in range(1, n + 1):
	print(arr[i], end=' ')


n = int(input())
f = [int(x) for x in input().split()]
pr = set(f)
ans = []
miss = []
for i in range(1, n + 1):
	if i not in pr:
		ans.append(i)
	if f[i - 1] == 0:
		miss.append(i - 1)
for ms in miss:
	if ms != ans[-1] - 1:
		f[ms] = ans[-1]
		key = ans[-1]
		ind = ms
		ans.pop()
	elif len(ans) > 1:
		f[ms] = ans[-2]
		ans.pop(-2)
		key = ans[-1]
		ind = ms
	else:
		f[ms] = key
		f[ind] = ans[-1]
print(*f)


a = int(input())
z = list(map(int, input().split()))
t = [0 for i in range(a)]
gam = []
for i in range(len(z)):
	if z[i] != 0:
		t[z[i] - 1] = 1
	else:
		gam.append(i)
gam.sort()
rec = []
for i in range(len(t)):
	if t[i] == 0:
		rec.append(i)
rec.sort()
fin = []
for i in range(len(gam)):
	if gam[i] == rec[i]:
		fin.append(gam[i])
	z[gam[i]] = rec[i] + 1
if len(fin) == 0:
	print(' '.join(map(str, z)))
elif len(fin) == 1:
	if gam[0] != fin[0]:
		temp = z[gam[0]]
		z[fin[0]] = temp
		z[gam[0]] = fin[0] + 1
	else:
		temp = z[gam[1]]
		z[fin[0]] = temp
		z[gam[1]] = fin[0] + 1
	print(' '.join(map(str, z)))
else:
	fin.sort()
	for i in range(1, len(fin)):
		temp = z[fin[i]]
		z[fin[i]] = z[fin[i - 1]]
		z[fin[i - 1]] = temp
	print(' '.join(map(str, z)))


from collections import deque
n = int(input())
a = [int(i) for i in input().split()]
b = [0 for i in range(n)]
for i in range(len(a)):
	if a[i] != 0:
		b[a[i] - 1] = 1
b0 = deque()
for i in range(len(a)):
	if b[i] == 0:
		b0.append(i)
for i in range(len(a)):
	if a[i] == b[i] == 0:
		if b0[0] == i:
			l = b0.pop()
		else:
			l = b0.popleft()
		a[i] = l + 1
		b[l] = 1
for i in range(len(a)):
	if a[i] == 0:
		a[i] = b0[0] + 1
		b0.popleft()
for i in range(len(a)):
	print(a[i], end=' ')


n = int(input())
arr = list(map(int, input().split()))
dp = [0] * (n + 1)
for i in arr:
	if i > 0:
		dp[i] += 1
A = []
for i in range(1, n + 1):
	if dp[i] == 0:
		A.append(i)
p1 = 0
for i in range(n):
	if arr[i] == 0 and A[p1] == i + 1:
		(A[p1 - 1], A[p1]) = (A[p1], A[p1 - 1])
		p1 += 1
	elif arr[i] == 0:
		p1 += 1
k = 0
for i in range(n):
	if arr[i] == 0:
		arr[i] = A[k]
		k += 1
print(*arr)


n = int(input())
a = list(map(int, input().split()))
s = set(a)
free = []
for v in range(1, n + 1):
	if v not in s:
		free.append(v)
pos = 0
prev = None
for (i, v) in enumerate(a):
	if not v:
		if free[pos] == i + 1:
			if pos + 1 < len(free):
				(free[pos], free[pos + 1]) = (free[pos + 1], free[pos])
			else:
				(free[pos], free[pos - 1]) = (free[pos - 1], free[pos])
				a[prev] = free[pos - 1]
		a[i] = free[pos]
		prev = i
		pos += 1
print(*a)


from sys import stdin
n = int(stdin.readline())
arr = list(map(int, stdin.readline().split()))
ans = [True] * n
case = []
for i in range(n):
	if arr[i] == 0:
		case.append(i + 1)
	else:
		ans[arr[i] - 1] = False
case2 = []
for i in range(n):
	if ans[i] == True:
		case2.append(i + 1)
	else:
		pass
s = len(case)
i = 0
while i < s:
	if case[i] == case2[s - 1 - i]:
		if i == 0:
			m = case2[s - 2]
			arr[case[i + 1] - 1] = case2[s - i - 1]
			arr[case[i] - 1] = m
			i += 1
		else:
			m = arr[case[i - 1] - 1]
			arr[case[i - 1] - 1] = case2[s - i - 1]
			arr[case[i] - 1] = m
	else:
		arr[case[i] - 1] = case2[s - i - 1]
	i += 1
print(*arr)


n = int(input())
gotten = list(map(int, input().split(' ')))
inps = list()
preinps = dict()
otps = list()
preotps = dict()
voids = list()
happy = list()
for i in range(1, n + 1):
	if gotten[i - 1] != 0:
		preotps[i] = 1
		preinps[gotten[i - 1]] = 1
for i in range(1, n + 1):
	if preinps.get(i):
		if not preotps.get(i):
			inps.append(i)
	elif preotps.get(i):
		otps.append(i)
	else:
		voids.append(i)
if voids:
	if inps:
		gotten[inps[0] - 1] = voids[0]
		gotten[voids[-1] - 1] = otps[0]
		for i in range(len(voids) - 1):
			gotten[voids[i] - 1] = voids[i + 1]
		for i in range(1, len(otps)):
			gotten[inps[i] - 1] = otps[i]
	else:
		gotten[voids[-1] - 1] = voids[0]
		for i in range(len(voids) - 1):
			gotten[voids[i] - 1] = voids[i + 1]
else:
	for i in range(0, len(otps)):
		gotten[inps[i] - 1] = otps[i]
for g in gotten:
	print(g, end=' ')


n = int(input())
F = list(map(int, input().split()))
total = set([i for i in range(1, n + 1)])
getting = set()
for i in range(n):
	if F[i] > 0:
		getting.add(F[i])
remainGet = total - getting
for i in range(n):
	if F[i] == 0:
		if i + 1 in remainGet:
			popped = remainGet.pop()
			if popped == i + 1:
				F[i] = remainGet.pop()
				remainGet.add(popped)
			else:
				F[i] = popped
for i in range(n):
	if F[i] == 0:
		F[i] = remainGet.pop()
for f in F:
	print(f, end=' ')


n = int(input())
visited = [0 for i in range(n)]
ls = []
f = input().split()
for i in range(n):
	f[i] = int(f[i])
	if f[i] > 0:
		visited[f[i] - 1] = 1
	else:
		ls.append(i)
j = 0
flag = 0
for i in range(n):
	if visited[i] == 0:
		if j < len(ls) - 2:
			if ls[j] != i:
				f[ls[j]] = i + 1
				j += 1
			else:
				f[ls[j + 1]] = i + 1
				ls[j + 1] = ls[j]
				j += 1
		elif j == len(ls) - 2:
			if ls[j] != i:
				f[ls[j]] = i + 1
				flag = ls[j]
				j += 1
			else:
				f[ls[j + 1]] = i + 1
				flag = ls[j + 1]
				ls[j + 1] = ls[j]
				j += 1
		elif ls[j] != i:
			f[ls[j]] = i + 1
			j += 1
		else:
			f[ls[j]] = f[flag]
			f[flag] = i + 1
print(*f)


from collections import Counter, defaultdict, deque
import heapq as hq
import math
import sys
input = sys.stdin.readline
n = int(input())
arr = [int(x) for x in input().split()]
s = set(arr)
free = deque((x for x in range(1, n + 1) if x not in s))
prevind = -1
for i in range(n):
	if arr[i] == 0:
		p = free.popleft()
		if len(free) == 1:
			prevind = i
		if p == i + 1:
			if prevind != -1 and len(free) == 0:
				arr[i] = arr[prevind]
				arr[prevind] = p
				break
			free.append(p)
			p = free.popleft()
		arr[i] = p
print(*arr)


import sys, math, random
sys.setrecursionlimit(20000000)
input = sys.stdin.readline

def cin1():
	return int(input())

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

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

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

def ok(a, b):
	for i in range(len(a)):
		if a[i] == b[i]:
			return False
	return True
n = cin1()
ara = cinara()
a = []
b = []
cnt = [0] * n
for i in range(n):
	if ara[i]:
		cnt[ara[i] - 1] = 1
for i in range(n):
	if ara[i] == 0:
		a.append(i + 1)
	if cnt[i] == 0:
		b.append(i + 1)
while not ok(a, b):
	random.shuffle(a)
	random.shuffle(b)
for i in range(len(a)):
	ara[a[i] - 1] = b[i]
print(*ara)


n = int(input())
a = list(map(int, input().split()))
outed = [0] * (n + 1)
ined = [0] * (n + 1)
for i in range(n):
	if a[i] > 0:
		outed[i + 1] += 1
		ined[a[i]] += 1
x = []
for i in range(1, n + 1):
	if outed[i] == 0 and ined[i] == 0:
		x.append(i)
if len(x) == 1:
	for i in range(1, n + 1):
		if ined[i] == 0 and outed[i] == 1:
			outed[x[0]] += 1
			ined[i] += 1
			a[x[0] - 1] = i
			break
else:
	for i in range(1, len(x)):
		outed[x[i - 1]] += 1
		ined[x[i]] += 1
		a[x[i - 1] - 1] = x[i]
(l, r) = ([], [])
for i in range(1, n + 1):
	if outed[i] == 1 and ined[i] == 0:
		l.append(i)
	if ined[i] == 1 and outed[i] == 0:
		r.append(i)
for i in range(len(l)):
	a[r[i] - 1] = l[i]
print(*a)


t = int(input())
r = [x for x in range(1, t + 1)]
ll = list(map(int, input().split()))
l = list(set(r).difference(ll))

def solve(ll, l):
	for i in range(len(ll)):
		if ll[i] == 0:
			j = len(l) - 1
			while j >= 0:
				if l[j] != i + 1:
					ll[i] = l.pop(j)
					break
				j -= 1
			if ll[i] == 0:
				(ll[prev], ll[i]) = (l.pop(), ll[prev])
			prev = i
	return ' '.join(list(map(str, ll)))
print(solve(ll, l))


n = int(input())
f = list(map(int, input().split()))
rec = []
give = []
oth = [0 for _ in range(n)]
for i in range(n):
	if f[i] == 0:
		give.append(i)
	else:
		oth[f[i] - 1] = 1
for j in range(n):
	if not oth[j]:
		rec.append(j)
for i in range(len(give)):
	if give[i] == rec[i]:
		if i == 0:
			s = give[i]
			give[i] = give[i + 1]
			give[i + 1] = s
		else:
			s = give[i]
			give[i] = give[i - 1]
			give[i - 1] = s
for k in range(len(give)):
	f[give[k]] = rec[k] + 1
print(*f)


n = int(input())
a = list(map(int, input().split()))
freq = [0] * (n + 1)
for x in a:
	freq[x] = 1
unused = []
for x in range(1, n + 1):
	if not freq[x]:
		unused.append(x)
unused.reverse()
j = 0
for i in range(n):
	if a[i] == 0:
		if unused[j] == i + 1:
			(unused[j], unused[j - 1]) = (unused[j - 1], unused[j])
		j += 1
j = 0
for (i, x) in enumerate(a):
	if x == 0:
		a[i] = unused[j]
		j += 1
print(*a)


n = int(input())
arr = [0 for i in range(n)]
l = input().split()
li = [int(i) for i in l]
for i in li:
	if i != 0:
		arr[i - 1] += 1
curr = 0
l1 = []
l2 = []
hashik = dict()
for i in range(n):
	if li[i] == 0:
		l1.append(i)
		hashik[i] = len(l1) - 1
hashim = dict()
for i in range(n):
	if arr[i] == 0:
		l2.append(i)
		hashim[i] = len(l2) - 1
l3 = []
z = len(hashim)
curr = 0
done = [0 for i in range(z)]
perm = [0 for i in range(z)]
for i in range(z):
	if l1[i] in hashim:
		perm[i] = hashim[l1[i]]
		done[hashim[l1[i]]] = 1
for i in range(z):
	if l1[i] not in hashim:
		while done[curr]:
			curr += 1
		perm[i] = curr
		curr += 1
for i in range(n):
	if li[i]:
		print(li[i], end=' ')
	else:
		j = hashik[i]
		print(l2[perm[(j + 1) % z]] + 1, end=' ')


from sys import exit
n = int(input())
f = [int(i) for i in input().split()]
r = [False] * n
for dst in f:
	if dst > 0:
		r[dst - 1] = True
(src, dst) = (0, 0)
(swap, last) = (False, -1)
while True:
	try:
		while f[src] > 0:
			src += 1
		while r[dst]:
			dst += 1
	except:
		break
	f[src] = dst + 1
	r[dst] = True
	if swap or src == dst:
		if last < 0:
			swap = True
		else:
			f[src] = f[last]
			f[last] = dst + 1
			swap = False
	last = src
print(' '.join(map(str, f)))


n = int(input())
A = [*map(int, input().split())]
B = [0] * n
V = [0] * n
for i in range(n):
	if A[i]:
		B[A[i] - 1] = i + 1
F = []
R = []
for i in range(n):
	p = i
	if not V[i] and (not (not A[p] and (not B[p]))):
		fin = i
		V[i] = 1
		while A[fin]:
			fin = A[fin] - 1
			if V[fin]:
				break
			V[fin] = 1
		ini = i
		while B[ini]:
			ini = B[ini] - 1
			if V[ini]:
				break
			V[ini] = 1
		if not A[fin]:
			R.append([ini, fin])
	if not A[p] and (not B[p]):
		F.append(i + 1)
if len(F) == 1 and len(R):
	for i in range(len(F) - 1):
		A[F[i] - 1] = F[i + 1]
	R.append([F[-1] - 1, R[0][0]])
	for i in range(len(R) - 1):
		A[R[i][1]] = R[(i + 1) % len(R)][0] + 1
	A[R[-1][0]] = R[-1][1] + 1
else:
	for i in range(len(F)):
		A[F[i] - 1] = F[(i + 1) % len(F)]
	for i in range(len(R)):
		A[R[i][1]] = R[(i + 1) % len(R)][0] + 1
print(*A)


n = int(input())
l = list(map(int, input().split()))
s = set()
s1 = set()
for i in range(1, n + 1):
	if l[i - 1] == 0:
		s1.add(i)
	s.add(i)
s = s - set(l) - {0}
l1 = []
for i in s1:
	if i in s:
		v = s.pop()
		while i == v:
			s.add(i)
			v = s.pop()
		l[i - 1] = v
		l1.append(i)
for i in l1:
	s1.remove(i)
for i in s1:
	l[i - 1] = s.pop()
print(*l)


n = int(input())
a = list(map(int, input().split()))
l1 = []
l2 = set(range(1, n + 1))
for i in range(n):
	if a[i] == 0:
		l1.append(i)
	else:
		l2.remove(a[i])
m = len(l1)
l2 = sorted(l2)
while any((l1[i] + 1 == l2[i] for i in range(m))):
	l2 = l2[1:] + [l2[0]]
for i in range(len(l1)):
	a[l1[i]] = l2[i]
print(*a)


import random
n = int(input())
f = list(map(int, input().split()))
setn = set([i for i in range(n + 1)])
rem = list(setn - set(f))
zeros = []
for i in range(n):
	if f[i] == 0:
		zeros.append(i + 1)
for i in range(len(rem)):
	if rem[i] == zeros[i]:
		x = random.randint(0, len(rem) - 1)
		while x == i:
			x = random.randint(0, len(rem) - 1)
		tmp = rem[i]
		rem[i] = rem[x]
		rem[x] = tmp
for i in range(len(zeros)):
	f[zeros[i] - 1] = rem[i]
print(*f)


n = int(input())
friends = list(map(int, input().split()))
friends.insert(0, None)
inDegrees = [0] * (n + 1)
outDegrees = [0] * (n + 1)
for (i, f) in enumerate(friends):
	if not f:
		continue
	inDegrees[f] += 1
	outDegrees[i] += 1
chains = []
for i in range(1, n + 1):
	if inDegrees[i] == 0 and outDegrees[i] == 0:
		chains.append((i, i))
	elif inDegrees[i] == 0 and outDegrees[i] == 1:
		k = i
		while outDegrees[k] == 1:
			k = friends[k]
		chains.append((i, k))
for i in range(len(chains)):
	friends[chains[i][1]] = chains[(i + 1) % len(chains)][0]
for f in friends[1:]:
	print(f, end=' ')


n = int(input())
a = [int(i) for i in input().split()]
b = {i for i in range(1, n + 1)} - {*a}
for i in range(n):
	if a[i] == 0:
		if i + 1 in b:
			for j in b:
				if j != i + 1:
					a[i] = j
					b.remove(j)
					break
for i in range(n):
	if a[i] == 0:
		for j in b:
			a[i] = j
			b.remove(j)
			break
print(*a)


friends = int(input())
missingIndexes = []
receiving = set()
allFriends = set([x for x in range(1, friends + 1)])
l = list(map(int, input().split()))
for (i, f) in enumerate(l, 1):
	if f == 0:
		missingIndexes.append(i)
	else:
		receiving.add(f)
friendsWithout = sorted(list(allFriends - receiving), reverse=True)
wrongPos = []
for (i, x) in enumerate(missingIndexes):
	l[x - 1] = friendsWithout[i]
	if x == friendsWithout[i]:
		wrongPos.append(x)
i = 0
while wrongPos:
	current = wrongPos.pop() - 1
	currentSwitch = missingIndexes[i] - 1
	i += 1
	if current == currentSwitch:
		wrongPos.append(current + 1)
		continue
	(l[current], l[currentSwitch]) = (l[currentSwitch], l[current])
print(' '.join((str(x) for x in l)))


def main():
	n = int(input())
	f = list(map(int, input().split()))
	incoming = [0] * n
	outgoing = [0] * n
	incomings = []
	outgoings = []
	for i in range(n):
		f[i] -= 1
		if f[i] != -1:
			outgoing[i] += 1
			incoming[f[i]] += 1
	loop = []
	for i in range(n):
		if incoming[i] == 0 and outgoing[i] == 0:
			loop.append(i)
	if len(loop) == 1:
		for i in range(n):
			if incoming[i] == 0 and i != loop[0]:
				f[loop[0]] = i
				incoming[i] += 1
				outgoing[loop[0]] += 1
				break
	elif len(loop) > 1:
		for i in range(len(loop)):
			cur = loop[i]
			next = loop[(i + 1) % len(loop)]
			f[cur] = next
			incoming[next] += 1
			outgoing[cur] += 1
	for i in range(n):
		if incoming[i] == 0:
			incomings.append(i)
		if outgoing[i] == 0:
			outgoings.append(i)
	for i in range(len(incomings)):
		f[outgoings[i]] = incomings[i]
	for x in f:
		print(x + 1, end=' ')
	print()
	return
main()


n = int(input())
arr = [int(s) for s in input().split()]
recieved = [0 for i in range(n + 1)]
for i in range(n):
	recieved[arr[i]] = 1
given = arr.copy()
given.insert(0, 0)
left_recieved = []
left_given = []
for i in range(1, n + 1):
	if recieved[i] == 0:
		left_recieved.append(i)
	if given[i] == 0:
		left_given.append(i)
problem = []
l = len(left_recieved)
for i in range(l):
	if left_recieved[i] == left_given[i]:
		problem.append([left_recieved[i], left_given[i]])
if len(problem) == 1:
	for i in range(l):
		if left_given[i] != left_recieved[i]:
			problem.append([left_recieved.pop(i), left_given.pop(i)])
			break
d = {}
l = len(left_recieved)
for i in range(l):
	if left_given[i] != left_recieved[i]:
		d[left_given[i]] = left_recieved[i]
l = len(problem)
if l != 0:
	for i in range(l - 1):
		d[problem[i][1]] = problem[i + 1][0]
	d[problem[l - 1][1]] = problem[0][0]
ans = []
for i in range(n):
	if arr[i] != 0:
		ans.append(arr[i])
	else:
		ans.append(d[i + 1])
for i in ans:
	print(i, end=' ')
print()


from io import BytesIO, IOBase
from math import sqrt
import sys, os
inpl = lambda : list(map(int, input().split()))
inpm = lambda : map(int, input().split())
inpi = lambda : int(input())
inp = lambda : input()
(rev, ra, l) = (reversed, range, len)
P = print
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))

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

def B(n):
	return bin(n).replace('0b', '')

def factors(n):
	arr = []
	for i in ra(2, int(sqrt(n)) + 1):
		if n % i == 0:
			arr.append(i)
			if i * i != n:
				arr.append(int(n / i))
	return arr

def dfs(arr, n):
	pairs = [[i + 1] for i in ra(n)]
	vis = [0] * (n + 1)
	for i in ra(l(arr)):
		pairs[arr[i][0] - 1].append(arr[i][1])
	pairs[arr[i][1] - 1].append(arr[i][0])
	comp = []
	for i in ra(n):
		stack = [pairs[i]]
		temp = []
		if vis[stack[-1][0]] == 0:
			while len(stack) > 0:
				if vis[stack[-1][0]] == 0:
					temp.append(stack[-1][0])
					vis[stack[-1][0]] = 1
					s = stack.pop()
					for j in s[1:]:
						if vis[j] == 0:
							stack.append(pairs[j - 1])
				else:
					stack.pop()
			comp.append(temp)
	return comp
from bisect import bisect_left as bl
from bisect import bisect_right as br
import sys, operator, math, operator
from collections import Counter
import random
n = inpi()
li = inpl()
omap = Counter(li)
arr = []
for i in ra(1, n + 1):
	if i not in omap:
		arr.append(i)
tr = []
for i in ra(n):
	if li[i] == 0 and i + 1 not in omap:
		tr.append(i + 1)
if l(tr) == 1:
	for i in ra(l(arr)):
		if tr[0] != arr[i]:
			li[tr[0] - 1] = arr[i]
			arr.pop(i)
			break
	j = 0
	for i in ra(n):
		if li[i] == 0:
			li[i] = arr[j]
			j += 1
elif l(tr) == 0:
	j = 0
	for i in ra(n):
		if li[i] == 0:
			li[i] = arr[j]
			j += 1
else:
	cp = tr.copy()
	tr.insert(0, tr.pop())
	diff = list(set(arr).difference(set(tr)))
	for i in ra(l(tr)):
		li[cp[i] - 1] = tr[i]
	j = 0
	for i in ra(n):
		if li[i] == 0:
			li[i] = diff[j]
			j += 1
P(*li)


n = int(input())
l = list(map(int, input().split()))
dostal = [0] * (n + 1)
for i in range(n):
	dostal[l[i]] = 1
do_dania = []
ind = []
for i in range(n):
	if l[i] == 0:
		ind.append(i)
for i in range(1, n + 1):
	if dostal[i] == 0:
		do_dania.append(i)
j = 0
for i in range(n):
	if l[i] == 0:
		l[i] = do_dania[j]
		j += 1
for i in range(len(ind) - 1):
	if l[ind[i]] == ind[i] + 1:
		kk = l[ind[i]]
		l[ind[i]] = l[ind[i + 1]]
		l[ind[i + 1]] = kk
if l[ind[-1]] == ind[-1] + 1:
	kk = l[ind[-1]]
	l[ind[-1]] = l[ind[0]]
	l[ind[0]] = kk
print(*l)


def gifts(n, a):
	d = {i: [0, 0] for i in range(1, n + 1)}
	for i in range(1, n + 1):
		if a[i - 1] != 0:
			d[i][1] = a[i - 1]
			d[a[i - 1]][0] = i
	index = []
	f = []
	for key in d:
		if d[key][1] == 0:
			index.append(key)
		if d[key][0] == 0:
			f.append(key)
	for i in range(len(f) - 2):
		if index[i] == f[i]:
			(f[i], f[i + 1]) = (f[i + 1], f[i])
		d[index[i]][1] = f[i]
		d[f[i]][0] = index[i]
	i1 = len(f) - 2
	i2 = len(f) - 1
	if index[i1] == f[i1] or index[i2] == f[i2]:
		(f[i1], f[i1 + 1]) = (f[i1 + 1], f[i1])
	d[index[i1]][1] = f[i1]
	d[f[i1]][0] = index[i1]
	d[index[i2]][1] = f[i2]
	d[f[i2]][0] = index[i2]
	for i in d:
		print(d[i][1], end=' ')
n = int(input())
arr = [int(i) for i in input().split()]
gifts(n, arr)


n = int(input())
a = list(map(int, input().split()))
v = [0] * n
c = []
b = []
for i in range(n):
	if a[i] != 0:
		v[a[i] - 1] = 1
for j in range(n):
	if a[j] == 0:
		c.append(j + 1)
	if v[j] == 0:
		b.append(j + 1)
m = len(c)
for l in range(m):
	if c[l] == b[l]:
		x = l
		y = (l + 1) % m
		(b[x], b[y]) = (b[y], b[x])
for g in range(m):
	a[c[g] - 1] = b[g]
print(*a)


n = int(input())
l = list(map(int, input().split(' ')))
ind = []
x = []
np = []
pos = []
for i in range(n):
	if l[i] == 0:
		ind.append(i)
x = sorted(l)
k = n - 1
val = n
while k >= 0:
	if val == 0:
		break
	if val == x[k]:
		k -= 1
		val -= 1
	else:
		np.append(val)
		val -= 1
i = 0
while i < len(ind):
	if ind[i] + 1 == np[i]:
		(np[i], np[(i + 1) % len(ind)]) = (np[(i + 1) % len(ind)], np[i])
		i += 2
	else:
		i += 1
for i in range(len(ind)):
	l[ind[i]] = np[i]
for i in l:
	print(i, end=' ')


n = int(input())
ganhou = [0] + [int(i) for i in input().split()]
conjunto = set(ganhou)
sem = []
indecisos = []
rep = []
nrep = []
for i in range(1, n + 1):
	if i not in conjunto:
		if ganhou[i] == 0:
			rep.append(i)
		else:
			sem.append(i)
	elif ganhou[i] == 0:
		nrep.append(i)
t = len(rep)
if t > 0:
	if t == 1:
		rep.append(nrep[-1])
		del nrep[-1]
	for i in range(0, t - 1):
		ganhou[rep[i]] = rep[i + 1]
	ganhou[rep[-1]] = rep[0]
pos = 0
for i in range(1, n + 1):
	if ganhou[i] == 0:
		ganhou[i] = sem[pos]
		pos += 1
for i in range(1, n + 1):
	print(ganhou[i], end=' ')
print()


n = int(input())
arr = [int(i) for i in input().split()]
in_ = set(range(1, n + 1))
out_ = set(range(1, n + 1))
for i in range(len(arr)):
	if arr[i]:
		out_.remove(i + 1)
		in_.remove(arr[i])
out_ = list(out_)
out_.sort()
in_ = list(in_)
in_.sort()
for i in range(len(in_)):
	if in_[i] == out_[i]:
		(in_[i], in_[(i + 1) % len(in_)]) = (in_[(i + 1) % len(in_)], in_[i])
ptr = 0
for i in range(len(arr)):
	if arr[i] == 0:
		arr[i] = in_[ptr]
		ptr += 1
print(' '.join(map(str, arr)))


from random import shuffle
n = int(input())
a = [0] + list(map(int, input().split()))
b = []
for i in range(1, n + 1):
	if a[i] == 0:
		b.append(i)
c = []
g = [0] * (n + 5)
for i in range(1, n + 1):
	g[a[i]] = i
for i in range(1, n + 1):
	if g[i] == 0:
		c.append(i)
while True:
	shuffle(c)
	fl = True
	for i in range(0, len(b)):
		if b[i] == c[i]:
			fl = False
	if fl:
		break
j = 0
for i in range(1, n + 1):
	if a[i]:
		print(a[i], end=' ')
	else:
		print(c[j], end=' ')
		j += 1


def checkSame(notGet, notGive):
	for index in range(len(notGet)):
		if notGet[index] == notGive[index]:
			return True
	return False
totalCase = input()
inputNumber = input()
newNumber = inputNumber.split()
getting = {}
notGive = []
notGet = []
for i in range(int(totalCase)):
	if int(newNumber[i]) != 0:
		getting[newNumber[i]] = True
	else:
		notGive.append(i + 1)
for i in range(int(totalCase)):
	if str(i + 1) not in getting:
		notGet.append(i + 1)
checkFlag = True
while checkFlag:
	temp = notGet[0]
	notGet = notGet[1:len(notGet)]
	notGet.append(temp)
	checkFlag = checkSame(notGet, notGive)
indexGet = 0
for index in range(int(totalCase)):
	if int(newNumber[index]) == 0:
		newNumber[index] = str(notGet[indexGet])
		indexGet = indexGet + 1
delim = ' '
print(delim.join(newNumber))


n = int(input())
s = [int(x) for x in input().split()]
pos = [0] * (n + 1)
for i in range(0, len(s)):
	pos[s[i]] = 1
L = []
for i in range(0, len(pos)):
	if pos[i] == 0:
		L.append(i)
last = 0
for i in range(0, len(s)):
	if s[i] == 0:
		flag = 0
		flag2 = 0
		for j in range(len(L) - 1, -1, -1):
			if L[j] != i + 1:
				s[i] = L[j]
				L.pop()
				flag = 1
				break
			else:
				flag2 = 2
				L.pop()
		if flag2 == 2:
			L.append(i + 1)
		if flag == 0:
			rem = L[0]
			temp = s[last]
			s[last] = rem
			s[i] = temp
		last = i
print(*s)


n = int(input())
a = [int(i) for i in input().split()]
ans = a
b = [0] * n
a1 = []
b1 = []
for i in range(n):
	if a[i] != 0:
		b[a[i] - 1] = 1
	else:
		a1.append(i + 1)
for i in range(n):
	if b[i] == 0:
		b1.append(i + 1)
a2 = set(a1)
b2 = set(b1)
c1 = a2 & b2
a3 = a2 - c1
b3 = b2 - c1
a3 = list(a3)
b3 = list(b3)
c2 = list(c1)
if len(c2) > 1:
	for i in range(len(c2) - 1):
		ans[c2[i] - 1] = c2[i + 1]
	ans[c2[len(c2) - 1] - 1] = c2[0]
elif len(c2) == 1:
	ans[c2[0] - 1] = b3[0]
	ans[a3[0] - 1] = c2[0]
	a3.pop(0)
	b3.pop(0)
for i in range(len(a3)):
	ans[a3[i] - 1] = b3[i]
for i in range(n):
	print(ans[i], end=' ')


n = int(input())
a = [int(x) for x in input().split()]
b = [True] * n
c = [False] * n
for i in range(n):
	if a[i]:
		b[a[i] - 1] = False
sam = []
for i in range(n):
	if not a[i] and b[i]:
		sam.append(i)
		c[i] = True
if len(sam) > 1:
	pos = 0
	for i in range(n):
		if c[i]:
			pos = (pos + 1) % len(sam)
			a[i] = sam[pos] + 1
			b[sam[pos]] = False
elif len(sam) == 1:
	j = 0
	while not b[j] or j == sam[0]:
		j += 1
	a[sam[0]] = j + 1
	b[j] = False
j = 0
for i in range(n):
	if not a[i]:
		while not b[j]:
			j += 1
		a[i] = j + 1
		j += 1
for i in range(n):
	print(a[i], end=' ')


n = int(input())
a = list(map(int, input().split()))
b = {}
for i in range(n):
	k = a[i]
	if k != 0:
		if i + 1 in b and (b[i + 1] == 1 or b[i + 1] == -1):
			b[i + 1] = 10
		else:
			b[i + 1] = 1
		if k in b and (b[k] == 1 or b[k] == -1):
			b[k] = 10
		else:
			b[k] = -1
	elif i + 1 not in b:
		b[i + 1] = 0
c = [[], [], []]
for i in b:
	if b[i] == 0:
		c[0].append(i)
	if b[i] == 1:
		c[1].append(i)
	if b[i] == -1:
		c[2].append(i)
l = len(c[0])
if l == 1:
	a[c[0][0] - 1] = c[1][0]
	a[c[2][0] - 1] = c[0][0]
	for i in range(1, len(c[1])):
		a[c[2][i] - 1] = c[1][i]
elif l % 2 == 0:
	for i in range(len(c[1])):
		a[c[2][i] - 1] = c[1][i]
	i = 0
	while i < l:
		a[c[0][i] - 1] = c[0][i + 1]
		a[c[0][i + 1] - 1] = c[0][i]
		i = i + 2
else:
	a[c[0][0] - 1] = c[0][1]
	a[c[0][1] - 1] = c[0][2]
	a[c[0][2] - 1] = c[0][0]
	for i in range(len(c[1])):
		a[c[2][i] - 1] = c[1][i]
	i = 3
	while i < l:
		a[c[0][i] - 1] = c[0][i + 1]
		a[c[0][i + 1] - 1] = c[0][i]
		i = i + 2
print(*a)


n = int(input())
inp = lambda x: int(x) - 1
to = list(map(inp, input().split()))
fromm = [-1 for i in range(n)]
for i in range(n):
	if to[i] != -1:
		fromm[to[i]] = i
head = []
tail = []
both = []
for i in range(n):
	if to[i] == -1 and fromm[i] == -1:
		both.append(i)
	elif to[i] == -1 and fromm[i] != -1:
		head.append(i)
	elif to[i] != -1 and fromm[i] == -1:
		tail.append(i)
if len(head) > 0:
	while head:
		curr = head.pop()
		while both:
			currBoth = both.pop()
			to[curr] = currBoth
			curr = currBoth
		to[curr] = tail.pop()
else:
	first = both.pop()
	curr = first
	while both:
		currBoth = both.pop()
		to[curr] = currBoth
		curr = currBoth
	to[curr] = first
inc1 = lambda x: str(x + 1)
print(' '.join(list(map(inc1, to))))


from sys import stdin, stdout
import math, sys
from itertools import permutations, combinations
from collections import defaultdict, deque
import bisect as bi
import heapq as hq
from math import floor

def main():
	try:
		n = int(input())
		l = list(map(int, input().split()))
		(a1, a2) = ({x for x in range(1, n + 1)}, deque())
		for x in range(n):
			if l[x] == 0:
				a2.append(x + 1)
			else:
				a1.remove(l[x])
		a1 = deque(a1)
		ans = []
		if a1[0] == a2[0]:
			a1.appendleft(a1.pop())
		while a1:
			if a1[-1] != a2[-1]:
				l[a2.pop() - 1] = a1.pop()
			else:
				a1.appendleft(a1.pop())
		print(*l)
	except:
		pass
M = 998244353
P = 1000000007
main()


n = int(input())
f = [int(i) for i in input().split()]
m = dict()
for i in range(n):
	m[f[i]] = 1
l = list()
for i in range(1, n + 1):
	if m.get(i):
		continue
	else:
		l.insert(len(l), i)
l.sort(reverse=True)
val = -1
pre = []
nex = []
for i in range(n):
	pre.insert(len(pre), 0)
	nex.insert(len(nex), 0)
for i in range(n - 1, -1, -1):
	if not f[i]:
		nex[n - 1 - i] = val
		val = i
nex.reverse()
val = -1
prev = 0
for i in range(n):
	if not f[i]:
		pre[i] = val
		val = i
		f[i] = l[prev]
		prev += 1
for i in range(n):
	if f[i] == i + 1:
		if pre[i] == -1:
			idx = nex[i]
		else:
			idx = pre[i]
		tmp = f[idx]
		f[idx] = f[i]
		f[i] = tmp
for i in range(n):
	print(f[i], end=' ')
print()


n = int(input())
ar = list(map(int, input().split()))
h = [0] * (n + 1)
for i in ar:
	h[i] = 1
m = []
for i in range(1, n + 1):
	if h[i] == 0:
		m.append(i)
s = []
for i in range(n):
	if ar[i] == 0:
		s.append(i)
a = []
b = []
aa = []
bb = []
for i in range(len(m)):
	if m[i] - 1 == s[i]:
		a.append(m[i])
		b.append(s[i])
	else:
		aa.append(m[i])
		bb.append(s[i])
if len(a) != 1:
	for i in range(len(aa)):
		ar[bb[i]] = aa[i]
	if len(a) > 1:
		ar[b[-1]] = a[0]
		for i in range(1, len(a)):
			ar[b[i - 1]] = a[i]
else:
	ar[b[0]] = aa[0]
	ar[bb[0]] = a[0]
	for i in range(1, len(bb)):
		ar[bb[i]] = aa[i]
print(*ar)


n = int(input())
p = list(map(int, input().split()))
nov = list(range(1, n + 1))
for i in range(n):
	if p[i] != 0:
		nov[p[i] - 1] = 0
	else:
		a = i
for k in range(2):
	for i in range(n):
		if p[i] == 0:
			for j in range(len(nov) - 1, -1, -1):
				if nov[j] != 0:
					if nov[j] == i + 1:
						p[i] = p[a]
						p[a] = nov[j]
						nov.pop()
						break
					else:
						p[i] = nov[j]
						nov.pop()
						break
				else:
					nov.pop()
			a = i
for i in range(n):
	print(p[i], end=' ')


n = int(input())
arr = list(map(int, input().split()))
a1 = set(arr)
lis = []
for i in range(1, n + 1):
	if i not in a1:
		lis.append(i)
c1 = 0
for i in range(n):
	if arr[i] == 0 and lis[c1] == i + 1:
		(lis[c1], lis[c1 - 1]) = (lis[c1 - 1], lis[c1])
		c1 += 1
		continue
	if arr[i] == 0:
		c1 += 1
c1 = 0
for i in range(n):
	if arr[i] == 0:
		arr[i] = lis[c1]
		c1 += 1
print(*arr)


from collections import Counter
t = 1
for _ in range(t):
	n = int(input())
	ali = list(map(int, input().split()))
	c = Counter()
	for i in range(n):
		c[i + 1] = ali[i]
	nogiven = []
	a = [0] * n
	for i in range(n):
		if ali[i] != 0:
			a[ali[i] - 1] = 1
	for i in range(len(a)):
		if a[i] == 0:
			nogiven.append(i)
	zeroind = []
	for i in range(n):
		if ali[i] == 0:
			zeroind.append(i)
	if zeroind[0] == nogiven[0]:
		(nogiven[0], nogiven[1]) = (nogiven[1], nogiven[0])
	for i in range(1, len(zeroind)):
		if nogiven[i] == zeroind[i]:
			(nogiven[i], nogiven[0]) = (nogiven[0], nogiven[i])
	for i in range(len(zeroind)):
		ali[zeroind[i]] = nogiven[i] + 1
	print(*ali)


import sys, os, io

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 + '\n')

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

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	for _ in range(1):
		n = ri()
		a = ria()
		d = Counter(a)
		zf = []
		p = {}
		for i in range(n):
			if a[i] == 0:
				p[i + 1] = 1
		for i in range(1, n + 1):
			if i not in d:
				zf.append(i)
		for i in range(len(zf)):
			if len(p) == 2:
				A = zf[i]
				B = zf[i + 1]
				CD = []
				for j in p:
					CD.append(j)
				C = CD[0]
				D = CD[1]
				if A != C and B != D:
					a[C - 1] = A
					a[D - 1] = B
				if B != C and A != D:
					a[C - 1] = B
					a[D - 1] = A
				break
			for j in p:
				if zf[i] != j:
					a[j - 1] = zf[i]
					del [p[j]]
					break
		print(*a)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


import sys
input = sys.stdin.readline
n = int(input())
F = list(map(int, input().split()))
USE = [0] * (n + 1)
B = []
for i in range(n):
	USE[F[i]] = 1
	if F[i] == 0:
		B.append(i + 1)
A = []
for i in range(1, n + 1):
	if USE[i] == 0:
		A.append(i)
for i in range(len(A) - 1):
	if A[i] == B[i]:
		(A[i], A[i + 1]) = (A[i + 1], A[i])
if A[-1] == B[-1]:
	(A[-1], A[-2]) = (A[-2], A[-1])
ind = 0
for i in range(n):
	if F[i] == 0:
		F[i] = A[ind]
		ind += 1
print(*F)


from collections import defaultdict
n = int(input())
f = defaultdict(list)
data = map(int, input().split())
for i in range(n):
	f[i + 1].append(0)
	f[i + 1].append(0)
for (i, v) in enumerate(data):
	if v:
		f[i + 1][0] = v
		f[v][1] = i + 1
first = []
second = []
special = []
for (i, v) in f.items():
	if not v[0] and (not v[1]):
		special.append(i)
	elif not v[0]:
		first.append(i)
	elif not v[1]:
		second.append(i)
p = 0
if len(special) == 1:
	p = 1
for i in range(len(special) - p):
	if i < len(special) - p - 1:
		f[special[i]][0] = special[i + 1]
		f[special[i + 1]][1] = special[i]
	else:
		f[special[i]][0] = special[0]
		f[special[0]][1] = special[i]
for i in range(len(first) - p):
	f[first[i]][0] = second[i]
	f[second[i]][1] = first[i]
if p:
	f[first[len(first) - 1]][0] = special[len(special) - 1]
	f[special[len(special) - 1]][0] = second[len(second) - 1]
data = f.values()
print(' '.join([str(i[0]) for i in data]))


n = int(input())
arr = list(map(int, input().split()))
rec = []
giv = []
taken = [0] * n
for i in range(n):
	if arr[i] == 0:
		giv.append(i)
	else:
		taken[arr[i] - 1] = 1
for i in range(n):
	if taken[i] == 0:
		rec.append(i)
for i in range(len(rec)):
	if rec[i] == giv[i] and i != 0:
		(giv[i], giv[i - 1]) = (giv[i - 1], giv[i])
	elif rec[i] == giv[i]:
		(giv[i], giv[i + 1]) = (giv[i + 1], giv[i])
for i in range(len(rec)):
	arr[giv[i]] = rec[i] + 1
for i in arr:
	print(i, end=' ')
print()


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')
n = int(input())
friends = list(map(int, input().split()))
setty = set([k for k in range(1, n + 1)])
indices = []
for s in range(n):
	if friends[s] != 0:
		setty.remove(friends[s])
	else:
		indices.append(s + 1)
setty = list(setty)
setty.sort()
setty.reverse()
for s in range(len(setty)):
	if setty[s] == indices[s] and s != len(setty) - 1:
		(setty[s], setty[-1]) = (setty[-1], setty[s])
		break
	elif setty[s] == indices[s] and s == len(setty) - 1:
		(setty[s], setty[0]) = (setty[0], setty[s])
		break
for s in range(len(indices)):
	friends[indices[s] - 1] = setty[s]
friends = [str(k) for k in friends]
print(' '.join(friends))


def missing_elements(vec1):
	mis = []
	vec = list(vec1)
	temp = [0] * len(vec)
	for i in vec:
		if i != 0:
			temp[i - 1] = 1
	for i in range(len(temp)):
		if temp[i] == 0:
			mis.append(i + 1)
	return mis
n = int(input())
x = list(map(int, input().split()))
mis = missing_elements(x)
temp = []
for i in range(len(x)):
	if x[i] == 0:
		temp.append(i)
j = 0
for i in range(len(x)):
	if x[i] == 0:
		if mis[j] == i + 1:
			if j + 1 == len(mis):
				swap = mis[j]
				mis[j] = mis[j - 1]
				mis[j - 1] = swap
				break
			else:
				swap = mis[j]
				mis[j] = mis[j + 1]
				mis[j + 1] = swap
		j += 1
j = 0
for i in range(len(x)):
	if x[i] == 0:
		x[i] = mis[j]
		j += 1
for i in x:
	print(i, end=' ')


n = int(input())
a = list(map(int, input().split()))
s = [False] * n
r = [False] * n
for i in range(n):
	if a[i]:
		s[i] = True
		r[a[i] - 1] = True
a = [i - 1 if i else 0 for i in a]
s_ = []
r_ = []
for i in range(len(s)):
	if not s[i]:
		s_.append(i)
	if not r[i]:
		r_.append(i)
s = s_
r = r_
for i in range(len(s)):
	if s[i] == r[i]:
		if i == 0:
			(r[i], r[i + 1]) = (r[i + 1], r[i])
		else:
			(r[i], r[i - 1]) = (r[i - 1], r[i])
for i in range(len(s)):
	a[s[i]] = r[i]
for i in range(len(a)):
	a[i] = a[i] + 1
print(' '.join(map(str, a)))


from collections import *
n = int(input())
lst = list()
take = [False] * (n + 1)
give = [0] * (n + 1)
i = 1
for num in input().split():
	num = int(num)
	give[i] = num
	take[num] = True
	i += 1
i = 1
while i <= n:
	if not take[i] and give[i] == 0:
		lst.append(i)
	i += 1
if len(lst) == 1:
	i = 1
	while i <= n:
		if not take[i] and lst[0] != i:
			give[lst[0]] = i
			take[i] = True
			break
		i += 1
else:
	i = 0
	while i < len(lst):
		j = (i + 1) % len(lst)
		give[lst[i]] = lst[j]
		take[lst[j]] = True
		i += 1
dq = deque()
i = 1
while i <= n:
	if not take[i]:
		dq.append(i)
	i += 1
i = 1
while i <= n:
	if give[i] == 0:
		give[i] = dq.popleft()
	i += 1
i = 1
ans = []
while i <= n:
	ans.append(give[i])
	i += 1
for x in ans:
	print(x)


import sys
from collections import deque
n = int(sys.stdin.readline())
list_num = list(map(int, sys.stdin.readline().split()))
list_index = [i for i in range(n) if not list_num[i]]
list_check = sorted(list_num) + [n + 1]
list_to = deque()
for i in range(len(list_index) - 1, n):
	for j in range(list_check[i] + 1, list_check[i + 1]):
		list_to.append(j)
for _ in range(len(list_to)):
	now = list_to.popleft()
	list_to.append(now)
	if not list_num[now - 1]:
		list_num[now - 1] = list_to.popleft()
for i in list_index:
	if list_num[i]:
		continue
	list_num[i] = list_to.popleft()
print(*list_num)


n = int(input())
l = list(map(int, input().split()))
so = []
for x in l:
	if x != 0:
		so.append(x)
so = sorted(so)
ind = 0
n_2 = len(so)
not_there = []
for x in range(1, n + 1):
	if ind < n_2 and so[ind] > x:
		not_there.append(x)
	elif ind >= n_2:
		not_there.append(x)
	elif so[ind] <= x:
		ind += 1
ind = 0
prev = -1
not_there.reverse()
while ind < n:
	if l[ind] == 0:
		if ind + 1 != not_there[-1]:
			l[ind] = not_there[-1]
			not_there.pop()
			prev = ind
		elif prev == -1:
			x = not_there[-1]
			y = not_there[-2]
			l[ind] = y
			not_there.pop()
			not_there.pop()
			not_there.append(x)
		else:
			x = l[prev]
			l[prev] = not_there[-1]
			l[ind] = x
			not_there.pop()
			prev = ind
	ind += 1
print(*l)


from random import shuffle
n = int(input())
l = list(map(int, input().split()))
gifted = [0 for i in range(n + 1)]
for i in l:
	gifted[i] = 1
notgifted = []
unsure = []
for i in range(n):
	if l[i] == 0:
		unsure.append(i + 1)
for i in range(1, n + 1):
	if not gifted[i]:
		notgifted.append(i)
i = 0
while True:
	flag = False
	for i in range(len(unsure)):
		if unsure[i] == notgifted[i]:
			flag = True
			break
	if flag == False:
		break
	else:
		shuffle(unsure)
for i in range(len(unsure)):
	l[unsure[i] - 1] = notgifted[i]
l = [str(_) for _ in l]
print(' '.join(l))


from io import BytesIO, IOBase
from math import sqrt
import sys, os
inpl = lambda : list(map(int, input().split()))
inpm = lambda : map(int, input().split())
inpi = lambda : int(input())
inp = lambda : input()
(rev, ra, l) = (reversed, range, len)
P = print

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

def B(n):
	return bin(n).replace('0b', '')

def factors(n):
	arr = []
	for i in ra(2, int(sqrt(n)) + 1):
		if n % i == 0:
			arr.append(i)
			if i * i != n:
				arr.append(int(n / i))
	return arr

def dfs(arr, n):
	pairs = [[i + 1] for i in ra(n)]
	vis = [0] * (n + 1)
	for i in ra(l(arr)):
		pairs[arr[i][0] - 1].append(arr[i][1])
	pairs[arr[i][1] - 1].append(arr[i][0])
	comp = []
	for i in ra(n):
		stack = [pairs[i]]
		temp = []
		if vis[stack[-1][0]] == 0:
			while len(stack) > 0:
				if vis[stack[-1][0]] == 0:
					temp.append(stack[-1][0])
					vis[stack[-1][0]] = 1
					s = stack.pop()
					for j in s[1:]:
						if vis[j] == 0:
							stack.append(pairs[j - 1])
				else:
					stack.pop()
			comp.append(temp)
	return comp
from bisect import bisect_left as bl
from bisect import bisect_right as br
import sys, operator, math, operator
from collections import Counter
import random
n = inpi()
li = inpl()
omap = Counter(li)
arr = []
for i in ra(1, n + 1):
	if i not in omap:
		arr.append(i)
tr = []
for i in ra(n):
	if li[i] == 0 and i + 1 not in omap:
		tr.append(i + 1)
if l(tr) == 1:
	for i in ra(l(arr)):
		if tr[0] != arr[i]:
			li[tr[0] - 1] = arr[i]
			arr.pop(i)
			break
	j = 0
	for i in ra(n):
		if li[i] == 0:
			li[i] = arr[j]
			j += 1
elif l(tr) == 0:
	j = 0
	for i in ra(n):
		if li[i] == 0:
			li[i] = arr[j]
			j += 1
else:
	cp = tr.copy()
	tr.insert(0, tr.pop())
	diff = list(set(arr).difference(set(tr)))
	for i in ra(l(tr)):
		li[cp[i] - 1] = tr[i]
	j = 0
	for i in ra(n):
		if li[i] == 0:
			li[i] = diff[j]
			j += 1
P(*li)


n = int(input())
arr = list(map(int, input().split()))
left = set([i for i in range(1, n + 1)])
places = []
for i in range(n):
	if not arr[i]:
		places.append(i)
	else:
		left.discard(arr[i])
left = list(left)
for i in range(len(places)):
	if places[i] + 1 == left[i]:
		if i + 1 < len(places):
			(left[i], left[i + 1]) = (left[i + 1], left[i])
		elif i - 1 < len(places):
			(left[i], left[i - 1]) = (left[i - 1], left[i])
index = 0
for i in range(n):
	if not arr[i]:
		arr[i] = left[index]
		index += 1
print(' '.join(map(str, arr)))


n = int(input())
arr = list(map(int, input().split()))
(give, take) = ([], [])
vis = [False for i in range(n)]
for i in range(n):
	if arr[i] != 0:
		vis[arr[i] - 1] = True
	else:
		take.append(i + 1)
for i in range(n):
	if vis[i] == False:
		give.append(i + 1)
for i in range(len(give)):
	if i == 0:
		if give[i] == take[i]:
			(give[i], give[i + 1]) = (give[i + 1], give[i])
	elif give[i] == take[i]:
		(give[i], give[i - 1]) = (give[i - 1], give[i])
pt = 0
for i in range(n):
	if arr[i] == 0:
		arr[i] = give[pt]
		pt += 1
print(*arr)


n = int(input())
arr = list(map(int, input().split()))
set_sisa = {i for i in range(1, n + 1)}
empty_indices = []
for (i, v) in enumerate(arr):
	if v != 0:
		set_sisa.remove(v)
	else:
		empty_indices.append(i)
for (i, empty_index) in enumerate(empty_indices):
	try:
		candidate = set_sisa.pop()
	except:
		print(i, set_sisa, empty_indices, arr)
		exit(0)
	if candidate - 1 == empty_index:
		if len(set_sisa) != 0:
			other_candidate = set_sisa.pop()
			set_sisa.add(candidate)
			arr[empty_index] = other_candidate
		else:
			prev_empty = empty_indices[i - 1]
			(arr[prev_empty], arr[empty_index]) = (candidate, arr[prev_empty])
	else:
		arr[empty_index] = candidate
print(' '.join(map(str, arr)))


def read_input():
	global PERM
	_ = int(input())
	PERM = [int(x) for x in input().split()]

def split_into_paths(perm):
	has_outgoing = set((i + 1 for i in range(len(perm)) if perm[i] != 0))
	has_incoming = set(perm) - set([0])
	is_starting_point = has_outgoing - has_incoming
	paths = []
	for x in is_starting_point:
		curr = x
		while perm[curr - 1] != 0:
			curr = perm[curr - 1]
		paths.append((x, curr))
	remaining = set((i + 1 for i in range(len(perm)) if perm[i] == 0)) - set((p[-1] for p in paths))
	return (paths, list(remaining))

def update_perm_from_paths(perm, paths, remaining):
	if len(paths) == 0:
		for (a, b) in zip(remaining, remaining[1:] + [remaining[0]]):
			perm[a - 1] = b
		return
	for (sta, sto) in paths[1:]:
		perm[sto - 1] = sta
	fst = paths[0]
	for (a, b) in zip([fst[-1]] + remaining, remaining + [fst[0]]):
		perm[a - 1] = b
read_input()
(paths, remaining) = split_into_paths(PERM)
update_perm_from_paths(PERM, paths, remaining)
print(*PERM)


import heapq

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))
n = int(input())
arr = [int(x) for x in input().split()]
indexesToFill = []
usableNumbers = set(range(1, n + 1))
for i in range(n):
	if arr[i] == 0:
		indexesToFill.append(i + 1)
	else:
		usableNumbers.remove(arr[i])
heapq.heapify(indexesToFill)
usableNumbers2 = list(usableNumbers)
heapq.heapify(usableNumbers2)
m = len(indexesToFill)
i = 0
while indexesToFill:
	if len(indexesToFill) >= 2:
		idx1 = heapq.heappop(indexesToFill)
		idx2 = heapq.heappop(indexesToFill)
		un1 = heapq.heappop(usableNumbers2)
		un2 = heapq.heappop(usableNumbers2)
		if idx1 == un1 or idx2 == un2:
			arr[idx1 - 1] = un2
			heapq.heappush(indexesToFill, idx2)
			heapq.heappush(usableNumbers2, un1)
		else:
			arr[idx1 - 1] = un1
			heapq.heappush(indexesToFill, idx2)
			heapq.heappush(usableNumbers2, un2)
	else:
		idx = indexesToFill.pop()
		un = usableNumbers2.pop()
		arr[idx - 1] = un
oneLineArrayPrint(arr)


n = int(input())

def swap(a, b):
	a = a ^ b
	b = a ^ b
	a = a ^ b
	return (a, b)
arr = list(map(int, input().strip().split()))
for i in range(n):
	arr[i] = arr[i] - 1
gi = arr.copy()
gi.sort()
left = []
for i in range(n - 1):
	index = gi[i] + 1
	while index < gi[i + 1]:
		left.append(index)
		index = index + 1
index = gi[-1] + 1
while index < n:
	left.append(index)
	index = index + 1
fill = []
for i in range(n):
	if arr[i] == -1:
		fill.append(i)
while len(fill) != 0:
	if len(fill) == 2:
		if fill[-2] == left[-2] or fill[-1] == left[-1]:
			(fill[-1], fill[-2]) = swap(fill[-1], fill[-2])
		arr[fill[-2]] = left[-2]
		arr[fill[-1]] = left[-1]
		left.pop()
		fill.pop()
		left.pop()
		fill.pop()
	else:
		if fill[-1] == left[-1]:
			(fill[-1], fill[-2]) = swap(fill[-1], fill[-2])
		arr[fill[-1]] = left[-1]
		left.pop()
		fill.pop()
for i in range(n):
	arr[i] = arr[i] + 1
for i in arr:
	print(i, end=' ')
print()


n = int(input())
a = list(map(int, input().split()))
temp = [0 for i in range(n + 1)]
ovaga = []
bolod = []
for i in range(n):
	if a[i] != 0:
		temp[a[i]] += 1
	else:
		bolod.append(i + 1)
for i in range(1, n + 1):
	if temp[i] == 0:
		ovaga.append(i)
left = 0
right = len(ovaga) - 1
last = []
for i in range(n):
	if a[i] == 0:
		temp = ovaga[right]
		if temp == i + 1:
			if right == left:
				flag = last[-1]
				temp1 = flag[0]
				j = flag[1]
				a[j] = temp
				a[i] = temp1
				break
			else:
				temp = ovaga[left]
				left += 1
				last.append((temp, i))
		else:
			right -= 1
			last.append((temp, i))
		a[i] = temp
print(*a)


from collections import deque
n = int(input())
s = deque()
a = list(map(int, input().split()))
b = set(a)
b.remove(0)
value = 0
index = 0
for i in range(len(a)):
	if i + 1 in b:
		continue
	else:
		s.append(i + 1)
for item in range(len(a)):
	if a[item] != 0:
		continue
	elif item + 1 == s[0]:
		if len(s) == 1:
			a[item] = value
			a[index] = s.pop()
		else:
			a[item] = s.pop()
	else:
		value = s.popleft()
		index = item
		a[item] = value
print(*a)


from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time

def I():
	return int(input())

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

def S():
	return input()

def MS():
	return map(str, input().split())

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def StoI():
	return [ord(i) - 97 for i in input()]

def ItoS(nn):
	return chr(nn + 97)

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

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
YN = {False: 'No', True: 'Yes'}
MOD = 10 ** 9 + 7
inf = float('inf')
IINF = 10 ** 10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
show_flg = False

def main():
	N = I()
	F = LI()
	gifts = [0] * (N + 1)
	for i in range(N):
		gifts[F[i]] = 1
	q = deque()
	for i in range(1, N + 1):
		if gifts[i] == 0:
			q.append(i)
	total = len(q)
	cur = 0
	c = 0
	while cur < N and c + 2 < total:
		if F[cur] == 0:
			item = q.popleft()
			if cur + 1 == item:
				q.append(item)
				item = q.popleft()
			F[cur] = item
			c += 1
		cur += 1
	pairs = []
	for i in range(cur, N):
		if F[i] == 0:
			pairs.append(i + 1)
	if len(pairs) == 2:
		for i in range(len(q)):
			item = q.popleft()
			if pairs[0] == item:
				F[pairs[1] - 1] = item
				pairs.pop(1)
				break
			elif pairs[1] == item:
				F[pairs[0] - 1] = item
				pairs.pop(0)
				break
			q.append(item)
		while len(q) != 0:
			item = q.popleft()
			num = pairs.pop(0)
			F[num - 1] = item
	elif len(pairs) == 1:
		item = q.popleft()
		F[pairs[0] - 1] = item
	print(*F)
main()


from sys import stdin, stdout
n = int(stdin.readline().strip())
flist = list(map(int, stdin.readline().split()))
avail = set([i for i in range(1, n + 1)])
unpaired = set()
for (i, v) in enumerate(flist):
	if v:
		avail.remove(v)
	else:
		unpaired.add(i + 1)
dupl = unpaired.intersection(avail)
if dupl:
	if len(dupl) > 1:
		avail -= dupl
		unpaired -= dupl
		f1 = first = dupl.pop()
		while dupl:
			f2 = dupl.pop()
			flist[f1 - 1] = f2
			f1 = f2
		flist[f1 - 1] = first
	else:
		(f1, other) = (dupl.pop(), None)
		for f2 in avail:
			if f1 != f2:
				other = flist[f1 - 1] = f2
				break
		avail.remove(other)
		unpaired.remove(f1)
for f1 in unpaired:
	f2 = avail.pop()
	flist[f1 - 1] = f2
stdout.write(' '.join(map(str, flist)))


n = int(input())
a = [int(x) for x in input().split()]
ll = []
arr = [0] * (n + 1)
for x in a:
	arr[x] = 1
for i in range(1, n + 1):
	if arr[i] == 0:
		ll.append(i)
last_edited_index = 0
ll_index = 0
for i in range(n):
	if a[i] == 0:
		if i + 1 != ll[ll_index]:
			a[i] = ll[ll_index]
		elif ll_index + 1 < len(ll):
			a[i] = ll[ll_index + 1]
			ll[ll_index + 1] = ll[ll_index]
		else:
			a[i] = a[last_edited_index]
			a[last_edited_index] = ll[ll_index]
		ll_index += 1
		last_edited_index = i
print(*a)


def binarySearch(alist, item):
	first = 0
	last = len(alist) - 1
	found = False
	while first <= last and (not found):
		midpoint = (first + last) // 2
		if alist[midpoint] == item:
			found = True
		elif item < alist[midpoint]:
			last = midpoint - 1
		else:
			first = midpoint + 1
	return found
t = int(input(''))
mat = list(map(int, input().split()))
x = mat.copy()
x.sort()
miss = []
for i in range(1, t + 1):
	if binarySearch(x, i) == False:
		miss.append(i)
k = 0
num = []
for i in range(len(mat)):
	if mat[i] == 0:
		num.append(i + 1)
jhamela = 0
for i in range(len(num) - 1):
	if i == 0:
		if num[i] == miss[i]:
			tmp = miss[i]
			miss[i] = miss[len(miss) - 1]
			miss[len(miss) - 1] = tmp
	if num[i + 1] == miss[i + 1]:
		tmp = miss[i]
		miss[i] = miss[i + 1]
		miss[i + 1] = tmp
for i in range(len(mat)):
	if mat[i] == 0:
		mat[i] = miss[k]
		k = k + 1
print(*mat)


import sys
import math

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

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

def input():
	return sys.stdin.readline().strip()
from collections import deque
N = int(input())
A = alele()
B = [0] * (len(A) + 1)
queue = deque()
F = []
for i in range(N):
	if A[i] != 0:
		B[A[i]] = 1
	else:
		F.append(i + 1)
B = B[1:]
for i in range(len(B)):
	if B[i] == 0:
		queue.append(i + 1)
for i in range(len(F)):
	if F[i] != queue[0]:
		A[F[i] - 1] = queue.popleft()
	elif F[i] != queue[-1]:
		A[F[i] - 1] = queue.pop()
	else:
		A[F[i] - 1] = queue.pop()
		(A[F[i] - 1], A[F[i - 1] - 1]) = (A[F[i - 1] - 1], A[F[i] - 1])
print(*A)


n = int(input())
l = list(map(int, input().split()))
a = []
b = []
c = []
d = []
for i in range(len(l)):
	c.append(0)
for i in range(len(l)):
	if l[i] == 0:
		a.append(i + 1)
	else:
		c[l[i] - 1] = 1
for i in range(len(c)):
	if c[i] == 0:
		d.append(i + 1)
d = sorted(d, reverse=True)
for i in range(len(d)):
	if d[i] == a[i]:
		d[i - 1] = d[i] + d[i - 1]
		d[i] = d[i - 1] - d[i]
		d[i - 1] = d[i - 1] - d[i]
for i in range(len(d)):
	l[a[i] - 1] = d[i]
listToStr = ' '.join(map(str, l))
print(listToStr)


n = int(input())
f = list(map(int, input().split()))
set1 = set(f)
f1 = []
f2 = []
for i in range(1, n + 1):
	if i not in set1:
		f1.append(i)
	if f[i - 1] == 0:
		f2.append(i)
set2 = set(f1)
set3 = set(f2)
f3 = []
f4 = []
l2 = len(f2)
for i in range(0, l2):
	if f2[i] in set2:
		f3.append(f2[i])
	else:
		f4.append(f2[i])
set4 = set(f3)
setf = set2 - set4
ff = list(setf)
l3 = len(f3)
l4 = len(f4)
if l3 == 1:
	f[f4[0] - 1] = f3[0]
elif l3 % 2 == 0:
	for i in range(l3):
		f[f3[i] - 1] = f3[-(i + 1)]
else:
	f[f3[l3 // 2] - 1] = f3[l3 - 1]
	j = l3 - 2
	for i in range(l3):
		if i == l3 // 2:
			continue
		else:
			f[f3[i] - 1] = f3[j]
			j -= 1
if l4 == 0:
	print(*f)
else:
	k = 0
	for i in range(0, n):
		if f[i] == 0:
			f[i] = ff[k]
			k += 1
	print(*f)


n = int(input())
l = list(map(int, input().strip().split()))
recieved = [False for i in range(n + 1)]
recieved[0] = True
for i in range(len(l)):
	recieved[l[i]] = True
recievedNotGiven = []
givenNotRecieved = []
both = []
for i in range(1, n + 1):
	if l[i - 1] == 0 and recieved[i] == False:
		both.append(i)
	elif l[i - 1] == 0:
		recievedNotGiven.append(i)
	elif recieved[i] == False:
		givenNotRecieved.append(i)
if len(both) != 1:
	for i in range(len(recievedNotGiven)):
		l[recievedNotGiven[i] - 1] = givenNotRecieved[i]
	for i in range(len(both)):
		if i < len(both) - 1:
			l[both[i] - 1] = both[i + 1]
		else:
			l[both[i] - 1] = both[0]
else:
	l[both[0] - 1] = givenNotRecieved[0]
	l[recievedNotGiven[0] - 1] = both[0]
	for i in range(1, len(givenNotRecieved)):
		l[recievedNotGiven[i] - 1] = givenNotRecieved[i]
for i in range(len(l)):
	print(l[i], end=' ')


n = int(input())
f = list(map(int, input().split()))
new = {i + 1: False for i in range(n)}
for x in f:
	if x != 0:
		new[x] = True
new1 = [i + 1 for i in range(n) if f[i] == 0]
new2 = [i + 1 for i in range(n) if new[i + 1] == False]
for i in range(len(new1)):
	if new1[i] == new2[i]:
		if i == 0:
			(new2[0], new2[1]) = (new2[1], new2[0])
		else:
			(new2[0], new2[i]) = (new2[i], new2[0])
for i in range(len(new1)):
	f[new1[i] - 1] = new2[i]
for x in f:
	print(x, end=' ')
print()


import math
from collections import *
import sys
from functools import reduce

def get_ints():
	return map(int, input().strip().split())

def get_list():
	return list(get_ints())

def getlistofstring():
	return list(input().strip().split())

def printxsp(*args):
	return print(*args, end='')

def printsp(*args):
	return print(*args, end=' ')
UGLYMOD = int(1000000000.0) + 7
SEXYMOD = 998244353
MAXN = int(100000.0)
n = int(input())
li = list(map(lambda x: x - 1, get_list()))
selfloops = []
indegree = [0] * n
outdegree = [0] * n
for (i, v) in enumerate(li):
	if v != -1:
		outdegree[i] = 1
		indegree[v] = 1
for i in range(n):
	if not indegree[i] | outdegree[i]:
		selfloops.append(i)
if len(selfloops) == 1:
	for i in selfloops:
		for j in range(n):
			if indegree[j] == 0 and i != j:
				indegree[j] = 1
				outdegree[i] = 1
				li[i] = j
				break
elif len(selfloops) > 1:
	sz = len(selfloops)
	for i in range(sz):
		v1 = selfloops[i]
		v2 = selfloops[(i + 1) % sz]
		li[v1] = v2
		outdegree[v1] = 1
		indegree[v2] = 1
remainIns = [i for i in range(n) if indegree[i] == 0]
remainOuts = [i for i in range(n) if outdegree[i] == 0]
sz = len(remainIns)
for i in range(sz):
	v1 = remainIns[i]
	v2 = remainOuts[i]
	li[v2] = v1
print(*list(map(lambda x: x + 1, li)))


import sys

def fastio():
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()

def debug(*var, sep=' ', end='\n'):
	print(*var, file=sys.stderr, end=end, sep=sep)
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
(n,) = I()
f = [0] + I()
v = [0] * (n + 1)
for i in f:
	v[i] = 1
not_decided = []
not_visited = []
for i in range(1, n + 1):
	if f[i] == 0:
		not_decided.append(i)
	if v[i] == 0:
		not_visited.append(i)
k = len(not_decided)
ok = set(not_visited)
common = []
un = []
for i in range(k):
	if not_decided[i] in ok:
		common.append(not_decided[i])
	else:
		un.append(not_decided[i])
not_decided = common + un
for i in range(k):
	x = not_decided[i]
	y = not_visited[i]
	if x == y and i + 1 < k:
		(not_visited[i], not_visited[i + 1]) = (not_visited[i + 1], not_visited[i])
	elif x == y:
		f[not_decided[i - 1]] = not_visited[i]
		f[not_decided[i]] = not_visited[i - 1]
		break
	f[x] = not_visited[i]
print(*f[1:])


n = int(input())
arr = list(map(int, input().split()))
rem = []
want = []
dic = {}
r = {}
w = {}
dic[0] = 0
le = 0
flag = 0
same = []
for i in range(n):
	dic[i + 1] = 0
	r[i + 1] = 0
	w[i + 1] = 0
for i in range(n):
	dic[arr[i]] = 1
	if arr[i] == 0:
		w[i + 1] = 1
		want.append(i + 1)
		le += 1
for i in range(1, n + 1):
	if dic[i] == 0:
		r[i] = 1
		rem.append(i)
		if w[i] == 1:
			flag += 1
if flag <= 1:
	for i in range(le):
		if want[i] == rem[i]:
			if i < le - 1:
				(rem[i], rem[i + 1]) = (rem[i + 1], rem[i])
			else:
				(rem[i], rem[i - 1]) = (rem[i - 1], rem[i])
	j = 0
	for i in arr:
		if i == 0:
			print(rem[j], end=' ')
			j += 1
		else:
			print(i, end=' ')
else:
	rem = []
	want = []
	for i in range(1, n + 1):
		if r[i] == w[i] == 1:
			same.append(i)
			continue
		if r[i] == 1:
			rem.append(i)
		if w[i] == 1:
			want.append(i)
			le += 1
	s = 0
	j = 0
	for i in range(n):
		if arr[i] == 0:
			if r[i + 1] == w[i + 1] == 1:
				print(same[s - 1], end=' ')
				s += 1
			else:
				print(rem[j], end=' ')
				j += 1
		else:
			print(arr[i], end=' ')


import sys, os, io
from sys import stdin
import math
from collections import defaultdict
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
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')
alphabets = list('abcdefghijklmnopqrstuvwxyz')
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 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

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def sieveForSmallestPrimeFactor():
	MAXN = 100001
	spf = [0 for i in range(MAXN)]
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, math.ceil(math.sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
	return spf

def getPrimeFactorizationLOGN(x):
	spf = sieveForSmallestPrimeFactor()
	ret = list()
	while x != 1:
		ret.append(spf[x])
		x = x // spf[x]
	return ret

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def si():
	return input()

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')

def solve():
	n = ii()
	l = li()
	d = defaultdict(lambda : 0)
	for i in l:
		d[i] += 1
	zeros = []
	ind = []
	for i in range(1, n + 1):
		if l[i - 1] == 0:
			ind.append(i - 1)
		if d[i] == 0:
			zeros.append(i)
	ptr = 0
	zeros.reverse()
	for i in range(n):
		if l[i] == 0:
			l[i] = zeros[ptr]
			ptr += 1
	ptr = 0
	for i in range(len(ind)):
		if l[ind[i]] == ind[i] + 1:
			if i == 0:
				(l[ind[i]], l[ind[1]]) = (l[ind[1]], l[ind[i]])
			else:
				(l[ind[i]], l[ind[0]]) = (l[ind[0]], l[ind[i]])
	print(*l)
t = 1
for _ in range(t):
	solve()


n = int(input())
a = list(map(int, input().split()))
a.insert(0, 0)
got = [0] * (n + 1)
(get, give) = ([], [])
for i in range(1, n + 1):
	if a[i] == 0:
		give.append(i)
	got[a[i]] = 1
for i in range(1, n + 1):
	if got[i] == 0:
		get.append(i)
for i in range(len(get)):
	if get[i] == give[i]:
		if i > 0:
			(get[i], get[i - 1]) = (get[i - 1], get[i])
		else:
			(get[0], get[1]) = (get[1], get[0])
for i in range(len(get)):
	a[give[i]] = get[i]
print(*a[1:])


import sys
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()

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

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 998244353
n = int(ri())
a = Ri()
take = []
give = []
tg = []
togive = [0] * n
totake = [1] * n
for i in range(len(a)):
	if a[i] == 0:
		togive[i] = 1
	else:
		totake[a[i] - 1] = 0
for i in range(len(a)):
	if togive[i] == 1 and totake[i] == 1:
		tg.append(i)
	elif togive[i] == 1:
		give.append(i)
	elif totake[i] == 1:
		take.append(i)
dic = {}
for i in range(0, len(tg)):
	dic[tg[i]] = tg[(i + 1) % len(tg)]
if len(tg) == 1:
	take.append(tg[-1])
	give = [tg[-1]] + give
for i in range(len(take)):
	dic[give[i]] = take[i]
ans = []
for i in range(len(a)):
	if a[i] != 0:
		ans.append(a[i])
	else:
		ans.append(dic[i] + 1)
print(*ans)


n = int(input())
A = list(map(int, input().split()))
B = []
C = []
D = []
E = [1] * n
F = [0] * n
for i in range(n):
	a = A[i]
	if a != 0:
		F[a - 1] = 1
	else:
		E[i] = 0
for i in range(n):
	(a, b) = (E[i], F[i])
	if a == 0 and b == 0:
		B.append(i)
	elif a == 0 and b == 1:
		C.append(i)
	if b == 0:
		D.append(i)
d = 0
l = 0
h = len(B)
f = -1
if h == 1:
	f = 0
	while D[f] == B[0]:
		f += 1
	A[B[0]] = D[f] + 1
for i in range(len(D)):
	if i != f:
		j = D[i]
		if h > 1 and B[d] == j:
			if d == len(B) - 1:
				A[j] = B[0] + 1
			else:
				d += 1
				A[j] = B[d] + 1
		else:
			A[C[l]] = j + 1
			l += 1
print(*A)


count = int(input())
friends = [int(elem) for elem in input().split()]
lonely = set(range(count + 1))
free = set(range(count + 1))
lonely -= {0}
free -= {0}
for (fro, to) in enumerate(friends):
	if to:
		lonely -= {to, fro + 1}
		free -= {to}
free -= lonely
assert 0 not in free
assert 0 not in lonely
for (fro, to) in enumerate(friends):
	if to == 0:
		if lonely:
			candidate = lonely.pop()
			if candidate == fro + 1:
				if free:
					friends[fro] = free.pop()
					free |= {candidate}
				else:
					friends[fro] = lonely.pop()
					free |= {fro + 1}
			else:
				friends[fro] = candidate
		else:
			friends[fro] = free.pop()
for i in friends:
	print(i, end=' ')


from sys import stdin, stdout
from math import gcd, sqrt, factorial
from collections import deque, defaultdict
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 0 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
n = I()
a = L()
p = [1] * n
ind = []
for i in range(n):
	if a[i]:
		p[a[i] - 1] = 0
	else:
		ind += (i,)
res = deque()
for i in range(n):
	if p[i]:
		res += (i + 1,)
res.reverse()
for i in range(n):
	if not a[i]:
		if i + 1 == res[0]:
			(res[0], res[-1]) = (res[-1], res[0])
		a[i] = res.popleft()
		if i + 1 == a[i]:
			(a[ind[0]], a[i]) = (a[i], a[ind[0]])
print(*a)


import random
input()
a = list(map(int, input().split()))
b = a.copy()
b.sort()
tmp = 1
fill = []
for i in range(len(b)):
	if b[i] < tmp:
		continue
	elif b[i] == tmp:
		tmp += 1
	else:
		for j in range(tmp, b[i]):
			fill.append(j)
		tmp = b[i] + 1
for j in range(tmp, len(a) + 1):
	fill.append(j)
blank = []
for i in range(len(a)):
	if a[i] == 0:
		blank.append(i)
begin = 0
end = len(fill) - 1
for i in blank:
	if end - begin + 1 <= 3:
		break
	if i + 1 != fill[end]:
		a[i] = fill[end]
		end -= 1
	else:
		a[i] = fill[begin]
		begin += 1
OK = False
while not OK:
	if end - begin == 0:
		Ok = True
		break
	OK = True
	left = end - begin + 1
	left_begin = len(blank) - left
	rand = random.randint(0, 100) % left
	for i in range(left):
		a[blank[left_begin + (i + rand) % left]] = fill[begin + i]
		if blank[left_begin + (i + rand) % left] + 1 == fill[begin + i]:
			OK = False
print(' '.join((str(i) for i in a)))


number = int(input())
accept = [0 for i in range(number)]
k = input()
give = list(map(int, k.split()))
for i in range(number):
	if give[i] != 0:
		accept[give[i] - 1] = i + 1
zero = []
give_zero = []
accept_zero = []
for i in range(number):
	if give[i] == 0:
		if accept[i] == 0:
			zero.append(i + 1)
		else:
			give_zero.append(i + 1)
	elif accept[i] == 0:
		accept_zero.append(i + 1)
accept_mark = 0
give_end = len(give_zero)
give_mark = 0
while give_mark < give_end:
	if accept_mark == give_end:
		break
	while give[give_zero[give_mark] - 1] != 0:
		give_mark += 1
		if give_mark == give_end:
			break
	start = give_zero[give_mark]
	if len(zero):
		give[start - 1] = zero[0]
		if len(zero) > 1:
			for i in range(len(zero) - 1):
				give[zero[i] - 1] = zero[i + 1]
		give[zero[-1] - 1] = accept_zero[accept_mark]
		zero = []
		follow = accept_zero[accept_mark]
		accept_mark += 1
		while follow != start:
			if give[follow - 1] == 0:
				give[follow - 1] = accept_zero[accept_mark]
				follow = accept_zero[accept_mark]
				accept_mark += 1
			else:
				follow = give[follow - 1]
	else:
		give[start - 1] = accept_zero[accept_mark]
		follow = accept_zero[accept_mark]
		accept_mark += 1
		while follow != start:
			if give[follow - 1] == 0:
				give[follow - 1] = accept_zero[accept_mark]
				follow = accept_zero[accept_mark]
				accept_mark += 1
			else:
				follow = give[follow - 1]
	give_mark += 1
if len(zero):
	for i in range(len(zero) - 1):
		give[zero[i] - 1] = zero[i + 1]
	give[zero[-1] - 1] = zero[0]
for i in range(number - 1):
	print(give[i], end='')
	print(' ', end='')
print(give[number - 1])


n = int(input())
vals = list(map(int, input().split()))
zero_vals = []
utlz_vals = [0] * n
free_vals = []
for i in range(len(vals)):
	if vals[i] != 0:
		utlz_vals[vals[i] - 1] = 1
	else:
		zero_vals.append(i)
for i in range(n):
	if utlz_vals[i] == 0:
		free_vals.append(i)
for i in range(len(zero_vals)):
	if zero_vals[i] == free_vals[i]:
		(free_vals[i], free_vals[(i + 1) % len(zero_vals)]) = (free_vals[(i + 1) % len(zero_vals)], free_vals[i])
for i in range(len(zero_vals)):
	vals[zero_vals[i]] = free_vals[i] + 1
print(*vals)


n = int(input())
l = list(map(int, input().split()))
mile = [0] * (n + 1)
for i in range(n):
	mile[l[i]] = 1
diye = [0] * (n + 1)
for i in range(n):
	if l[i] != 0:
		diye[i + 1] = 1
same = []
for i in range(n + 1):
	if mile[i] == 0 and diye[i] == 0:
		same.append(i)
if len(same) > 1:
	for i in range(len(same) - 1):
		l[same[i] - 1] = same[i + 1]
	l[same[len(same) - 1] - 1] = same[0]
elif len(same) == 1:
	for i in range(1, n + 1):
		if mile[i] == 0 and i != same[0]:
			l[same[0] - 1] = i
mile = [0] * (n + 1)
for i in range(n):
	mile[l[i]] = 1
leftnum = []
for i in range(1, n + 1):
	if mile[i] == 0:
		leftnum.append(i)
j = 0
for i in range(n):
	if l[i] == 0:
		l[i] = leftnum[j]
		j += 1
print(*l)


n = int(input())
x = list(map(int, input().split()))
tmp = sorted(x)
r = []
for i in range(n - 1):
	if tmp[i + 1] != tmp[i] + 1 and tmp[i + 1]:
		w = tmp[i + 1] - tmp[i]
		while w >= 2:
			r += [tmp[i + 1] - (w - 1)]
			w -= 1
if tmp[n - 1] != n:
	w = tmp[n - 1]
	while w < n:
		r += [w + 1]
		w += 1
tmp = x.copy()
q = 0
for b in range(n):
	if x[b] == 0:
		if b + 1 != r[len(r) - 1]:
			x[b] = r[len(r) - 1]
			r.pop(len(r) - 1)
		elif b + 1 != r[0]:
			x[b] = r[0]
			r.pop(0)
		else:
			x[b] = r[0]
			while True:
				if tmp[q] == 0 and b + 1 != x[q]:
					(x[q], x[b]) = (x[b], x[q])
					break
				q += 1
print(*x)


from collections import Counter, deque
N = int(input())
fi = [int(x) for x in input().split()]
freq = Counter(fi)
unsure = []
for x in range(N):
	if freq[x + 1] == 0:
		unsure.append(x + 1)
zeropos = set([x + 1 for x in range(len(fi)) if fi[x] == 0])
nonself = [x for x in unsure if x in zeropos]
nsset = set(nonself)
nonself = deque(nonself)
free = [x for x in unsure if x not in zeropos]
fset = set(free)
free = deque(free)
for (index, i) in enumerate(fi[:-1]):
	if i != 0:
		print(i, end=' ')
	elif len(nonself) > 0:
		if len(nonself) > 1:
			if nonself[0] == index + 1:
				nonself.rotate()
				print(nonself.popleft(), end=' ')
			else:
				print(nonself.popleft(), end=' ')
		elif nonself[0] == index + 1:
			print(free.popleft(), end=' ')
		else:
			print(nonself.popleft(), end=' ')
	else:
		print(free.popleft(), end=' ')
i = fi[-1]
index = len(fi) - 1
if i != 0:
	print(i)
elif len(nonself) > 0:
	if len(nonself) > 1:
		if nonself[0] == index + 1:
			nonself.rotate()
			print(nonself.popleft())
		else:
			print(nonself.popleft())
	elif nonself[0] == index + 1:
		print(free.popleft())
	else:
		print(nonself.popleft())
else:
	print(free.popleft())


n = int(input())
ar = [int(x) for x in input().split()]
gave = [0] * (n + 1)
got = [0] * (n + 1)
for k in range(1, n + 1):
	if ar[k - 1] != 0:
		gave[k] = 1
		got[ar[k - 1]] = 1
ngot = []
ngave = []
for k in range(len(gave)):
	if gave[k] == 0 and k != 0:
		ngave.append(k)
for k in range(len(got)):
	if got[k] == 0 and k != 0:
		ngot.append(k)
done = 0
m = len(ngot)
ptr = 0
while done != max(0, len(ngave) - 2):
	if ngot[ptr] == ngave[done] or ngot[ptr] < 0:
		ptr = (ptr + 1) % m
		continue
	ar[ngave[done] - 1] = ngot[ptr]
	done += 1
	ngot[ptr] *= -1
a = ngave[-1]
b = ngave[-2]
flag = False
for k in ngot:
	if k > 0 and flag == False:
		c = k
		flag = True
	elif k > 0:
		d = k
if a == c or b == d:
	ar[a - 1] = d
	ar[b - 1] = c
else:
	ar[a - 1] = c
	ar[b - 1] = d
for k in ar:
	print(k, end=' ')


n = int(input())
fs = list(map(int, input().split()))
given_to = [False] * n
fucked = []
ok = []
shlag = []
for i in range(len(fs)):
	fs[i] -= 1
	if fs[i] != -1:
		given_to[fs[i]] = True
for i in range(n):
	if fs[i] == -1 and (not given_to[i]):
		fucked.append(i)
	elif not given_to[i]:
		ok.append(i)
	elif fs[i] == -1:
		shlag.append(i)
if len(fucked) == 1:
	fs[shlag[0]] = fucked[0]
	fs[fucked[0]] = ok[0]
	for i in range(1, len(ok)):
		fs[shlag[i]] = ok[i]
elif fucked:
	for i in range(len(fucked) - 1):
		fs[fucked[i]] = fucked[i + 1]
	fs[fucked[len(fucked) - 1]] = fucked[0]
	for i in range(len(ok)):
		fs[shlag[i]] = ok[i]
else:
	for i in range(len(shlag)):
		fs[shlag[i]] = ok[i]
for i in range(n):
	fs[i] += 1
print(' '.join(list(map(str, fs))))


n = int(input())
a = list(input().split())
b = []
c = [0]
d = []
for i in range(n):
	c.append(0)
	a[i] = int(a[i])
	if a[i] == 0:
		b.append(i)
for i in range(n):
	c[a[i] - 1] = 1
for i in range(n):
	if c[i] == 0:
		d.append(i + 1)
for i in range(len(b)):
	a[b[i]] = d[i]
for i in range(len(b) - 1):
	if a[b[i]] == b[i] + 1:
		a[b[i]] += a[b[i + 1]]
		a[b[i + 1]] = a[b[i]] - a[b[i + 1]]
		a[b[i]] -= a[b[i + 1]]
		b[i] += b[i + 1]
		b[i + 1] = b[i] - b[i + 1]
		b[i] -= b[i + 1]
if a[b[-1]] == b[-1] + 1:
	a[b[-1]] += a[b[0]]
	a[b[0]] = a[b[-1]] - a[b[0]]
	a[b[-1]] -= a[b[0]]
res = ''
for i in a:
	res += str(i)
	res += ' '
print(res)


n = int(input())
xs = list(map(int, input().split()))
d = set()
e = list()
es = set()
for (i, x) in enumerate(xs):
	d.add(x)
	if x == 0:
		e.append(i + 1)
		es.add(i + 1)
d2 = set()
e2 = list()
for i in range(n + 1):
	if i not in d:
		d2.add(i)
		e2.append(i)
rr = dict()
tmp = set()
for ee in es:
	if ee in d2:
		xx = d2.pop()
		if ee != xx:
			rr[ee] = xx
		else:
			yy = d2.pop()
			rr[ee] = yy
			d2.add(xx)
		tmp.add(ee)
for xx in tmp:
	es.remove(xx)
for ee in es:
	if ee not in d2:
		xx = d2.pop()
		rr[ee] = xx
r = []
for (i, x) in enumerate(xs):
	if x != 0:
		r.append(x)
		continue
	r.append(rr[i + 1])
print(*r)


n = int(input())
a = list(map(int, input().split()))
zero = []
ng = []
g = []
gi = [0] * n
for i in range(n):
	if a[i] == 0:
		zero.append(i)
	else:
		g.append(a[i] - 1)
		gi[a[i] - 1] = 1
for i in range(n):
	if gi[i] == 0:
		ng.append(i)
for i in range(n):
	if a[i] == 0:
		if ng[-1] != i:
			a[i] = ng[-1] + 1
			ng.pop()
		elif ng[-1] == i and len(ng) > 1:
			a[i] = ng[-2] + 1
			ng.remove(ng[-2])
		elif a[zero[0]] != 0:
			a[i] = a[zero[0]]
			a[zero[0]] = ng[-1] + 1
		else:
			a[i] = a[zero[1]]
			a[zero[0]] = ng[-1] + 1
print(*a, sep=' ')


n = int(input())
arr = list(map(int, input().split()))
hash = [0] * n
lis = []
ind = []
for i in range(len(arr)):
	if arr[i] > 0:
		hash[arr[i] - 1] = 1
	else:
		ind.append(i + 1)
for i in range(len(hash)):
	if hash[i] == 0:
		lis.append(i + 1)
ind.sort()
lis.sort()
tup = []
cnt = 0
mark = 0
temp = 0
for i in range(len(ind)):
	tup.append((ind[i], lis[i]))
	if ind[i] == lis[i]:
		cnt += 1
		mark = i
if cnt == 0:
	for i in range(len(tup)):
		if tup[i] != None:
			arr[tup[i][0] - 1] = tup[i][1]
if cnt == 1:
	if mark >= 0 and mark < len(tup) - 1:
		arr[tup[mark][0] - 1] = tup[mark + 1][1]
		arr[tup[mark + 1][0] - 1] = tup[mark][1]
		tup[mark] = None
		tup[mark + 1] = None
	elif mark == len(tup) - 1:
		arr[tup[mark][0] - 1] = tup[mark - 1][1]
		arr[tup[mark - 1][0] - 1] = tup[mark][1]
		tup[mark] = None
		tup[mark - 1] = None
	for i in range(len(tup)):
		if tup[i] != None:
			arr[tup[i][0] - 1] = tup[i][1]
elif cnt > 1:
	for i in range(len(tup)):
		if tup[i][0] != tup[i][1]:
			arr[tup[i][0] - 1] = tup[i][1]
			tup[i] = None
	for i in range(tup.count(None)):
		tup.remove(None)
	arr[tup[len(tup) - 1][0] - 1] = tup[0][0]
	for i in range(len(tup) - 1):
		arr[tup[i][0] - 1] = tup[i + 1][1]
for i in range(len(arr)):
	print(arr[i], end=' ')


from math import *
from collections import *
import sys
sys.setrecursionlimit(10 ** 9)
n = int(input())
a = list(map(int, input().split()))
b = [0 for i in range(n + 1)]
for i in a:
	b[i] = 1
ans = []
for i in range(1, n + 1):
	if b[i] == 0:
		ans.append(i)
j = 0
prev = -1
m = len(ans)
for i in range(n - 1, -1, -1):
	if a[i] == 0:
		if ans[j] == i + 1:
			if j + 1 == m:
				(ans[j - 1], ans[j]) = (ans[j], ans[j - 1])
				a[prev] = ans[j - 1]
			else:
				(ans[j + 1], ans[j]) = (ans[j], ans[j + 1])
		a[i] = ans[j]
		j += 1
		prev = i
for i in a:
	print(i, end=' ')
print()


n = int(input())
a = [int(i) for i in input().split()]
s = set()
for i in range(1, n + 1):
	s.add(i)
x = []
for i in range(n):
	if a[i] == 0:
		x.append(i + 1)
	else:
		s.remove(a[i])
for i in x:
	if i in s:
		for j in s:
			if j != i:
				a[i - 1] = j
				break
		s.remove(a[i - 1])
for i in range(n):
	if a[i] == 0:
		for j in s:
			if j != i + 1:
				a[i] = j
				break
		s.remove(j)
print(*a)


n = int(input())
f = list(map(int, input().split()))
f2 = [0 for x in range(n)]
(fng, fnr) = ([], [])
for (i, fi) in enumerate(f):
	if fi != 0:
		f2[fi - 1] = i + 1
	else:
		fng.append(i + 1)
li = []
for (i, fi) in enumerate(f2):
	if fi == 0:
		fnr_len = len(fnr)
		if fng[fnr_len] == i + 1:
			li.append(fnr_len)
		fnr.append(i + 1)
li_len = len(li)
if li_len > 0:
	for i in range(1, li_len, 2):
		(fng[li[i - 1]], fng[li[i]]) = (fng[li[i]], fng[li[i - 1]])
	if li_len % 2 != 0:
		if li[-1] != 0:
			(fng[li[-1]], fng[0]) = (fng[0], fng[li[-1]])
		else:
			(fng[li[-1]], fng[-1]) = (fng[-1], fng[li[-1]])
for (fngi, fnri) in zip(fng, fnr):
	f[fngi - 1] = fnri
print(*f)


n = int(input())
a = [-1] + list(map(int, input().split()))
(indeg, outdeg) = ([0] * (n + 1), [0] * (n + 1))
for i in range(1, n + 1):
	if a[i]:
		outdeg[i] = 1
		indeg[a[i]] = 1
vs = [[] for _ in range(3)]
for i in range(1, n + 1):
	if indeg[i] and (not outdeg[i]):
		vs[0].append(i)
	elif not indeg[i] and outdeg[i]:
		vs[1].append(i)
	elif not indeg[i] and (not outdeg[i]):
		vs[2].append(i)
rem = len(vs[0]) + len(vs[1]) + len(vs[2])
v = -1
while rem:
	if vs[0]:
		v = vs[0].pop()
		rem -= 1
	else:
		v = vs[2].pop()
		vs[1].append(v)
	while vs[2]:
		a[v] = vs[2][-1]
		v = vs[2].pop()
		rem -= 1
	a[v] = vs[1][-1]
	if vs[1]:
		v = vs[1].pop()
		rem -= 1
	else:
		v = vs[2].pop()
		vs[0].append(v)
print(*a[1:])


t = 1
while t:
	t -= 1
	n = int(input())
	l = list(map(int, input().split()))
	a = [0 for i in range(n + 1)]
	for i in l:
		a[i] = 1
	b = []
	for i in range(n + 1):
		if a[i] == 0:
			b.append(i)
	c = []
	for i in range(n):
		if l[i] == 0:
			c.append(i + 1)
	c.sort()
	b.sort()
	for i in range(len(b)):
		if b[i] == c[i] and i == 0:
			(b[i], b[i + 1]) = (b[i + 1], b[i])
		elif b[i] == c[i]:
			(b[i], b[i - 1]) = (b[i - 1], b[i])
	cnt = 0
	for i in range(n):
		if l[i] == 0:
			l[i] = b[cnt]
			cnt += 1
	print(*l)


import sys
input = sys.stdin.readline
N = int(input())
li = list(map(int, input().split()))
check = [1 for i in range(N + 1)]
dup = [1 for i in range(N + 1)]
for i in range(len(li)):
	if li[i] == 0:
		dup[i + 1] += 1
	else:
		dup[li[i]] -= 1
		check[li[i]] = 0
dup2 = [i for i in range(1, len(dup)) if dup[i] == 2]
toGo = dup2[:]
fromGo = dup2[:]
for i in range(len(li)):
	if li[i] == 0 and dup[i + 1] != 2:
		fromGo.append(i + 1)
for i in range(1, len(check)):
	if check[i] & 1 and dup[i] != 2:
		toGo.append(i)
for i in range(len(fromGo)):
	li[fromGo[i] - 1] = toGo[(i + 1) % len(toGo)]
result = list(map(str, li))
print(' '.join(result))


import sys
from collections import deque
input = lambda : sys.stdin.readline().rstrip('\r\n')
N = int(input())
givers = []
friends = []
receivers = {i for i in range(N)}
for (i, friend) in enumerate(input().split()):
	friend = int(friend) - 1
	friends.append(friend)
	if friend == -1:
		givers.append(i)
	else:
		receivers.remove(friend)
receivers = deque(receivers)
givers = deque(givers)
while givers:
	giver = givers.popleft()
	receiver = receivers.popleft()
	if giver != receiver and receivers != givers:
		friends[giver] = receiver
	else:
		receivers.append(receiver)
		friends[giver] = receivers.popleft()
print(*[i + 1 for i in friends])


numfriends = int(input())
friendsvalues = list(map(int, input().split()))
missingvalues1 = list(range(1, numfriends + 1))
missingvaluesneat = []
for i in friendsvalues:
	if i != 0:
		missingvalues1[i - 1] = 'k'
for i in range(numfriends):
	if missingvalues1[i] != 'k':
		missingvaluesneat.append(missingvalues1[i])
missingvaluesneat.append(missingvaluesneat[0])
missingvaluesneat.pop(0)
missingvaluesneat.reverse()
pointer1 = 0
indextracker = []
while pointer1 < numfriends:
	if friendsvalues[pointer1] == 0:
		if pointer1 + 1 == missingvaluesneat[-1]:
			if len(missingvaluesneat) == 1:
				(friendsvalues[indextracker[0]], friendsvalues[pointer1]) = (missingvaluesneat[0], friendsvalues[indextracker[0]])
			else:
				friendsvalues[pointer1] = missingvaluesneat[-2]
				missingvaluesneat.pop(-2)
			indextracker.append(pointer1)
		elif pointer1 + 1 != missingvaluesneat[-1]:
			friendsvalues[pointer1] = missingvaluesneat[-1]
			missingvaluesneat.pop()
			indextracker.append(pointer1)
	pointer1 += 1
print(' '.join(map(str, friendsvalues)))


import sys
import math
from functools import reduce
import bisect

def getN():
	return int(input())

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

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

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

def index(a, x):
	i = bisect.bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return i
	return False
n = getN()
arr = getList()
without = set((x for x in range(1, n + 1)))
available = set()
zero = set()
for i in range(n):
	if arr[i] != 0:
		available.add(arr[i])
	else:
		zero.add(i + 1)
without -= available
full_zero = list(without & zero)
if full_zero:
	if len(full_zero) > 1:
		for i in range(len(full_zero) - 1):
			arr[full_zero[i] - 1] = full_zero[i + 1]
			zero.remove(full_zero[i])
			without.remove(full_zero[i])
		arr[full_zero[-1] - 1] = full_zero[0]
		zero.remove(full_zero[-1])
		without.remove(full_zero[-1])
	else:
		x = zero.pop()
		if x != full_zero[0]:
			arr[x - 1] = full_zero[0]
		else:
			y = zero.pop()
			arr[y - 1] = full_zero[0]
			zero.add(x)
		without.remove(full_zero[0])
zero = list(zero)
without = list(without)
for i in range(len(zero)):
	arr[zero[i] - 1] = without[i]
print(*arr)


import math
from collections import defaultdict, Counter, deque
INF = float('inf')

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def primeFactor(n):
	if n % 2 == 0:
		return 2
	i = 3
	while i ** 2 <= n:
		if n % i == 0:
			return i
		i += 1
	return n

def main():
	n = int(input())
	arr = list(map(int, input().split()))
	graph = {}
	isolated = []
	for i in range(n):
		if arr[i] > 0:
			graph[i + 1] = arr[i]
		else:
			isolated.append(i + 1)
	inter = set(isolated).intersection(set(graph.values()))
	for i in range(len(isolated)):
		target = isolated[(i + 1) % len(isolated)]
		if target not in inter:
			graph[isolated[i]] = isolated[(i + 1) % len(isolated)]
	allNodes = set((i + 1 for i in range(n)))
	indegree = list(allNodes - set(graph.keys()))
	outdegree = list(allNodes - set(graph.values()))
	for i in range(len(indegree)):
		graph[indegree[i]] = outdegree[i]
	for i in range(n):
		arr[i] = graph[i + 1]
	print(*arr)
t = 1
for _ in range(t):
	main()


q = 1
for i in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	confused = []
	party = [0] * (n + 1)
	for i in range(n):
		if l[i] == 0:
			confused.append(i + 1)
	for i in range(n):
		party[l[i]] += 1
	not_gifted = []
	for i in range(1, n + 1):
		if party[i] == 0:
			not_gifted.append(i)
	i = 0
	j = 0
	k = len(confused)
	for i in range(len(confused)):
		if confused[i] == not_gifted[i]:
			temp = not_gifted[i]
			not_gifted[i] = not_gifted[(i + 1) % k]
			not_gifted[(i + 1) % k] = temp
	j = 0
	for i in range(n):
		if l[i] != 0:
			print(l[i], end=' ')
		else:
			print(not_gifted[j], end=' ')
			j += 1


n = int(input())
ls = list(map(int, input().split()))
nogive = set(list(range(1, n + 1)))
noget = set(list(range(1, n + 1)))
for (i, e) in enumerate(ls):
	if e != 0:
		nogive.remove(i + 1)
		noget.remove(e)
prio = nogive.intersection(noget)
while len(nogive):
	if len(prio):
		giver = prio.pop()
		nogive.remove(giver)
	else:
		giver = nogive.pop()
	if len(prio):
		getter = prio.pop()
		noget.remove(getter)
	else:
		getter = noget.pop()
		if getter == giver:
			getter2 = noget.pop()
			noget.add(getter)
			getter = getter2
	ls[giver - 1] = getter
for e in ls:
	print(e, end=' ')


n = int(input())
a = [int(x) - 1 for x in input().split()]
g = []
r = []
hit = n * [0]
for i in range(n):
	if a[i] == -1:
		g.append(i)
	else:
		hit[a[i]] = 1
for i in range(n):
	if hit[i] == 0:
		r.append(i)
l = len(g)
for i in range(l - 2):
	if g[i] != r[i]:
		a[g[i]] = r[i]
	else:
		a[g[i]] = r[i + 1]
		k = r[i]
		r[i] = r[i + 1]
		r[i + 1] = k
g1 = g[l - 2]
g2 = g[l - 1]
r1 = r[l - 1]
r2 = r[l - 2]
if g1 == r1 or g2 == r2:
	a[g1] = r2
	a[g2] = r1
else:
	a[g1] = r1
	a[g2] = r2
for x in a:
	print(x + 1, end=' ')


n = int(input())
ar = [int(x) for x in input().split()]
al = [0] * n
br = [0] * n
rem = []
count = 0
for i in range(n):
	if ar[i] == 0:
		count += 1
	else:
		br[ar[i] - 1] = 1
	al[i] = ar[i]
for i in range(n):
	if br[i] == 0:
		rem.append(i)
p = 0
q = len(rem) - 1
val = 0
b = True
for i in range(n):
	if ar[i] == 0:
		if rem[p] != i:
			ar[i] = rem[p] + 1
			p += 1
		elif rem[q] != i:
			ar[i] = rem[q] + 1
			q -= 1
		else:
			b = False
			val = i
if b == False:
	for i in range(n):
		if al[i] == 0 and ar[i] != 0:
			temp = ar[i]
			ar[i] = val + 1
			ar[val] = temp
			break
for i in range(n):
	print(ar[i], end=' ')


import sys
input = sys.stdin.readline
import collections
n = int(input())
giving = [int(i) for i in input().split()]
not_giving = [0] * (n + 1)
not_recieving = [int(i) for i in range(n + 1)]
for i in range(len(giving)):
	if giving[i] == 0:
		not_giving[i] = i + 1
	not_recieving[giving[i]] = 0
not_giving = collections.deque(list(set(not_giving))[1:])
not_recieving = collections.deque(list(set(not_recieving))[1:])
if not_giving[-1] == not_recieving[-1]:
	(not_recieving[-1], not_recieving[-2]) = (not_recieving[-2], not_recieving[-1])
i = 0
while not_giving:
	if not_giving[i] != not_recieving[i]:
		giving[not_giving[i] - 1] = not_recieving[i]
		not_giving.popleft()
		not_recieving.popleft()
	else:
		j = not_recieving.popleft()
		not_recieving.append(j)
print(*giving)


import sys
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n = int(input())
fs = list(map(int, input().split()))

def arrangeSanta(n, fs):
	empty = set()
	hasSanta = set()
	for (i, f) in enumerate(fs):
		if f > 0:
			hasSanta.add(f - 1)
		else:
			empty.add(i)
	if not empty:
		return
	noSanta = set((i for i in range(n) if i not in hasSanta and i not in empty))
	if not noSanta:
		s = empty.pop()
		v = s
		while empty:
			to = empty.pop()
			fs[v] = to + 1
			v = to
		fs[v] = s + 1
		return
	for s in noSanta:
		v = fs[s] - 1
		while fs[v] > 0:
			v = fs[v] - 1
		empty.remove(v)
		fs[v] = s + 1
	if len(empty) == 1:
		to = empty.pop()
		fs[v] = to + 1
		fs[to] = s + 1
	elif len(empty) > 1:
		s = empty.pop()
		v = s
		while empty:
			to = empty.pop()
			fs[v] = to + 1
			v = to
		fs[v] = s + 1
	return
arrangeSanta(n, fs)
print(*fs)


def inp(dtype=str, strip=True):
	s = input()
	res = [dtype(p) for p in s.split()]
	res = res[0] if len(res) == 1 and strip else res
	return res

def problem1():
	t = inp(int)
	for _ in range(t):
		(h, m) = inp(int)
		print((23 - h) * 60 + (60 - m))

def problem2():
	t = inp(int)
	for _ in range(t):
		(n, k) = inp(int)
		res = n // k * k + min(n % k, k // 2)
		print(res)

def problem3():
	n = inp(int)
	f = inp(int, strip=False)
	f = [ch - 1 for ch in f]
	g = [-1 for _ in range(n)]
	for (i, ch) in enumerate(f):
		if ch >= 0:
			g[ch] = i
	gave = set([i for i in range(n) if f[i] >= 0 and g[i] == -1])
	received = set([i for i in range(n) if f[i] == -1 and g[i] >= 0])
	neither = set([i for i in range(n) if f[i] == -1 and g[i] == -1])
	while len(neither):
		if len(received):
			i = received.pop()
		else:
			i = neither.pop()
			gave.add(i)
		j = neither.pop()
		received.add(j)
		f[i] = j
	while len(received):
		i = received.pop()
		j = gave.pop()
		f[i] = j
	f = [ch + 1 for ch in f]
	print(' '.join([str(ch) for ch in f]))

def problem4():
	pass

def problem5():
	pass
problem3()


from sys import stdin
input = stdin.readline
from heapq import heapify, heappush, heappop, heappushpop
from collections import defaultdict as dd, deque as dq, Counter as C
from math import factorial as f, ceil, gcd, sqrt, log
from bisect import bisect_left as bl, bisect_right as br
from itertools import combinations as c, permutations as p
from math import factorial as f, ceil, gcd, sqrt, log
mp = lambda : map(int, input().split())
it = lambda : int(input())
ls = lambda : list(input().strip().split())
mt = lambda r: [list(mp()) for _ in range(r)]
lcm = lambda a, b: a * b // gcd(a, b)

def fibo_n(n):
	return ((1 + sqrt(5)) / 2) ** n / sqrt(5)
mod = 1000000007

def solve(no_recived, remain):
	for i in range(len(no_recived)):
		if no_recived[i] == remain[i]:
			if i + 1 == len(remain):
				(no_recived[0], no_recived[-1]) = (no_recived[-1], no_recived[0])
				continue
			(no_recived[i], no_recived[-1]) = (no_recived[-1], no_recived[i])
	flag = 0
	for i in range(len(remain)):
		if remain[i] == no_recived[i]:
			flag = 1
	return flag
for _ in range(1):
	a = it()
	l = list(mp())
	recived = set(l)
	recived.discard(0)
	s = set()
	remain = []
	for i in range(a):
		s.add(i + 1)
		if l[i] == 0:
			remain.append(i + 1)
	no_recived = dq(sorted(s - recived))
	remain.reverse()
	if solve(no_recived, remain) == 0:
		for ele in remain:
			l[ele - 1] = no_recived.popleft()
		print(*l)


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left
from bisect import bisect_right

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

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

def I():
	return int(stdin.readline())
P = 1000000007

def main():
	n = I()
	arr = L()
	a1 = set(arr)
	lis = []
	for i in range(1, n + 1):
		if i not in a1:
			lis.append(i)
	c1 = 0
	for i in range(n):
		if arr[i] == 0 and lis[c1] == i + 1:
			(lis[c1], lis[c1 - 1]) = (lis[c1 - 1], lis[c1])
			c1 += 1
			continue
		if arr[i] == 0:
			c1 += 1
	c1 = 0
	for i in range(n):
		if arr[i] == 0:
			arr[i] = lis[c1]
			c1 += 1
	print(*arr)
main()


t = int(input())
list1 = list(map(int, input().split()))
set1 = set()
set2 = set()
indi = []
for i in range(len(list1)):
	if list1[i] != 0:
		set1.add(list1[i])
	else:
		indi.append(i + 1)
	set2.add(i + 1)
p = list(set2 - set1)
while len(p) > 2:
	ind_last = indi[-1]
	if ind_last != p[-1]:
		list1[ind_last - 1] = p[-1]
	else:
		(p[-1], p[-2]) = (p[-2], p[-1])
		list1[ind_last - 1] = p[-1]
	p.pop()
	indi.pop()
if p[0] == indi[0] or p[1] == indi[1]:
	list1[indi[0] - 1] = p[1]
	list1[indi[1] - 1] = p[0]
else:
	list1[indi[0] - 1] = p[0]
	list1[indi[1] - 1] = p[1]
print(*list1)


t = int(input())
in_ = [0 for _ in range(t)]
out = [0 for _ in range(t)]
friends = [int(j) - 1 for j in input().split()]
for idx in range(t):
	cur = friends[idx]
	if cur != -1:
		out[idx] = 1
		in_[cur] = 1
iso = []
for i in range(0, t):
	if in_[i] == 0 and out[i] == 0:
		iso.append(i)
if len(iso) == 1:
	idx = iso[0]
	for i in range(0, t):
		if in_[i] == 0 and i != idx:
			in_[i] = 1
			out[idx] = 1
			friends[idx] = i
			break
elif len(iso) > 1:
	for i in range(0, len(iso)):
		cur = iso[i]
		next = iso[(i + 1) % len(iso)]
		friends[cur] = next
		out[cur] = 1
		in_[next] = 1
ins = []
outs = []
for i in range(0, t):
	if in_[i] == 0:
		ins.append(i)
	if out[i] == 0:
		outs.append(i)
for i in range(0, len(ins)):
	friends[outs[i]] = ins[i]
for f in friends:
	print(f + 1, end=' ')


n = int(input())
arr = [int(x) for x in input().strip().split()]
for i in range(n):
	arr[i] -= 1
a = [0] * n
for i in range(n):
	if arr[i] != -1:
		a[arr[i]] += 1
t = []
for i in range(n):
	if a[i] == 0:
		t.append(i)
ne = []
for i in range(2):
	for j in range(len(t)):
		ne.append(t[j])
ne = ne[1:len(t) + 1]
k = 0
for i in range(n):
	if arr[i] == -1:
		arr[i] = ne[k]
		k += 1
for i in range(n):
	if arr[i] - i == 0:
		for j in range(len(ne)):
			if ne[j] > i:
				break
		temp = arr[i]
		for k in range(n):
			if arr[k] == ne[j]:
				break
		arr[i] = arr[k]
		arr[k] = temp
for i in arr:
	print(i + 1, end=' ')