We need to determine if there exists a cycle reachable from the start item (item 1) that yields a positive total profit (sum of C along cycle). Also note that trades are like edges: if you have item i, you can exchange it for item j and also receive (or pay) C. Actually the description: trader will take i'th item from you and give you j'th item and C units of money. So if you give item i, you get item j plus C money. So C is added to your money. Negative C means you have to give C units of money (i.e., you lose money). So this is like a directed graph: from i to j with weight C. Starting with item 1 and some initial money? Presumably initial money is zero? Actually Monk starts with item 1, and we want to know if he can become infinitely rich, i.e., can increase money arbitrarily by repeating a profitable cycle. Money can be negative? But if there is a cycle that yields positive net money, then repeating it will increase total money without bound. So problem reduces to: In a directed graph with N nodes (items) and M edges (trades), each edge i -> j with weight C (money gained), is there a cycle reachable from node 1 that has a positive total weight? Also note that you can start at node 1, and you must be able to reach that cycle (and also come back to cycle?). Actually to repeat the cycle, you need to be able to traverse it repeatedly. That means you need a cycle that is reachable from start, and also you need to be able to return to the start of the cycle after each iteration? Usually, if you can reach a positive cycle from start, then you can increase money arbitrarily: go from start to cycle, then repeatedly loop the cycle. However, you must also consider that after completing the cycle, you end up at a node (the starting node of the cycle) and you can continue looping. So it's sufficient to have any positive cycle that is reachable from start. But careful: You start with item 1, not with any money. You might need to have enough money to pay negative C edges along the path to the cycle or within the cycle? In typical "arbitrage" problems, you look for a negative weight cycle in terms of exchange rates (logarithmic). But here money is additive and you can have negative edges. However, if you need to pay money, you could go into debt as long as eventually you can become infinitely rich? Typically in such problems (like Bellman-Ford detect positive cycles reachable from source), you assume you can have negative money as long as after repeating the cycle enough times you can offset any initial debt. But does the problem assume that you need to be able to follow the trades without having negative money? The statement: "if there are a series of profits, repeating which, will always increase the number of units of money with him!" It doesn't say you cannot have negative money during the process; it just says that by repeating a series of trades, you always increase total money. But if you need to initially go into debt to get into the cycle, but eventually you become infinitely rich, it's still possible? The phrase "if there are a series of profits, repeating which, will always increase the number of units of money with him!" suggests that there is a specific series of trades that, when repeated as a block, yields a net positive profit each time. Starting from his initial state (having item 1 and presumably 0 money). So we need to find a cycle (or more generally a sequence that starts and ends at the same item) that yields a positive net profit, and also that sequence is reachable from the start: we need to be able to get to the start node of the cycle (from item 1) and also after completing the cycle we are back at that node, so we can repeat. So it's exactly: Is there a positive-weight cycle in the directed graph that is reachable from node 1? The graph may have negative edges and cycles.
Constraints: N ≤ 100, M ≤ 1000, T up to 10. We can run Bellman-Ford from source node 1 to detect positive cycles? Actually Bellman-Ford typically detects negative cycles (by relaxing edges). To detect positive cycles, we could invert the signs or use Bellman-Ford for longest paths. Standard approach: We want to know if there exists a reachable positive cycle. We can consider distances as maximum money achievable after some trades? But the typical method: If after N-1 relaxations, we can still relax an edge, that indicates a negative cycle (for shortest path) or positive cycle for longest path. We can convert by negating weights and detecting negative cycles? But careful: We want to find any positive cycle reachable from source. That is equivalent to finding a negative cycle in graph with edges of weight -C (since sum(C) > 0 => sum(-C) < 0). But we also need that cycle is reachable from source. So we can run Bellman-Ford for shortest path on graph with weights w' = -C from source, detect if there is a negative cycle reachable from source. However, we must ensure that we can reach that cycle from source. In Bellman-Ford, if we initialize distances with INF except source=0, after N-1 relaxations, any further relaxation indicates a negative cycle that is reachable from source (since only reachable nodes can have finite distances). But careful: If the negative cycle is not reachable from source, distances to nodes in that cycle will remain INF, so they won't be relaxed. So Bellman-Ford with source node 1 will only detect negative cycles that are reachable from source (i.e., there exists a path from source to some node in the cycle). Actually the condition: If after N-1 relaxations, we can still relax any edge (i.e., we can reduce distance), then there is a negative cycle reachable from source. Because the relaxation propagates from source. But there's a nuance: It's possible to have a negative cycle that is not reachable but can be relaxed if some node in the cycle becomes reachable via other relaxations? No, if it's not reachable, distances remain INF, so no relaxation. So Bellman-Ford correctly identifies negative cycles reachable from source.
Thus we can solve: For each test case:
- Build graph edges: from i to j with weight C.
- Transform to w' = -C.
- Run Bellman-Ford from source node 1 to compute shortest distances (minimum) after N-1 relaxations.
- Then run one more iteration; if any edge (u->v) can be relaxed (i.e., dist[u] + w' < dist[v]), then there is a negative cycle reachable => positive cycle in original => print "Yes". Else "No".
But we need to consider if there are multiple edges? Yes, we include all M edges. The graph is directed? The description: "the trader will take i'th item from you and give you j'th item and C units of money." That implies you can give i and get j, so it's directed from i to j. So it's a directed graph. However, is it possible to use the trade in reverse? Not unless there is a trader for that. So directed.
Edge case: what about a self-loop (i=j)? If C > 0, then you can give item i and get the same item plus money, infinite profit. So that should be Yes if reachable (i=1 or can get to i). So our method will detect that as a positive cycle (or negative cycle in transformed graph). For a self-loop with weight C, transformed weight w' = -C. If C>0, then w' negative. Edge (i,i) with weight w' negative. In Bellman-Ford, after initial dist[i] maybe finite. Then check: dist[i] + w' < dist[i] -> if w' < 0, that is true (since dist[i] + (-C) < dist[i] if C>0). So it will detect negative cycle. So good.
But is there any nuance regarding the requirement that the cycle must be a cycle (returns to the same item) and yields positive total weight? Yes.
Potential pitfalls: Starting money is 0. If we have a positive cycle that requires some initial money to enter (like we need to pay money along the path to it), but you could still go into debt. The Bellman-Ford detection for negative cycles in the transformed graph doesn't care about initial debt; it simply determines existence of a cycle reachable from source that has negative total weight (positive in original). However, consider scenario: There is a positive cycle, but to get to it you need to traverse edges with negative weight (i.e., lose money), so the total money after reaching it could be negative. But after looping the cycle many times, you can become positive and then infinite. Is that allowed? Typically yes: you can have negative money intermediate; the problem statement doesn't forbid debt. So existence of a reachable positive cycle is sufficient.
But there is another nuance: The sequence that yields positive profit when repeated must start and end with the same item. But if you need to go from start to cycle, you could also incorporate the path into the cycle? However, repeating the series of profits must always increase money. That series could include the path to the cycle and the cycle, but after one iteration you end at some item, not necessarily the start of the series. To repeat, you need to be able to get back to the start state (item and money?) The problem says "if there are a series of profits, repeating which, will always increase the number of units of money with him!" The series is a sequence of trades. After performing this sequence, you might end up with a different item, but you could then repeat the same sequence? If the sequence ends with the same item as it started, then you can repeat. So it's essentially a cycle. However, you could also have a sequence that starts with item 1 and ends with item 1, yielding positive net money. That would be a cycle starting and ending at item 1. But you could also have a cycle that starts at some other item, and you first go from item 1 to that item (maybe losing money), then cycle many times, then eventually go back to item 1? But the condition is that you can become infinitely rich, not necessarily that you repeat the exact same series. You could start with item 1, then go to node X, then loop the positive cycle many times, and after many loops, you could have arbitrarily large money, even if you never return to item 1. The problem asks: "if there are a series of profits, repeating which, will always increase the number of units of money with him!" This suggests that the series itself can be repeated to increase money. To repeat it, you must be able to start each repetition in the same state (i.e., same item). So if the series starts with item A and ends with item A, then you can repeat it. So if there's a positive cycle reachable from start (i.e., you can get to A from start), you could do the sequence: go from 1 to A (maybe not part of the repeating series), then repeat the cycle. However, the "series" that is repeated might be the cycle itself. But then after completing one cycle, you are at A again, so you can repeat. So indeed, the existence of a positive cycle reachable from start is sufficient.
But consider: to get from 1 to A, you might need to spend money (negative net). Could that prevent the repetition? Because after you go to A, you have some money (maybe negative). Then you start repeating a positive cycle; each iteration adds a positive amount. After enough iterations, you will become positive. So it's okay.
Thus detection of reachable positive cycles is correct.
We could also solve using Floyd-Warshall to detect positive cycles? But Bellman-Ford is simpler.
Edge Cases: There might be multiple test cases, N up to 100, M up to 1000, T up to 10, so O(T * N * M) is fine.
Implementation details:
- For each test case, read N, M.
- Create edges list: for each edge (i, j, C), store (i-1, j-1, C) maybe zero-indexed.
- Transform weight: w = -C.
- Initialize dist array of size N with INF (like 1e18). Set dist[0] = 0.
- For relaxation: for i in 1..N-1: for each edge (u, v, C_orig): w = -C_orig; if dist[u] != INF and dist[u] + w < dist[v]: dist[v] = dist[u] + w.
- After N-1 iterations, run one more: for each edge: if dist[u] != INF and dist[u] + w < dist[v]: then there is a negative cycle reachable => positive cycle => Yes.
- Else No.
But careful: The detection of negative cycle in Bellman-Ford may also be triggered if there is a reachable negative cycle, but we need to ensure we only treat it as positive cycle in original. However, note: If the original has a positive cycle, then transformed has negative cycle. If original has a zero-weight cycle, not considered. If original has negative cycle, transformed has positive cycle, but that would not trigger a negative cycle detection. However, we don't care about negative cycles in original; we only care about positive cycles. So we detect negative cycles in transformed graph.
But wait: Could there be a case where original graph has a cycle with total weight > 0, but the transformed cycle weight is negative, so detection works. Conversely, if original has a cycle with total weight < 0, transformed weight positive, we don't detect, which is fine because that does not lead to infinite wealth.
Thus the algorithm is correct.
One nuance: The Bellman-Ford algorithm for detecting negative cycles works even if there are positive edges in transformed? We are just detecting negative cycles. The condition dist[u] + w < dist[v] after N-1 relaxations indicates that we can still find a shorter path; that implies a negative cycle reachable.
But we need to be careful about integer overflow. Use long long for distances, INF = 1e18.
Also, note that the graph may have edges that are not reachable from source. That's fine.
Now test with sample.
Sample 1:
N=5 M=6
Edges:
1->2 (2)
2->3 (-1)
3->4 (-7)
4->5 (0)
2->3 (-7)
3->5 (6)
Compute transformed:
1->2 (-2)
2->3 (1)
3->4 (7)
4->5 (0)
2->3 (7?) Wait careful: second 2->3 has C=-7, so w = -(-7)=7.
3->5 (6) -> w = -6.
Run Bellman-Ford from 1.
Let's manually see if there is a positive cycle reachable. Look at cycles:
Maybe 2->3->? 3->? There is 2->3 (C=-1 or -7). Both negative. So edges from 2 to 3 lose money. There's 3->5 (gain 6) and 5? From 5 there is no outgoing? Actually only edges: 4->5 (0). So no way to get back to 2 or 1. There's 3->4 (-7) loses. So overall cycles? Check 2->3->5->? No edge from 5 to anything else? Actually there is none, so no cycle. 3->4->5 no outgoing from 5. So no cycles reachable from 1. So answer No. Our detection should yield No.
Sample 2:
N=5 M=8
Edges:
1->5 (10)
2->3 (-6)
5->2 (5)
4->5 (9)
1->5 (1) (another trader)
2->4 (-10)
2->3 (-2)
4->1 (1)
Transform:
1->5 (-10)
2->3 (6)
5->2 (-5)
4->5 (-9)
1->5 (-1)
2->4 (10)
2->3 (2)
4->1 (-1)
Now, is there a positive cycle reachable? The example gives cycle: 1->5 (10), 5->2 (5), 2->4 (-10), 4->1 (1) yields total: 10+5-10+1=6 >0. That is reachable from 1 (it includes 1). So detection should find a negative cycle in transformed: sum of transformed weights = -10-5+10-1 = -6? Actually transformed weights: 1->5: -10, 5->2: -5, 2->4: 10, 4->1: -1 => sum = -6 (<0). So negative cycle reachable. So detection should say Yes.
Now implement.
Potential issues: The detection of negative cycles after N-1 iterations: In some implementations, they also check if any node's distance changes on the Nth iteration; but that indicates a negative cycle reachable from source only if that node is reachable. Since we only relax edges from nodes with dist[u] != INF, it's fine.
But there is a subtle point: The graph may have positive cycles that are reachable only via a path that includes a negative cycle? That doesn't matter; as long as there's a reachable positive cycle, detection should find it. However, consider a scenario where the positive cycle is not directly reachable because to get to it you must go through a negative cycle that could make the distance -infinity? Actually if there is a negative cycle reachable, that already indicates infinite wealth? No, negative cycle in original (i.e., losing money each time) would not yield infinite wealth, but negative cycle in transformed means positive cycle in original, so we would detect it. But what if there is a positive cycle in original, but to reach it you must go through a negative cycle in original? That might cause the distance to become -∞? But in transformed graph, that negative cycle becomes positive cycle? Let's think. Our detection uses transformed weights. If there is a negative cycle in original (i.e., lose money each loop), then transformed cycle sum >0, which is a positive cycle in transformed. That could also be detected as a negative cycle? Actually positive cycle in transformed would not cause relaxation after N-1 iterations because positive cycles increase distance (since we are minimizing). So they would not be flagged. So they don't interfere. So it's safe.
But we need to make sure we detect all positive cycles (original). Since we are converting each edge weight to negative, a positive total sum in original becomes negative in transformed. So any positive cycle in original becomes a negative cycle in transformed. So detection of negative cycle in transformed yields positive cycle in original. However, is it possible that a positive cycle in original is not reachable from source? In that case, we wouldn't detect it because distances to nodes on that cycle remain INF. So it's fine.
Thus algorithm stands.
Alternative approach: Run Bellman-Ford to find maximum money (like longest path) and detect positive cycles by checking if we can still increase distance after N-1 iterations. That would be directly with original weights. But typical Bellman-Ford is for shortest paths; we can adapt to longest by initializing distances to -INF, source to 0, and relax condition: if dist[u] + C > dist[v] then update. After N-1 iterations, if we can still increase, then there is a positive cycle reachable. That is simpler: we don't need to negate. But we need to be careful with negative infinity initialization. I'll choose the negating method because it's straightforward with standard Bellman-Ford.
But let's think about the longest path method: For each node, keep maximum money achievable after some trades starting from item 1 with that item in hand? Actually the state includes the item you hold. The graph nodes represent items you currently hold. So you traverse edges and add C to money. We want to know if we can have arbitrarily large money. So we want to detect a positive cycle reachable from source. This is exactly the detection of positive cycle in the graph. Bellman-Ford for longest path: initialize dist[source]=0, others = -INF. For i=1..N-1: for each edge (u,v,C): if dist[u] != -INF and dist[u] + C > dist[v] then relax. After N-1 iterations, if any edge can still be relaxed (i.e., we can increase dist[v]), that indicates a positive cycle reachable. This is analogous to negative cycle detection for shortest path but with >. So we can directly do that without negation. But careful: In longest path detection, we need to ensure that we can propagate -INF? Actually the relaxation condition should also account for unreachable nodes; dist[u] = -INF means we cannot use that edge. So we can implement.
I think the negation approach is easier as we can use standard shortest path detection with <.
But note: If we negate weights, then edges with -C could be positive, negative, zero. Since we are minimizing, we initialize distances to INF, source 0. Then we relax if dist[u] + w < dist[v]. After N-1 iterations, we check if any edge can still relax. That works.
I'll go with negation.
Now, we should consider constraints: T up to 10, N up to 100, M up to 1000. So O(TNM) = 101001000=1e6, fine.
Implementation plan:
- Read integer T.
- Loop test cases:
- Read N, M.
- Create vector edges of tuple (u, v, C). Use 0-indexing.
- For each edge: read i, j, C; store (i-1, j-1, C).
- Set dist array of size N, fill with LLONG_MAX/2 (like 1e18). dist[0] = 0.
- For k = 1 to N-1:
for each edge (u,v,C):
if dist[u] != INF:
long long newDist = dist[u] - C; // because w = -C
if newDist < dist[v]: dist[v] = newDist;
- After N-1 iterations, set a flag = false.
- For each edge (u,v,C):
if dist[u] != INF:
if dist[u] - C < dist[v]: flag = true; break;
- If flag, print "Yes" else "No".
Potential pitfall: The distances may become very negative due to negative cycles; but we are using long long and our INF is large, so safe.
But note: In the relaxation, we need to ensure that we don't cause overflow if we add negative to INF. We only compute if dist[u] != INF, so safe.
Now, check sample. Should work.
One more nuance: The graph might have multiple edges between same nodes. That's fine.
Now, I think this is correct. But let's examine any scenario where a positive cycle is reachable only if you have some initial money to pay for negative edges along the path? In our model, we start with 0 money. If the path from 1 to the cycle has negative total weight (i.e., you lose money), then dist[cycle node] after Bellman-Ford will be some negative value (in transformed, it'll be positive? Let's think: In original, going from 1 to node A might have net money change D (could be negative). In transformed, we are minimizing, so dist[A] = -D (since we negate weights). Actually if original path sum = S, then transformed sum = -S. So if S is negative, -S is positive, dist[A] will be positive. That's fine. However, detection of negative cycles in transformed does not depend on the distance to the cycle start being finite; it just requires that there is some node in the cycle that can be relaxed, which will happen if the cycle sum is negative. So it should detect.
But consider a case: The positive cycle exists, but to enter it you need to have a certain amount of money to pay a negative edge? Actually in the graph model, edges are unconditional trades: if you have item i, you can always trade to get item j and receive C (which could be negative, meaning you have to pay). But the trade presumably requires that you have enough money to pay if C is negative? The problem doesn't state any constraints on having enough money; it says "the trader will take i'th item from you and give you j'th item and C units of money. A negative value of C signifies that, in order to get j'th item from the trader, you will have to give i'th item and C units of money." So it implies that you need to pay C units. So if you don't have enough money, you cannot perform that trade. This is crucial: The trades might require you to have sufficient money to pay the negative C. Therefore, the existence of a positive cycle reachable from start does not guarantee that you can actually traverse it if you need to have initial capital to cover negative payments along the way or within the cycle. However, the typical problems of "arbitrage" or "becoming infinitely rich" assume you can start with zero money and if there is a positive cycle, you can exploit it because you can first accumulate some money? But in arbitrage, you need to have some money to invest, but here you are exchanging items and receiving or paying money. Starting with item 1 and zero money. If there is a positive cycle, can you always eventually perform it? Not necessarily. Suppose the positive cycle includes a negative edge that requires you to pay a large amount of money. To go around the cycle, you might need to have enough money to pay that negative amount. If you start with zero, you might not be able to pay. However, if the net sum of the cycle is positive, you could possibly go around it after building up some capital? But if you can't start the cycle because you can't afford the first negative edge, maybe you could use a different sequence to build capital first? The positive cycle itself may have internal negative edges, but its net is positive. But to start the cycle, you need to be at the start node of the cycle and have enough money to pay any negative edges as you traverse the cycle. However, since the net is positive, if you could complete the cycle once, you'd end with more money than you started. But if you start with insufficient money to pay the negative edges, you might not be able to even complete the first loop. But maybe you could use some other trades to accumulate enough money to then start the cycle? The question asks: "if there are a series of profits, repeating which, will always increase the number of units of money with him!" That series, when repeated, must be feasible from the starting state (item 1 and 0 money) each time? Actually the phrase "repeating which" suggests that you can repeat the same series of trades over and over, and each repetition increases your money. It does not necessarily say that you must start with the same item each time; you could be in a different state after each repetition, but the series is defined as a sequence of trades. So if you have a positive cycle that starts and ends with item A, you need to get to item A first. That might require some trades that may lose money. But once you are at A, you might have some amount of money M (maybe negative). To traverse the cycle, you need to be able to pay negative edges; if M is not enough to cover the most negative cumulative requirement along the cycle, you might not be able to complete it. However, if the net of the cycle is positive, you could potentially do the cycle many times and increase your money, but you need to survive the first iteration. If you start with M insufficient, you might be unable to pay a negative edge. So we need to consider feasibility with respect to money balance.
This is reminiscent of the problem of detecting if there's a "positive cycle" in a weighted graph with the ability to have negative cash flows but requiring that your balance never goes negative? Actually typical problems about making infinite money assume that you can go into debt, or there's no constraint on money. The problem statement doesn't explicitly say that you need to have non-negative money. It says: "if there are a series of profits, repeating which, will always increase the number of units of money with him!" It doesn't say you can't have negative money during the process. It might be implicit that you can have negative money (debt) because they talk about negative C meaning you have to give money. But if you have no money, can you give? In real life, you can't give money you don't have. But in these algorithmic puzzles, often they ignore the cash constraint and just consider net profit. I need to examine the problem statement more carefully.
Look at the sample explanation: For the second test case, the cycle they show: 1->5 gain 10, 5->2 gain 5, 2->4 lose 10, 4->1 gain 1. Starting with item 1 and presumably 0 money. Let's simulate:
- Start: item 1, money = 0.
- Trade 1: give item1, get item5, gain 10 -> money = 10, item5.
- Trade 2: give item5, get item2, gain 5 -> money = 15, item2.
- Trade 3: give item2, get item4, lose 10 -> requires paying 10, so money becomes 5, item4.
- Trade 4: give item4, get item1, gain 1 -> money becomes 6, item1.
So net +6, and all trades feasible because at trade 3 we had money 15 >= 10, so ok. So no issue. Could there be a case where the cycle net positive but requires a negative payment that you can't afford initially? For instance, a cycle: A->B: +1, B->C: -100, C->A: +101. Net +2. Starting at A with 0 money: after first trade, money=1, item B; second trade requires paying 100, but you have only 1, so you can't. So the cycle is not feasible from zero cash. However, you could perhaps take out a loan? The problem doesn't allow borrowing; you must have money to pay. So is such a cycle considered a valid way to become infinitely rich? The series of trades, if repeated, would not be feasible because you can't perform the second trade. But could you use a different sequence to build up enough money first? For instance, maybe there is a path to get to A with enough money, then you can do the cycle. Since you start with item 1, you could accumulate money via other trades before entering the cycle. So even if the cycle itself is not immediately feasible from zero cash at A, it might be feasible after you have enough cash. And if there is any way to become infinitely rich, we should output Yes. So the question reduces to: Is there a cycle (reachable from start) with positive total weight such that the cycle is "executable" given that we can accumulate money before entering it? In other words, if there exists a reachable positive cycle, can we always eventually execute it? Possibly not if the cycle has a negative edge that requires more money than we can ever accumulate before entering the cycle. But since the cycle is positive, you could potentially loop it many times to increase money; but to start it you need to have a minimum cash balance to survive the troughs. This is similar to the concept of "minimum initial capital" to be able to traverse a cycle. However, if the cycle is reachable, you could get to its start node with some money (maybe negative? but you can't go negative). So you need to find if there is a reachable cycle such that there exists a path from start to the cycle (with some net money gain) that gives you enough cash to then perform the cycle. Since you can also repeat other trades before attempting the cycle, you could potentially increase your cash arbitrarily by other means? But if the only way to increase cash is through that cycle, you may be stuck. But if the cycle itself is positive, but you can't afford it initially, maybe you can use a prefix of the cycle to get some money? Actually you need to traverse the entire cycle to complete it. If the cycle has a negative edge that requires more money than you have at that point, you cannot traverse it. However, if you can first do some other trades to increase your cash, then you might be able to afford it. But those other trades themselves might require cash. So this becomes a more complex feasibility problem.
Let's examine typical solutions to similar problems on CodeChef or other platforms. I recall a problem "Monk and the Islands" but not this. The problem might be from CodeChef "Monk and the Magical Candy Bags"? No. This problem resembles the "arbitrage" problem but with items instead of currencies. Usually, in arbitrage problems (like with currencies), you look for a cycle where the product of exchange rates > 1, and you can start with one unit of a currency and become infinitely rich, but there is no cash constraint because you are exchanging currencies, not money. Here, there is an additional "money" that is additive. The trades are like: give item i, get item j and C money. So you always have an item and some money. The money can be negative? It might be allowed to be negative? In financial terms, you could have debt. But is it allowed? The problem statement doesn't explicitly forbid negative money. They talk about "number of units of money with him", and negative C means you have to give money. If you have no money, can you give? It would imply you cannot perform that trade if you lack the money, unless borrowing is allowed. Usually in such algorithmic problems, they don't consider the cash constraint; they assume you can have negative money (or unlimited credit). The goal is to detect if there is a positive cycle reachable, because then you can generate infinite money by repeating it (even if you go into debt initially, after many cycles you'll become positive and then infinite). But the example doesn't test negative money scenario.
We need to decide based on typical contest problems. I've seen a problem on CodeChef: "Monk and the Island" is BFS. There's also "Monk and the Graph" etc. This problem might be from HackerEarth? The formatting resembles HackerEarth. I recall a problem "Monk and his Friends" but not this. However, there is a known problem: "Monk and the Magical Candy Bags" is about heaps. This problem seems to be about detecting positive cycles in a directed graph. I've seen a similar problem on SPOJ: "Arbitrage" which asks to detect if there is a sequence of currency exchanges that yields profit. That problem uses logarithms to convert to negative cycles. But there, you start with some amount of a currency and exchange; you don't have a separate money; profit is in the same currency. So that's similar but here we have money as separate.
Actually, consider an equivalent: You have items and money. Each trade changes your state from (item, money) to (new item, money + C). So if we ignore the money amount, the question reduces to: Is there a reachable cycle with total C > 0? Because if such a cycle exists, then starting with any amount of money (including 0), you can go around the cycle as many times as you like, each time increasing money by sum(C). But is it always possible to go around the cycle if sum(C) > 0, regardless of intermediate cash balances? Not necessarily, because if the cycle includes a negative edge that is large in magnitude, you might not have enough cash to cover it on the first iteration. However, if you can go into debt (i.e., negative money is allowed), then you can still do it. If negative money is not allowed, you might need to ensure that the minimum cash balance along the cycle (starting from 0 at the start node) is non-negative. But you could also start with a larger cash by doing some other trades before. Since there might be other trades that can increase cash without requiring a large outlay, you might be able to accumulate enough to afford the negative edge. But if the only way to increase cash is through the cycle itself, you might be stuck.
The problem statement: "if there are a series of profits, repeating which, will always increase the number of units of money with him!" It doesn't mention any constraint on having to have non-negative money. In many graph theory problems involving money and trades, they assume you can have negative money, or they just consider net profit. I suspect the intended solution is simply to detect a positive cycle reachable from node 1. Because that is the classic "arbitrage" detection but with additive profit.
Let's look at constraints: N ≤ 100, M ≤ 1000, C can be negative. The problem expects a solution using Bellman-Ford. That's classic for detecting cycles in weighted graphs. So likely the intended approach is as I described.
But to be absolutely sure, consider if there could be a scenario where a positive cycle exists but you cannot use it because you cannot afford the negative edges, yet the answer might still be Yes? Or maybe the problem expects No? The sample doesn't cover that. Let's think of a small example: N=2, M=2. Start with item 1.
Edges: 1->2: C = -5 (you give item1 and pay 5 to get item2)
2->1: C = 7 (you give item2 and get 7 to get item1)
Cycle 1->2->1 sum = 2 > 0. Is it possible to become infinitely rich? Starting with item1, money 0. To do 1->2, you need to pay 5, but you have 0. So you cannot perform that trade. So you cannot even start the cycle. But could you do something else? No other edges. So you cannot make any trade. So answer should be No. However, if we simply detect a reachable positive cycle, we would say Yes because there is a cycle from 1 to 2 to 1 with total +2, and both nodes are reachable from 1 (1 is start, 2 is reachable via the edge but you can't actually traverse it because you need money). But wait, is node 2 reachable? In graph terms, reachable means there exists a path. But the path 1->2 exists. However, the edge 1->2 has C=-5, requiring 5 money to perform. If you have 0 money, you cannot perform it. So the state (item 1, money=0) cannot transition to item 2 because you lack the money to pay. So the graph model with only items as nodes and edges representing trades is not sufficient if we also have a money constraint. The ability to traverse an edge depends on current money. So the existence of a positive cycle in the item graph does not guarantee that you can actually traverse it starting from 0 money. This nuance is critical.
Thus the problem is more complex: we need to consider the state as (item, money). Since money can be unbounded, we need to determine if there is a strategy to make money arbitrarily large. This is essentially a decision problem: can we achieve arbitrarily high money starting from (item 1, money 0) using the trades, with the constraint that at each trade, if C is negative, we must have at least -C money to pay? This is similar to the "minimum cost to reach a node" but with profit. Actually it's like we have a directed graph where each edge (i->j) with weight C can be taken if we have enough money to cover negative C? But we can always accumulate money; the question is whether we can get infinite money. This is reminiscent of "systems of difference constraints" or "detecting positive cycles in a graph with a resource constraint". However, typical algorithmic contests problems about "becoming infinitely rich" with trades and items often ignore the cash constraint and assume that you can go into debt, or they treat the money as just a balance that can be negative. I need to examine the exact wording: "the trader will take i'th item from you and give you j'th item and C units of money. A negative value of C signifies that, in order to get j'th item from the trader, you will have to give i'th item and C units of money." It doesn't say you need to have the money; it just says you have to give C units. In real life, you can't give what you don't have, but in many algorithmic problems, they allow negative balances as long as you can later offset. Usually they don't consider such constraints unless explicitly stated. Also note that in the sample explanation, they didn't need to worry about negative balances because the cycle didn't have a large negative relative to current money. So it's ambiguous.
Let's search memory: I recall a HackerEarth problem named "Monk and the Magical Candy Bags"? Not that. Actually I recall a problem on HackerEarth: "Monk in the real estate" but no. There's a known CodeChef problem "Monk and the Islands" about BFS. There's also "Monk and the Graph" about articulation points. I'm not sure.
Maybe the problem is from HackerEarth's "Monk and his Friends"? Not.
Alternatively, perhaps the intended solution is indeed to detect positive cycles reachable from node 1, ignoring cash constraints. Because the problem constraints are small and the solution is simple Bellman-Ford. The mention of negative C and the requirement to give money might be just to define the direction of money flow; they probably assume you can have negative money (debt) and can always perform trades regardless of current money. In many graph theory problems with money, they don't enforce non-negative cash; they just treat it as a number that can go negative. The question "if there is a way by which he can become infinity rich if he acts smart!" essentially asks if there's a cycle with net positive profit reachable from start, because if you can go around it many times, you'll get arbitrarily large money, even if you go negative in the process. So the cash constraint is not considered.
But let's test with the counterexample I gave: N=2, M=2, edges: 1 2 -5; 2 1 7. Starting with item 1, money=0. According to the description, can he become infinitely rich? If he can go into debt, then he could do: trade 1->2: give item1 and pay 5. But if he has 0 money, can he pay 5? If debt allowed, he can have -5 money after trade. Then he has item2, money -5. Then trade 2->1: give item2, get item1 and 7 money, so money becomes 2. So net +2, and he's back to item1 with money 2. Now he can repeat: each cycle adds 2. So starting from 0, after first cycle he has 2; after second cycle, 4; etc. But wait, in the first trade, he needed to pay 5. If he has 0, can he pay 5? In many financial contexts, you cannot pay if you don't have money, unless you borrow. The problem does not mention borrowing, but it might allow negative money implicitly because it's just a number. The example would yield Yes if negative money allowed. If the problem intended to disallow negative money, they would have mentioned a constraint like "Monk cannot have negative money" or "he must have enough money to give". Since they didn't, likely negative money is allowed.
Let's look at the sample: they have a trade with negative C (2->4 -10) but they had enough money because they gained from previous trades. But they didn't test the case where you can't afford. Usually in such problems, they don't impose a non-negative constraint.
Consider also the possibility of multiple edges: they might include a dealer that trades the same item i=j with positive C. That would be a self-loop giving money each time. That is obviously positive cycle and you can do it infinitely, provided you have the item. You don't need money to do it if C>0, because you give the item and get same item plus money. So you can always do that regardless of money. So such edges would be detected as positive cycles.
Thus I think the intended solution is simply to detect a positive cycle reachable from node 1.
But let's double-check with some known CodeChef problem: There is a problem "Monk and his Friend" but not. Actually I recall a problem "Monk and the Islands" from CodeChef. I'll try to search memory: The problem "Monk visits Biksy" maybe from HackerEarth? I think I've seen it: It's from HackerEarth's Monk and the Islands? Not sure. However, the typical solution for "Monk and the Islands" is BFS. The name "Biksy" appears in HackerEarth problem "Monk in the land of Apu" maybe.
I can attempt to search my mental database: There is a HackerEarth problem "Monk in the real estate" no.
Given the structure: "Monk visits Biksy, the largest trading market in the land." This seems like a story used in HackerEarth's "Monk and the Islands"? Actually HackerEarth has a series of "Monk and ..." problems. I've seen "Monk and the Islands" (graph BFS), "Monk and the Magical Candy Bags" (heap), "Monk and his Friends" (set), "Monk and the Graph" (articulation points). I don't recall "Monk visits Biksy". It could be from CodeChef's "Monk and the Graph"? Not.
Nevertheless, the simple solution is likely correct.
Let's verify with some more scenarios.
If there is a positive cycle that is not reachable from node 1, answer should be No. That's handled.
If there is a zero-weight cycle, no infinite wealth.
If there is a positive cycle but you need to go through negative edges to reach it, that's okay because we can go into debt and then later profit.
Thus algorithm: detect positive cycle reachable from node 1 using Bellman-Ford (or SPFA) with original weights relaxing for maximum.
Better to use the longest path detection: Use Bellman-Ford for longest path, initialize dist to -INF, dist[1]=0. For i=1 to N-1: for each edge (u,v,w): if dist[u] != -INF and dist[u] + w > dist[v] then update. After N-1, if any edge can still improve (dist[u] + w > dist[v]), then there's a positive cycle reachable. This is analogous to detecting negative cycles for shortest path.
But careful: For longest path, if there is a positive cycle, the distance can be increased arbitrarily, so after N-1 relaxations we can still improve. That's the detection.
Using this method directly avoids negation. I'll adopt this.
We need to be careful with -INF: use a very small number, like -1e18.
We'll represent edges as from i-1 to j-1 with weight C.
Pseudo:
for each test:
read N, M
edges = []
for _ in range(M):
i, j, C = map(int, input().split())
edges.append((i-1, j-1, C))
INF = 10**18
dist = [-INF] * N
dist[0] = 0
for _ in range(N-1):
updated = False
for u, v, w in edges:
if dist[u] != -INF and dist[u] + w > dist[v]:
dist[v] = dist[u] + w
updated = True
if not updated: break
# Check for positive cycle
has_positive_cycle = False
for u, v, w in edges:
if dist[u] != -INF and dist[u] + w > dist[v]:
has_positive_cycle = True
break
print("Yes" if has_positive_cycle else "No")
This should work.
But there is a nuance: If there is a positive cycle reachable, but the cycle is not reachable because the path to it includes a positive cycle? Actually if there is a positive cycle, the distances to nodes in that cycle will keep increasing, so after N-1 relaxations we will still be able to improve. So detection works.
Now, what about the case where there is a positive cycle but you cannot reach it because all paths to it require going through nodes that are unreachable? Unreachable nodes have dist = -INF, so they won't be relaxed. So detection won't happen.
Thus solution stands.
Now, confirm with the sample:
Sample 1:
N=5 M=6 edges as above.
Run Bellman-Ford for longest path.
Initialize dist[0]=0, others -INF.
Iteration 1:
- 1->2 (2): dist[0]=0 -> dist[1] becomes 2.
- 2->3 (-1): dist[1]=2 -> dist[2] becomes 1.
- 3->4 (-7): dist[2]=1 -> dist[3] becomes -6.
- 4->5 (0): dist[3]=-6 -> dist[4] becomes -6.
- 2->3 (-7): dist[1]=2 -> 2+(-7)=-5 >? dist[2] currently 1 -> no.
- 3->5 (6): dist[2]=1 -> 1+6=7 > dist[4]? dist[4] is -6, so update to 7.
After iteration 1, dist: [0,2,1, -6? Actually dist[3] from 3->4? Wait, we have edges: 3->4 (-7) from node index 2->3? Node indexing: 0:1,1:2,2:3,3:4,4:5. So after updates:
dist[0]=0
dist[1]=2 (from edge 0->1)
dist[2]=1 (from 1->2 with -1) also from 1->2 with -7? that gave -5, not >1.
dist[3] from 2->3 (edge 3->4) weight -7: dist[2]=1 -> -6; so dist[3] = -6
dist[4] from 3->4 (edge 4->5) weight 0: dist[3] = -6 -> -6; also from 2->4 (edge 3->5) weight 6: dist[2]=1 -> 7; so dist[4] = 7.
Iteration 2:
- 0->1: 0+2=2 not >2
- 1->2 (-1): 2+(-1)=1 not >1
- 2->3 (-7): 1+(-7)=-6 not >-6
- 3->4 (0): -6+0=-6 not >7
- 1->2 (-7): 2+(-7)=-5 not >1
- 2->4 (6): 1+6=7 not >7
No updates. So after N-1=4 iterations? Actually N=5, so 4 iterations total. We did 2 and found no updates, break early. Then check for positive cycle: none. So No.
Sample 2:
Edges as above.
Let's run quickly:
N=5, M=8.
Edges list (converted to 0-index):
0->4 (10)
1->2 (-6)
4->1 (5)
3->4 (9)
0->4 (1)
1->3 (-10)
1->2 (-2)
3->0 (1)
dist[0]=0 others -INF.
Iteration1:
- 0->4 (10): dist[4] = 10
- 1->2 (-6): dist[1] = -INF skip
- 4->1 (5): dist[4]=10 -> dist[1] = 15
- 3->4 (9): dist[3]= -INF skip
- 0->4 (1): 0+1=1 <10 so no
- 1->3 (-10): dist[1]=15 -> dist[3]=5
- 1->2 (-2): dist[1]=15 -> dist[2]=13
- 3->0 (1): dist[3]=5 -> dist[0]=6 (since 5+1=6 >0) update dist[0] to 6
Now after iteration1, distances: dist[0]=6, dist[1]=15, dist[2]=13, dist[3]=5, dist[4]=10.
Iteration2:
Check edges:
0->4 (10): 6+10=16 >10 -> update dist[4]=16
1->2 (-6): 15-6=9 <13 no
4->1 (5): 16+5=21 >15 -> dist[1]=21
3->4 (9): 5+9=14 <16? Actually 14<16 no
0->4 (1): 6+1=7 <16 no
1->3 (-10): 21-10=11 >5 -> dist[3]=11
1->2 (-2): 21-2=19 >13 -> dist[2]=19
3->0 (1): 11+1=12 >6 -> dist[0]=12
Now distances: [12,21,19,11,16]
Iteration3:
0->4 (10): 12+10=22 >16 -> dist[4]=22
1->2 (-6): 21-6=15 <19 no
4->1 (5): 22+5=27 >21 -> dist[1]=27
3->4 (9): 11+9=20 <22 no
0->4 (1): 12+1=13 <22 no
1->3 (-10): 27-10=17 >11 -> dist[3]=17
1->2 (-2): 27-2=25 >19 -> dist[2]=25
3->0 (1): 17+1=18 >12 -> dist[0]=18
Distances: [18,27,25,17,22]
Iteration4 (N-1=4):
0->4 (10): 18+10=28 >22 -> dist[4]=28
1->2 (-6): 27-6=21 <25 no
4->1 (5): 28+5=33 >27 -> dist[1]=33
3->4 (9): 17+9=26 <28 no
0->4 (1): 18+1=19 <28 no
1->3 (-10): 33-10=23 >17 -> dist[3]=23
1->2 (-2): 33-2=31 >25 -> dist[2]=31
3->0 (1): 23+1=24 >18 -> dist[0]=24
After 4 iterations, distances: [24,33,31,23,28]
Now we check for positive cycle: run one more relaxation:
0->4 (10): 24+10=34 >28 -> would update, so yes positive cycle detected. So output Yes. Good.
Thus algorithm works for sample.
Now, about the earlier counterexample with 1->2 (-5) and 2->1 (7). Let's test: N=2, M=2 edges: 0->1 (-5), 1->0 (7). Dist[0]=0.
Iteration1:
0->1: 0-5=-5 -> dist[1] = -5
1->0: -5+7=2 -> dist[0]=2
Iteration2 (since N-1=1? N=2 so only 1 iteration? Actually N-1=1, so we do exactly one relaxation pass. After that we check for positive cycle: After the first iteration, we have dist[0]=2, dist[1]=-5. Then we do an extra check: for each edge:
0->1: 2-5=-3 > -5? Actually check: dist[0]+w = 2 + (-5) = -3, which is greater than dist[1] (-5). Since we are checking for longest path, if dist[u] + w > dist[v], then there is a positive cycle. Here -3 > -5, so it would indicate positive cycle. So algorithm would output Yes. So it says yes. That matches if negative money is allowed. If the problem intended that you can't go negative, answer should be No. Which is correct? We need to check the problem statement for any indication.
Look at the problem statement again: "Monk visits Biksy having the item number 1. He collects the data of all the traders and wants to know if there is way by which he can become infinity rich if he acts smart! i.e. if there are a series of profits, repeating which, will always increase the number of units of money with him! Note that Monk can go to any dealer any number of times."
The phrase "series of profits" might imply that each individual trade could be a loss? Actually profit could be negative? They say "series of profits" but then they define "C units of money. A negative value of C signifies that, in order to get j'th item from the trader, you will have to give i'th item and C units of money." So trades can be profit or loss. A "series of profits" might be a sequence where the net is profit. They don't talk about needing to have enough money to give. Typically in such problems (like detecting positive cycles in a weighted directed graph), we ignore the cash flow constraint and just check for positive cycles reachable from source. Because if you can repeat a cycle with positive net, you can become infinitely rich regardless of intermediate negative balances, as you can go into debt and then later become positive. In many graph theory problems, they allow negative balances as long as the net cycle is positive. For example, the classic "arbitrage" problem is about currency exchange, where you start with some amount and multiply, but there is no constraint on having non-negative amount because you can always exchange as long as you have the currency, and the amount can be arbitrarily small? Actually in arbitrage, you need a positive amount to exchange, but you can't have negative amounts. However, the detection of positive cycles (in multiplicative sense) doesn't consider that you need enough of the currency; you assume you can start with 1 unit and repeatedly apply exchanges, and as long as the product > 1, you can get arbitrarily large. But here, if you need to pay money, that's like you need to have enough cash. In the classic problem of "making money" with additive profits, I've seen problems where they explicitly say that you can have negative money (like you can borrow). But this problem doesn't mention borrowing.
Let's see if any official editorial exists. Since I can't search now, I'll reason about typical contest problem expectations. The constraints are small (N=100, M=1000)