from collections import defaultdict, deque
def find_order(N, M, groups, dependencies):
# Create adjacency list and count incoming edges
adj = defaultdict(list)
in_degree = [0] * N
for a, b in dependencies:
a, b = a-1, b-1 # Convert to 0-based indexing
adj[a].append(b)
in_degree[b] += 1
# Create priority queue (will store projects with no dependencies)
# Format: (group_id, project_id)
available = []
# Add all projects with no dependencies initially
for i in range(N):
if in_degree[i] == 0:
available.append((groups[i], i))
available.sort() # Sort by group_id, then project_id
result = []
while available:
# Take project with lowest group_id and lowest project_id
_, curr_proj = available.pop(0)
result.append(curr_proj + 1) # Convert back to 1-based indexing
# Process all dependencies
for next_proj in adj[curr_proj]:
in_degree[next_proj] -= 1
if in_degree[next_proj] == 0:
available.append((groups[next_proj], next_proj))
available.sort() # Keep the list sorted
# Check if we used all projects
if len(result) != N:
return [-1]
return result
def main():
# Read input
N, M = map(int, input().split())
groups = list(map(int, input().split()))
dependencies = []
for _ in range(M):
a, b = map(int, input().split())
dependencies.append((a, b))
# Find order
result = find_order(N, M, groups, dependencies)
# Print result
if result[0] == -1:
print(-1)
else:
print(*result)
if __name__ == "__main__":
main()
ZnJvbSBjb2xsZWN0aW9ucyBpbXBvcnQgZGVmYXVsdGRpY3QsIGRlcXVlCgpkZWYgZmluZF9vcmRlcihOLCBNLCBncm91cHMsIGRlcGVuZGVuY2llcyk6CiAgICAjIENyZWF0ZSBhZGphY2VuY3kgbGlzdCBhbmQgY291bnQgaW5jb21pbmcgZWRnZXMKICAgIGFkaiA9IGRlZmF1bHRkaWN0KGxpc3QpCiAgICBpbl9kZWdyZWUgPSBbMF0gKiBOCiAgICAKICAgIGZvciBhLCBiIGluIGRlcGVuZGVuY2llczoKICAgICAgICBhLCBiID0gYS0xLCBiLTEgICMgQ29udmVydCB0byAwLWJhc2VkIGluZGV4aW5nCiAgICAgICAgYWRqW2FdLmFwcGVuZChiKQogICAgICAgIGluX2RlZ3JlZVtiXSArPSAxCiAgICAKICAgICMgQ3JlYXRlIHByaW9yaXR5IHF1ZXVlICh3a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