Minimum cost path for N*N matrix in ϴ(N^2) time - algorithm

I am provided with an N*N matrix of towns, and each town has a respective widget price (a weight).
I am tasked with finding the cheapest cost to acquire a widget for every town, using the following equation:
Cost for target town : (Target Town Cost) + (Rectilinear distance away from base town)
Cheapest Total Cost for base town = min(costs calculated for all target towns)
The simple solution is ϴ(N4), where we go through all N2 base towns, and calculate the cost for all N2 targets and the answer is the minimum.
I need to find a solution in ϴ(N2). I know there is a dynamic programming solution but we have not covered that yet so I am trying to find an alternative.
Solutions I have tried so far:
Calculating the cost for middle row and column, then recursively calculating the costs for the middle row and column for every sub-grid. This would however be ϴ(log(N2)N2), since calculating the mininum for the initial row and column would be ϴ((number of base towns) * (checking all target towns)) = ϴ(log(N2)N2)
Creating a min-heap based on the smallest town, but this would still take ϴ(N2log(N)) due to building the heap.
The current attempt I am trying seems to be leading me in the right direction. We can start out by
Finding the minimum cost town of the whole grid, and we know it is its own minimum cost town. That will take N2
Take the surrounding towns. Their minimum cost will either be themselves, or the global minimum.
We recurs onto the surrounding towns again, and here I don't know what to do. I am looking for a property of the already calculated towns that I could take advantage of in order to calculate each current surrounding town in constant time.
Is there something to this or should I consider some other method?
Thank you.

Related

Shortest path with time constraint

Few cities (<=50) are given along with two (N * N) matrices denoting travel time between cities and toll between cities. Now given a time t (<10000), we have to choose a path to reach from city 0 to city N-1 such that toll cost is minimum and we complete travel within given time t.
I am thinking of using A star algorithm to solve the above question. How to I satisfy both requirement by combining them into a heuristic function ?
I think you can use a simple distance score calculation for the heuristic, and use both the tolls and time for cost calculation, as c0der mentioned.
Your A* search should compare all the current paths dynamically though. Remove any loops as usual, and remove the more costly path if two paths reach the same point with a better cost. After each iteration, as the paths list gets reordered by their heuristic scores, better-doing paths will get brought up in that list.

Maximum Diversity: translate an heuristic algorithm in C (or pseudocode)

I have a set of N items and I know their mutual distances. every element has a cost and I have a budget. I should accomplish the following task: suppose I put an Item in the basket, the following item in the basket will be the item whose distance is the maximum from the first (under budget constraint) the third item will be the item whose sum of distances from item1 and item2 is the maximum (under budget constraints), a forth item will be the one whose sum of distances from item 1,2 and 3 is the maximum (always budget) etc. How do I find the subset whose total distance (computed as above) is max? Do you know any algorithm to solve this problem? thanks in advance
UPDATE: I've done some research and this problem is called Maximum Diversity Problem. I can't traslate the heuristic algorithm (that would solve the problem) stated above in C or pseudocode!
This is an interesting question. If I understand correctly you are trying to find a path with maximum distance given a budget.
Let us imagine the items here as a connected graph thus we can use tools from graph theory. The edges are the costs and the vertices or nodes are the actual items. Essentially it seems you want to find a maximum path under budget constraints so a reverse dijkstra algorithm.
Steps:
Select starting vertex
Evaluate distance from starting point.
Select vertex with maximum distance if this is above your budget go to the next one burning the edge that was above your budget
Calculate distance between the newly added item to the others as the sum of the path to get to the item + the cost of choosing the other item (i.e. first iteration say we got item 1 then went to item 2 then the distance between item 2 and item x would be item 1 + item 2 +item x)
Select maximum again if above budget go to the next maximum burning the edge to the maximum that would be above your budget.
Repeat until budget exhausted
Hope this helps feel free to ask for clarification if this makes sense. I suggest some background reading on graph theory and associated algorithms

Minimizing cost of pipeline by finding optimal locations for stations using dynamic programming

