How to solve this problem efficiently? Thanks in advance.
A complete weighted graph has N nodes. Source and End node is same (predefined). You can travel any node any times but not the source node. That means you can leave the source node just once. You want to maximise the sum of edge-weight. The sum of weight must not exceeds the pre given value M.
Determine the maximum sum and write the nodes sequentially.
Can you refer some similar problems so that i can examine the code/ algorithm.









"The sum of weight must not exceeds the pre given value M."
This is NP-hard by reduction from knapsack / subset sum. Think of a subset sum problem with numbers x1, ..., xn and you create n gadgets where to travel from vertex i to i+1 you either go through an edge of weight xi or an edge of weight 0. If the graph is undirected you can still enforce only traversing each edge once by setting a limit on the total number of edges you can travel (for example, each edge's weight is
10^67 + x, and the limit M is5 * 10^67 + desired weight). What is the constraint on M?dp[v][j + w[u][v]] ||= dp[u][j]. Obviously, there are $$$N*M$$$ states, and each state updates $$$N$$$ states, so the time complexity is $$$O(N^2*M)$$$. I'm not sure if there is a better way to do it; if there is, please let me know.I have a similar idea that is slightly faster if the number of edges is not too much (it probably is in most problems). You can turn it into a second graph with $$$V \cdot M$$$ vertices: "I am at vertex $$$v$$$ and have currently accumulated $$$M$$$ weight". If there were $$$E$$$ edges, there's now $$$E \cdot M$$$ of them. Simple graph traversal in $$$O(M(V + E))$$$ does the trick. Same runtime as yours if the graph is dense though.
This problem can be solved in polynomial time by Eppstein's algorithm.
A Leftist Heap gives the K shortest paths from start to end. Afterwards, it is simply a matter of continuously popping the path lengths from this heap (since it is least costliest at the root) until you reach the most expensive one under your budget.
See https://mirror.codeforces.com/blog/entry/102085 for additional details.
Note that the one modification you will have to make is blacklisting edges that go from anything --> source since you say we cannot go back to source.