Kth Ancestor

advertisement
KthAncestor
Atreeof nodesisanun-directedconnectedgraphhaving
edges.Letusdenote astheroot
node.If isanodesuchthatitisatadistanceof from ,and isanodesuchthatitisatatdistanceof
from and isconnectedto ,thenwecall astheparentof .
Similarly,if isatadistanceof from and isatadistanceof
length from to ,thenwecall asthe thparentof .
from andthereisapathof
SusanlikestoplaywithgraphsandTreedatastructureisoneofherfavorites.Shehasdesignedaproblem
andwantstoknowifanyonecansolveit.Sometimessheaddsorremovesaleafnode.Yourtaskistofigure
outthe thparentofanodeatanyinstant.
InputFormat
Thefirstlinecontainaninteger denotingthenumberoftestcases. testcasesfollow.Firstlineofeach
testcasecontainsaninteger ,thenumberofnodesinthetree. linesfollowseachcontainingtwo
integers and separatedbyasinglespacedenoting astheparentof .If is ,thenXistheroot
nodeofthetree.( isfornamesakeandisnotinthetree).
Thenextlinecontainsaninteger ,thenumberofqueries.
linesfolloweachcontainingaquery.
:
isaddedasanewleafnodewhoseparentis .
:Thistellsthatleafnode
isremovedfromthetree.
:Inthisqueryoutputthe
thparentof
.
isnotinthetreewhile isin.
isaleafinthetree.
isanodeinthetree.
Note
Eachnodeindexisanynumberbetween1and105i.e.,atreewithasinglenodecanhaveitsroot
indexedas105
OutputFormat
Foreachqueryoftype ,outputthe
doesn'texist,output .
Constraints
SampleInput
2
7
20
52
35
75
98
82
68
10
thparentof
.If
thparentdoesn'texist,output
andifthenode
0515
2152
13
01520
02013
2134
2133
2610
2111
291
1
100000
3
0100004
14
241
SampleOutput
2
2
5
0
0
8
0
Explanation
Thereare2testcases.Thefirsttestcasehas7nodeswith2asitsroot.Thereare10queries
0515->15isaddedasaleafnodeto5.
2152->2ndparentof15is15->5->2is2.
13->leafnode3isremovedfromthetree.
01520->20isaddedasaleafnodeto15.
02013->13isaddedasaleafnodeto20.
2134->4thparentof13is2.
2133->3rdparentof13is5.
2610->thereisno10thparentof6andhence0.
2111->11isnotanodeinthetree,hence0.
291->9'sparentis8.
thesecondtestcasehasatreewithonly1node(10000).
0100004->4isaddedasaleafnodeto10000.
14->4isremoved.
241->as4isalreadyremoved,answeris0.
Download