All problems

Problem 932

Loud and Rich

Medium · 20 pts · Graph, Depth-First Search, Topological Sort

Problem

People are numbered 0 to N - 1, each with a distinct quietness value. Each pair (a, b) in RICHER says a is richer than b, and the information is consistent (no cycles). For every person x, find the quietest person (smallest quietness) among everyone who is definitely at least as rich as x, which includes x and everyone reachable through richer relations. Memoised DFS over the 'richer than me' edges gives each answer from the answers of directly richer people.

Input

The first line contains N and M. The next M lines contain pairs a b (a is richer than b). The last line contains the N quietness values.

Output

Print N integers separated by spaces: the answer for each person.

Constraints

1 <= N <= 500; 0 <= M <= N × (N - 1) / 2; quietness values are a permutation of 0 .. N-1

Example input

8 7
1 0
2 1
3 1
3 7
4 3
5 3
6 3
3 2 5 4 6 1 7 0

Example output

5 5 2 5 4 5 6 7

Explanation

Person 1 is richer than 0; 2 and 3 are richer than 1; 4, 5 and 6 are richer than 3. Among persons 0 to 6 the quietest is person 5 (quietness 1), so answer[0] = 5. Doing this for everyone gives 5 5 2 5 4 5 6 7.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Number of Vertices to Reach All Nodes Next: Count Servers that Communicate