I have a question about dynamic programming that I am trying to describe an algorithm for.
Question:
A pipeline is to be built and you have to decide on the optimal location of the stations along the path that has already been decided. The pipeline connects points x1 and xn and goes through locations x2,x3...x(n-1). There are stations at x1 and xn but part of the problem is to decide whether to build a station at point xi for i = 2,3...n-1.If a station is built the associated cost is bi and if a pipeline is built between stations xi and xj, the corresponding cost is cij. The total cost is the sum of the costs of the station and the corresponding pipeline section costs. The goal is to decide the optimal location of stations so that the total cost is minimized.
We have to describe a general algorithm for this using dynamic programming.
My approach was to treat this like a rod cutting problem and try to make a matrix and minimize the cost but I am not sure how to deal with the extra variable of the cost of the stations being built as well. How should I approach this problem given the many variables? And how would I develop a recursive formula?
Any help would be appreciated!
EDIT: Yes I agree that the question is a bit unclear and also confused me at first, but that is all that was given in the question. I believe since the stations and pipelines all have different costs, there should be an optimal way of doing it.
The critical insight in this is that the minimum cost to connect any two points, xi and xj (call it mij) is independent of the configurations outside of that segment (i.e. x*1* to xi and xj to xn).
Your dynamic programming problem is to index and store each cost as it's found, and the to float partial solutions back up the call tree.
The base case is that the cost to connect two adjacent nodes, xi and xj (where j=i+1), is simply cij (you can't build a new station there).
The simplest case is when j=i+2; Is it profitable to build a station at i+1. In algebraic terms, is c(i)(i+2) < b(i+1) + c(i)(i+1) + c(i+1)(i+2) ?
In general, you need to recur on a find_first_station(i, j) function. This should find the location of the lowest-index station to build between stations already at i and j. For each point 'k, i<k<j, build a station atk, run a pipeik, and then recur withfind_first_station(k, j). Return the solution (all station locations) with the minimum cost for anyk`, or the null list if cij is the minimum cost.
Can you take it from there?

least cost path, destination unknown

Question
How would one going about finding a least cost path when the destination is unknown, but the number of edges traversed is a fixed value? Is there a specific name for this problem, or for an algorithm to solve it?
Note that maybe the term "walk" is more appropriate than "path", I'm not sure.
Explanation
Say you have a weighted graph, and you start at vertex V1. The goal is to find a path of length N (where N is the number of edges traversed, can cross the same edge multiple times, can revisit vertices) that has the smallest cost. This process would need to be repeated for all possible starting vertices.
As an additional heuristic, consider a turn-based game where there are rooms connected by corridors. Each corridor has a cost associated with it, and your final score is lowered by an amount equal to each cost 'paid'. It takes 1 turn to traverse a corridor, and the game lasts 10 turns. You can stay in a room (self-loop), but staying put has a cost associated with it too. If you know the cost of all corridors (and for staying put in each room; i.e., you know the weighted graph), what is the optimal (highest-scoring) path to take for a 10-turn (or N-turn) game? You can revisit rooms and corridors.
Possible Approach (likely to fail)
I was originally thinking of using Dijkstra's algorithm to find least cost path between all pairs of vertices, and then for each starting vertex subset the LCP's of length N. However, I realized that this might not give the LCP of length N for a given starting vertex. For example, Dijkstra's LCP between V1 and V2 might have length < N, and Dijkstra's might have excluded an unnecessary but low-cost edge, which, if included, would have made the path length equal N.
It's an interesting fact that if A is the adjacency matrix and you compute Ak using addition and min in place of the usual multiply and sum used in normal matrix multiplication, then Ak[i,j] is the length of the shortest path from node i to node j with exactly k edges. Now the trick is to use repeated squaring so that Ak needs only log k matrix multiply ops.
If you need the path in addition to the minimum length, you must track where the result of each min operation came from.
For your purposes, you want the location of the min of each row of the result matrix and corresponding path.
This is a good algorithm if the graph is dense. If it's sparse, then doing one bread-first search per node to depth k will be faster.

Suggest an algorithm (graph - possibly NP-Complete)

There is a network of towns, connected by roads of various integer lengths.
A traveler wishes to travel in his car from one town to another. However, he does not want to minimize distance traveled; instead he wishes to minimize the petrol cost of the journey. Petrol can be bought in any city, however each city supplies petrol at various (integer) prices (hence why the shortest route is not necessarily the cheapest). 1 unit of petrol enables him to drive for 1 unit of distance.
His car can only hold so much petrol in the tank, and he can choose how many units of petrol to purchase at each city he travels through. Find the minimum petrol cost.
Does anyone know an efficient algorithm that could be used to solve this problem? Even the name of this type of problem would be useful so that I can research it myself! Obviously it's not quite the same as a shortest path problem. Any other tips appreciated!
EDIT - the actual problem I have states that there will be <1000 cities; <10000 roads; and the petrol tank capacity will be somewhere between 1 and 100.
You could solve this directly using Djikstra's algorithm if you are happy to increase the size of the graph.
Suppose your petrol tank could hold from 0 to 9 units of petrol.
The idea would be to split each town into 10 nodes, with node x for town t representing being at town t with x units of petrol in the tank.
You can then construct zero-cost edges on this expanded graph to represent travelling between different towns (using up petrol in the process so you would go from a level 8 node to a level 5 node if the distance was 3), and more edges to represent filling up the tank at each town with one unit of petrol (with cost depending on the town).
Then applying Djikstra should give the lowest cost path from the start to the end.
I think the question is: Is there a chance the petrol stuff makes the underlying traveling salesman problem computationally more feasible? If not, there is no efficient non-approximating algorithm.
Of course, you can find efficient solutions for edge cases, and there might be more edge cases with the petrol condition, as in, always take this city first because the petrol is so cheap.
I think you can solve this with dynamic programming. For each node, you save an array of tuples of petrol cost and the length of the path where you use that petrol, containing the optimal solution. Every step you loop trough all nodes and if there is a node you can go, which already has a solution, you loop trough all the nodes you can go to with a solution. You select the minimum cost, but note: you have to account for the petrol cost in the current node. All costs in the array that are higher than the cost in the current node, can instead be bought at the current node. Note that nodes which already have a solution should be recalculated, as the nodes you can go to from there could change. You start with the end node, setting the solution to an empty array (or one entry with cost and length 0). The final solution is to take the solution at the beginning and sum up every cost * length.
I'd try this:
Find the shortest route from start to destination. Dijkstra's algorithm is appropriate for this.
Find the minimum cost of petrol to travel this route. I'm not aware of any off-the-shelf algorithm for this, but unless there are many cities along the route even an exhaustive search shouldn't be computationally infeasible.
Find the next shortest route ...
Defining precise stopping criteria is a bit of a challenge, it might be best just to stop once the minimum cost found for a newly-tested route is greater than the minimum cost for a route already tested.
So, use 2 algorithms, one for each part of the problem.
This might be optimized suitably well using a Genetic Algorithm. Genetic Algorithms beat humans at some complex problems:
http://en.wikipedia.org/wiki/Genetic_algorithm
The gist of a Genetic Algorithm is:
Come up with a ranking function for candidate solutions
Come up with a pool of unique candidate solutions. Initialize it
with some randomly-generated possibilities. Maybe 10 or 100 or
1000...
Copy a candidate solution from the pool and perturb it in some way -
add a town, remove a town, add two towns, etc. This might improve
or worsen matters - your ranking function will help you tell. Which
one do you pick? Usually, you pick the best, but once in a while,
you intentionally pick one that's not to avoid getting stuck on a
local optimum.
Has the new solution already been ranked? If yes, junk it and go to
If no, continue...
Add the perturbed candidate back to the pool under its newly-calculated rank
Keep going at this (repeat from #3) until you feel you've done it long enough
Finally, select the answer with the best rank. It may not be
optimal, but it should be pretty good.
You could also formulate that as an integer linear programming (ILP) problem. The advantage is that there is a number of off-the-shelf solvers for this task and the complexity won't grow so fast as in the case of Peters solution with the size of the tank.
The variables in this particular problem will be the amounts of petrol purchased in any one town, the amount in the cars tank in any town on the way and actual roads taken.
The constraints will have to guarantee that the car spends the necessary fuel on every road and does not have less that 0 or more than MAX units of fuel in any town and that the roads constitute a path from A to B.
The objective will be the total cost of the fuel purchased.
The whole thing may look monstrous (ILP formulations often do), but it does not mean it cannot be solved in a reasonable time.

Resources