Co-workers from Hell
Time limit1sMemory limit128 MB
Place tricks in chambers so the watchman's walk, where each trick is used once to change dwell time and jump target, maximizes total time before he normally finishes chamber n.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Graph, DFS, Implementation
- Solved
- No attempts yet
Statement
Every night a watchman inspects the chambers of a factory in a fixed order. He starts at chamber and, after inspecting the final chamber , leaves the factory and goes home. In a normal inspection he stays in chamber for units of time and then moves on to chamber .
A mischievous co-worker who has seen the schedule wants to keep the watchman at work as long as possible. Before the watchman arrives, the co-worker may place a trick in any subset of the chambers. When the watchman inspects a chamber that holds a trick, he is fooled: he stays there units of time instead of , and afterwards moves to chamber (which may be any chamber) instead of chamber .
A trick works only the first time the watchman enters that chamber; on every later visit to it he behaves normally (stays and moves to chamber ). A trick may send him backward, so he can pass through some chambers several times, or forward, so he may skip some chambers entirely. For instance, with five chambers inspected in order, if the only trick is placed in chamber and points to chamber , the watchman walks 1 → 2 → 4 → 5 and then goes home, never checking chamber .
The watchman goes home only when he performs a normal inspection of the final chamber . Determine the maximum total time the co-worker can force the watchman to stay in the factory.
Input
The first line contains the number of test cases .
Each test case starts with a line containing an integer (0 ≤ ≤ 100), the number of chambers. The next lines describe the chambers in order; the -th line contains three integers , , and (1 ≤ ≤ ): the normal inspection time in chamber , the inspection time when chamber is tricked, and the chamber the watchman moves to when chamber is tricked. Chamber is always the first chamber and chamber is always the final one.
Output
For each test case, print a single line with one integer: the maximum total time the watchman can be forced to remain in the factory before he leaves the final chamber by a normal inspection.