Simulate a sequence of peg placements and removals on a dependency DAG, tracking peak peg count and the first wet-rule violation.
Medium4SimulationGraphImplementationArrayInterviewNo attempts yetTime limit2sMemory limit512 MBFiona is an expert climber. She carries pegs and hammers them into strategic points of a rock wall so that less experienced climbers have something to stand on. Fiona can climb anywhere on the wall, but hammering a peg needs balance, so she places a peg at a point only while every point it depends on holds a peg. She can pull a peg out and use it again later.
A plan is a sequence of steps, and each step names one strategic point. If that point has no peg, Fiona places one there. If it already has a peg, she pulls that peg out. The number of pegs a plan needs is the largest number of pegs on the wall at the same time while she carries the plan out.
Fiona wrote her plans for dry rock, where a peg can be pulled out at any moment. Yesterday it rained, so the rock is wet, and pulling a peg out is unsafe unless she has the same support she had when she hammered it in. Under this wet rule she pulls the peg at point i only while every point that i depends on still holds a peg. The condition for placing a peg does not change.
Take a wall with 5 strategic points. Point 1 is close to the ground, so it depends on nothing. Points 2 and 3 each depend on point 1, point 4 depends on points 2 and 3, and point 5 depends on point 4. The plan 1, 2, 3, 1, 4, 2, 3, 5 is safe on dry rock and needs 3 pegs. On wet rock, step 6 pulls the peg at point 2 while point 1 is bare, and that step is the first one that breaks the wet rule.
You are given a wall and one of Fiona's dry rock plans. Report how many pegs the plan needs and which step first breaks the wet rule.
The first line contains an integer n (1≤n≤1000), the number of strategic points in the wall.
Each of the next n lines describes one point. Line i contains an integer p (0≤p<n) followed by p distinct integers x1,…,xp (1≤xj<i). Point i depends on exactly these points, so all of them must hold a peg when a peg at point i is placed or pulled out.
The next line contains an integer t (1≤t≤1000), the number of steps of the dry rock plan. Each of the next t lines contains an integer i (1≤i≤n), the point that step touches.
The plan is safe on dry rock: whenever a step places a peg at point i, every point that i depends on already holds a peg. Every strategic point holds a peg after at least one step of the plan.
Print two integers separated by one space. The first integer is the number of pegs the dry rock plan needs. The second integer is the number of the first step that breaks the wet rule, counting steps from 1. Print 0 as the second integer when every step of the plan obeys the wet rule.