A unit's chain of command is modeled as a rooted tree of n officers, numbered 1 to n. Every officer other than the current commander-in-chief reports directly to exactly one immediate superior. Following a reorganization, officer k — who currently has no subordinates of their own — is promoted to become the new commander-in-chief. The chain of command must be re-derived so that officer k sits at the top: for every other officer, their new immediate superior becomes whichever adjacent officer (in the original reporting structure, considered without direction) lies one step closer to officer k. Every reporting relationship that does not lie on the path between the old commander-in-chief and officer k stays exactly as it was; only the links along that path reverse direction. Determine the new immediate superior of every officer.
Line 1: two integers n and k (1 <= k <= n) — the number of officers and the officer being promoted to commander-in-chief.
Line 2: n integers p_1 ... p_n, where p_i is the immediate superior of officer i, or 0 if officer i is the current commander-in-chief. Exactly one p_i equals 0.
n space-separated integers q_1 ... q_n, where q_i is the immediate superior of officer i after the reorganization, with q_k = 0.
1 <= n <= 100000. The given p array forms a valid rooted tree on n officers. Officer k has no subordinates (no i with p_i = k) whenever n > 1; when n = 1, k = 1.
Example 1
Input
5 5 0 1 2 3 4
Expected
2 3 4 5 0
Explanation
The original chain is 1 <- 2 <- 3 <- 4 <- 5 (officer 1 is commander-in-chief, and each later officer reports to the one before). Promoting the bottom leaf, officer 5, reverses every link on the path from 1 to 5: officer 1 now reports to 2, 2 reports to 3, 3 reports to 4, 4 reports to 5, and 5 is now the top (parent 0). The output is "2 3 4 5 0".
Example 2
Input
4 4 0 1 1 1
Expected
4 1 1 0
Explanation
Officer 1 is commander-in-chief with three direct subordinates: 2, 3, and 4. Promoting leaf officer 4 only reverses the single link between 1 and 4: officer 1 now reports to officer 4, while officers 2 and 3 still report to officer 1 exactly as before, and officer 4 is now the top. The output is "4 1 1 0".
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →