Author : Sarvesh0955
This problem can be solved in several ways; one approach is as follows:
Construct a new graph (nodes n+1 to 2n) where all edge weights are multiplied by k. Connect the two graphs such that for each edge u→v with weight w, add an edge u→v+n with weight w*k, or for every node u, add an edge u→u+n with weight 0.
Run the Bellman-Ford algorithm (modify to find max instead of min / or make edge weight negative and then use the standard Bellman-Ford algorithm ) to find the maximum score from node 1 to either n or 2n (since using the operation at most once also includes not using it).
Case for -1 will be when we detect a positive cycle, but will it be always wrong??
No, in case the positive cycle does not lie in the path from 1 to n/2n, we will not print -1, i.e., there exists a positive cycle but if we go in that path, we cannot reach n/2n. (test case 103)
I have used SPFA algo which is modification of Bellman-Ford algo, works in average O(n) worst O(n^2) and in cnt array if value > n it means it was part of the cycle
Author : Sarvesh0955




