Ali Baba
Time limit1sMemory limit128 MB
Given starting tokens and trade rules over three token types, find the minimum number of trades to reach at least the required counts per type, or NIE if impossible.
- Level
Hard8 of 10
- Topics
- BFS, Graph, Shortest path, Implementation
- Solved
- No attempts yet
Problem
To open the cave of sesame, Ali Baba must be holding a set of tokens that contains at least gold tokens, silver tokens, and copper tokens. At the start he owns some number of tokens of each kind, and he may trade with the Guardian of the cave according to a fixed list of rules. Every rule has the form
meaning that Ali Baba may hand over gold, silver, and copper tokens and receive gold, silver, and copper tokens in return. Tokens gained in one trade may be spent in later trades.
For each test case, decide whether some finite sequence of trades lets Ali Baba end up holding at least the required number of tokens of every kind. If it does, report the smallest possible number of trades in such a sequence; otherwise report NIE (Polish for "no").
Input
The first line contains one positive integer (), the number of test cases. The test cases follow, each spanning several lines.
For every test case:
- the first line holds three non-negative integers , the numbers of gold, silver, and copper tokens Ali Baba owns at the start;
- the second line holds three integers , the numbers of gold, silver, and copper tokens needed to open the cave;
- the third line holds the number of rules ();
- each of the next lines holds six integers describing one rule .
Within every line the numbers are separated by single spaces.
Output
For each test case, print one line: either a single non-negative integer, the least number of trades Ali Baba must make in order to hold at least the required set of tokens, or the word NIE if no such sequence of trades exists.