ACM Revenge

No attempts yetTime limit1sMemory limit128 MB

Problem

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:

  1. ACM is a collection of rooms joined by one-way corridors. Nobody can walk a corridor backwards.
  2. One room is the entrance and it opens to the outside world. Every room in ACM is reached from the entrance by exactly one path.
  3. A room with no outgoing corridor is packed with treasure. The moment somebody reaches such a room, that person and everything inside are teleported out of ACM, landing somewhere near the entrance.
  4. Every other room has exactly two outgoing corridors, and a huge stone blocks one of them at any moment. When somebody steps into the free corridor, the stone slides over to block that corridor and frees the other one. Such a room also holds a few traps. One trap kills one person and then stops working, so the same trap never kills twice.

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 mm-th hunter to enter ACM is the one who reaches it first, and you need a program to compute mm.

Input

The input holds several test cases. The first line of each test case gives the number of rooms NN in ACM (1N200001 \le N \le 20000). The next NN lines describe room 11 through room NN in order. The ii-th of those lines holds three integers pip_i, fif_i and tit_i (0piN0 \le p_i \le N, 0fi10 \le f_i \le 1, 0ti1000000 \le t_i \le 100000).

pip_i is the number of the room at the other end of the corridor leading into room ii, and pi=0p_i = 0 means room ii is the entrance. fif_i is 11 when that corridor is free right now and 00 when the stone blocks it. tit_i is the number of working traps left in room ii.

The entrance room always has fi=1f_i = 1, and every room with no outgoing corridor has ti=0t_i = 0. A room has either no outgoing corridor or exactly two of them. The last line of the input holds a single 00.

Output

For each test case print m1m - 1 on one line. That value is the number of people who die before the first hunter reaches a treasure room.