How can I find the cheapest way in DAG if I have limited money?

So, if I have an acyclic graph with a direct acyclic graph, where the cost of each edge is 0 or more than 0, if it is more than 0, then it will have a negative weight (so you can do it for $ 5, and this will shorten your path at -20, for example).

I know that we can easily find the shortest / cheapest way in DAG, but what if we have limited money?

So imagine the following situation:

dag

We have 8 money. The algorithm will find the shortest path, which is -10 + -3 = -13, but it will cost 12, but we will only have 8 money, so this is not an option. The ideal path would be -10 + 0, which costs only 7 money. Is there an algorithm I can use to solve this problem?

+4
3

NP-Hard, -.

"":. - " ", " ", "" .

:

enter image description here

, "", , , "" .

:

weights=w1,w2,w3,...cn cost=c1,c2,..,cn, W, G=(V,E)

V= { V_i,U_i,W_i | i=0,...n }
E= { (W_i,V_i+1,U_i+1 | i=0,...,n-1} U {(V_i,W_i+1), (U_i,W_i+1) | i=0,...,n-1 }

value(W_i,V_i+1) = c_i+1
money(W_i,V_i+1) = w_i+1
value(W_i,U_i+1) = 0
money(W_i,U_i+1) = 0
money(V_i,W_i+1) = cost(V_i,W_i+1) = money(U_i,W_i+1) = cost(U_i,W_i+1) = 0

, W , W.


( Dynamic Programming):

D(start,0) = 0
D(v,x) = infinity     x < 0
D(v,x) = min { D(u,x-money(u,v)) + value(u,v) | for each edge (u,v) } U {infinity}

D(v,x) - , node v, x .

, , DAG, .

x 0 MAXIMAL_AMOUNT_OF_MONEY_ALLOWED, D(target,x), .
.

O(|V|*MAX_MONEY + |E|)

+5

. :
node .
, node .
> .
node.
node, .
, , . node.

0

, , , , .

- , , , . , , , . - , , , .

, ( , , , )...

// accepts the edge you are checking, max cost, and the sum weight and cost so far to this point
// returns float array {sum cost, sum weight), or infinity if cost is exceeded
void checkNextStep(Edge* edge, float maxCost, float* sumWeight, float* sumCost)
{
    if(*sumCost + edge->cost > maxCost)
    {
        *sumWeight = INFINITY;
        *sumCost += edge->cost;
    }
    *sumWeight += edge->weight;
    *sumCost += edge->cost;
}

, , , , .

If you end up with the shortest path with infinite mass, it means that you don’t have enough money to get to your node target in any way. Thus, you can use this as a check that you cannot get there with your money system.

0
source

All Articles