Treasure hunters from all over the world have gathered in front of the Amazing Corridors of Mesopotamia. Everyone in the trade calls the ruin ACM.
Over the years many hunters walked into ACM and never came back. The newly elected leader keeps saying that the time has come to end that history and take revenge. The speech does not move you. You already know what project ACM Revenge is really after, and it is the treasure sleeping inside ACM.
Old Mesopotamian scripts give this much:
The hunters go in one at a time. A person who steps into a room that still has a working trap dies there, and that trap stops working. A person who steps into a room whose traps are all spent leaves through the free corridor, and the stone changes place at that moment. The scream of a dying hunter carries to the entrance, and the next hunter goes in.
You know the map, the number of traps left in every room, and which corridor is free right now. You want to be the first person to reach a treasure room. The m-th hunter to enter ACM is the one who reaches it first, and you need a program to compute m.
The input holds several test cases. The first line of each test case gives the number of rooms N in ACM (1≤N≤20000). The next N lines describe room 1 through room N in order. The i-th of those lines holds three integers pi, fi and ti (0≤pi≤N, 0≤fi≤1, 0≤ti≤100000).
pi is the number of the room at the other end of the corridor leading into room i, and pi=0 means room i is the entrance. fi is 1 when that corridor is free right now and 0 when the stone blocks it. ti is the number of working traps left in room i.
The entrance room always has fi=1, and every room with no outgoing corridor has ti=0. A room has either no outgoing corridor or exactly two of them. The last line of the input holds a single 0.
For each test case print m−1 on one line. That value is the number of people who die before the first hunter reaches a treasure room.