Dijkstra by means of Heap and pred-field - heap

I have the following task, but I have no idea how to do it?
Calculate (lexicographically) the shortest path from V1-node to the other nodes by means of Dijkstra. Please write the current Heaps and corresponding Pred-fields as well. Start with new Heap and pred-field before the ExtractMin-Call.
I got this result via Dijkstra, but how should I add it to the min-heap (tree)?

I found exactly this task in an old exam I use for learning algorithms. I wasn't sure how to solve it so I searched several books for any explanation on how the minheap works along with Dijkstra and didn't find any. Finally I figured it out. So I hope this helps to understand how to solve this problem.
Step 1: Draw the heap lexicographically: V1 -> root, and then the
other nodes from left to right. V1 has the value 0, all other nodes
inf.
Step 2: ExtractMin(): swap root (which has the lowest value)
with the very last node and cut it off.
Step 3: Relaxation: Update new values for the nodes, if value decreases. "What is the new value from start to X when
I walk via the node, I just extracted, respecting its predecessors? Is it less than the old value, then update."
Step 4: Update the predecessor field if there is a better path.
Step 5: Call Heapify(): Resort the heap, so that
the node with the lowest value becomes root.
Repeat Step 2 to 5 until there are no nodes left.

Related

How to create directed graph with nodes having multiple data?

I want to create a graph with nodes and edges, where each node will contain n number of values. We would be given with the n values of the starting node, from which we need to generate other nodes where each value in each node would be of the form either:
t_n=t_(n-1)+2
or
t_n=t_(n-1)-1
When such a node is generated, it should create an edge from the old node to the new node.
I know this might be very trivial job, but I have very limited programming knowledge. I have been suggested to use classes in C++ or structure to represent the nodes. Please help me in creating the graph with nodes that would have multiple values and further the next nodes would be generated from the parent node following the above rule. Some C++ code would be very helpful.
Thanks in Advance.
here you have some code but I don't really fully understand your task.
- graph with nodes and edges
- each node has n number of values
- we are given n values of the starting point
- need to generate other nodes where each value in each node would be either
- t_n=t_(n-1)+2
- t_n=t_(n-1)-1
- when such node is generated, it creates an edge from the old node to the new node.
this starting point: do we have to generate a graph from it? what is with the creation of the edge from the old node and the new node? is old node here the starting point?
does n number of values means to where the point is connected to (as a chain of the other edges to which this edge is connected to)? example we are provided a node with a chain of numbers (6, 4, 5) where this means we need to generate extra edges which would be connected x times (first one linked to our starting point would be linked to 6 edges, one of them being the starting point)
will edit my answer when I have more information. could you please draw an example in paint and upload it online and provide the link? it would be easier to imagine.

Partition in Equivalence sets

I have a simple, non-dirictional tree T. I should find a path named A and another named B that A and B have no common vertex. The perpuse is to maxmize the Len(A)*Len(B).
I figured this problem is similer to Partition Problem, except in Partition Problem you have a set but here you have a Equivalence set. The solution is to find two uncrossed path that Len(A) ~ Len(B) ~ [n-1/2]. Is this correnct? how should I impliment such algorithm?
First of all. I Think you are looking at this problem the wrong way. As I understand it you have a graph related problem. What you do is
Build a maximum spanning tree and find the length L.
Now, you say that the two paths can't have any vertex in common, so we have to remove an edge to archieve this. I assume that every edge wheight in your graph is 1. So sum of the two paths A and B are L-1 after you removed an edge. The problem is now that you have to remove an edge such that the product of len(a) and len(b) is maximized. You do that by removeing the edge in et most 'middel' of L. Why, the problem is of the same as optimizing the area of a rectangle with a fixed perimeter. A short youtube video on the subject can be found here.
Note if your edge wheights are not equal to 1, then you have a harder problem, because there may exist more than one maximum spanning tree. But you may be able to split them in different ways, if this is the case, write me back, then I will think about a solution, but i do not have one at hand.
Best of luck.
I think there is a dynamic programming solution that is just about tractable if path length is just the number of links in the paths (so links don't have weights).
Work from the leaves up. At each node you need to keep track of the best pair of solutions confined to the subtree with root at that node, and, for each k, the best solution with a path of length k terminating in that node and a second path of maximum length somewhere below that node and not touching the path.
Given this info for all descendants of a node, you can produce similar info for that node, and so work your way up to the route.
You can see that this amount of information is required if you consider a tree that is in fact just a line of nodes. The best solution for a line of nodes is to split it in two, so if you have only worked out the best solution when the line is of length 2n + 1 you won't have the building blocks you need for a line of length 2n + 3.

AVL Insert and balance loop

I am implementing AVL Trees in C++ on my own code but this problem is more about understanding AVL trees rather than the code itself. I am sorry if it doesn't fit here but I have crawled through the Internet and I have still not found a solution to my problem.
My code works as expected with relatively small inputs (~25-30 digits) so I suppose it should work for more. I am using an array in which I hold the nodes I have visited during Insertion and then using a while loop I am raising the heights of each node when needed, I know that this procedure has to end when I find a node whose heights are equal (their subtraction result is 0 that is).
The problem is when it comes to balancing. While I can find the Balance Factor of each node and balance the tree correctly I am not sure if I should stop adjusting the heights after balancing and just end the Insertion loop or keep going until the condition is meant, and I just can't figure it out now. I know that during deletion of a node and re-balancing the tree I should keep checking but I am not sure about Insertion and balancing.
Anyone can provide any insight to this and perhaps some documentation?
If you insert only one item at a time: Only one (single or double) rotation is needed to readjust an AVL tree after an insertion throws it out of balance. http://cis.stvincent.edu/html/tutorials/swd/avltrees/avltrees.html You can probably prove it by yourself after you know the conclusion.
Just for reference of future readers there is no need to edit the heights of the nodes above the node you balanced if you have implemented the binary tree like my example:
10
(1)/ \(2)
8 16
(1)/ \(0)
11
(Numbers in parenthesis are the height of each sub tree)
Supposing than on the tree above we insert a node with data=15 Then the resulting subtree is as following:
10
(1)/ \(2)
8 16
(1)/ \(0)
11
(0)/ \(1)
15
Notice how previous heights of sub trees are not yet edited. After a successful insertion we run back through the insertion path, in this case its (11, 16, 10). After running back through this path we edit the heights when needed. That means the left height of the sub tree of 16 will be 2 while it's right height of sub tree is 0 resulting in an imbalanced AVL tree. After balancing the tree with a double rotation the sub tree is:
15
(1)/ \(1)
11 16
So the subtree height is maximum 1, as it was before, therefore heights above the root of this subtree haven't altered and the function changing the heights must return now.

Faster alternatives to Dijkstra's algorithm for GPS system

I'm a real speed freak if it gets to algorithms, and in the plugins I made for a game.
The speed is.. a bit.. not satisfying. Especially while driving around with a car and you do not follow your path, the path has to be recalculated.. and it takes some time, So the in-game GPS is stacking up many "wrong way" signals (and stacking up the signals means more calculations afterward, for each wrong way move) because I want a fast, live-gps system which updates constantly.
I changed the old algorithm (some simple dijkstra implementation) to boost::dijkstra's to calculate a path from node A to node B
(total node list is around ~15k nodes with ~40k connections, for curious people here is the map: http://gz.pxf24.pl/downloads/prv2.jpg (12 MB), edges in the red lines are the nodes),
but it didn't really increase in speed. (At least not noticeably, maybe 50 ms).
The information that is stored in the Node array is:
The ID of the Node,
The position of the node,
All the connections to the node (and which way it is connected to the other nodes, TO, FROM, or BOTH)
Distance to the connected nodes.
I'm curious if anybody knows some faster alternatives in C/C++?
Any suggestions (+ code examples?) are appreciated!
If anyone is interested in the project, here it is (source+binaries):
https://gpb.googlecode.com/files/RouteConnector_177.zip
In this video you can see what the gps-system is like:
http://www.youtu.be/xsIhArstyU8
as you can see the red route is updating slowly (well, for us - gamers - it is slow).
( ByTheWay: the gaps between the red lines have been fixed a long time ago :p )
Since this is a GPS, it must have a fixed destination. Instead of computing the path from your current node to the destination each time you change the current node, you can instead find the shortest paths from your destination to all the nodes: just run Dijkstra once starting from the destination. This will take about as long as an update takes right now.
Then, in each node, keep prev = the node previous to this on the shortest path to this node (from your destination). You update this as you compute the shortest paths. Or you can use a prev[] array outside of the nodes - basically whatever method you are using to reconstruct the path now should still work.
When moving your car, your path is given by currentNode.prev -> currentNode.prev.prev -> ....
This will solve the update lag and keep your path optimal, but you'll still have a slight lag when entering your destination.
You should consider this approach even if you plan on using A* or other heuristics that do not always give the optimal answer, at least if you still get lag with those approaches.
For example, if you have this graph:
1 - 2 cost 3
1 - 3 cost 4
2 - 4 cost 1
3 - 4 cost 2
3 - 5 cost 5
The prev array would look like this (computed when you compute the distances d[]):
1 2 3 4 5
prev = 1 1 1 2 3
Meaning:
shortest path FROM TO
1 2 = prev[2], 2 = 1, 3
1 3 = prev[3], 3 = 1, 3
1 4 = prev[ prev[4] ], prev[4], 4 = 1, 2, 4 (fill in right to left)
1 5 = prev[ prev[5] ], prev[5], 5 = 1, 3, 5
etc.
To make the start instant, you can cheat in the following way.
Have a fairly small set of "major thoroughfare nodes". For each node define its "neighborhood" (all nodes within a certain distance). Store the shortest routes from every major thoroughfare node to every other one. Store the shortest routes to/from each node to its major thoroughfares.
If the two nodes are in the same neighborhood you can calculate the best answer on the fly. Else consider only routes of the form, "here to major thoroughfare node near me to major thoroughfare near it to it". Since you've already precalculated those, and have a limited number of combinations, you should very quickly be able to calculate a route on the fly.
Then the challenge becomes picking a set of major thoroughfare nodes. It should be a fairly small set of nodes that most good routes should go through - so pick a node every so often along major streets. A list of a couple of hundred should be more than good enough for your map.

The New Villa Acm solution strategy

I am trying to solve this ACM problem The New Villa
and i am not figuring out how to approach this problem definitely its graph problem but doors and the room that have switches to other rooms are very confusing to make a generic solution. Can some body help me in defining the strategy for this problem.
Also i want some discussion forum for ACM problems if you know any one then please share.
Thanks
A.S
It seems like a pathfinding problem on states.
You can represent each vertex with a binary vector of size n + an indentifier - where which room you are in at the moment [n is the number of rooms].
G=(V,E) where V = {all binary vectors of size n and a recored for which room you are in} and E = {(u,v) | you can switch from binary vector u to v by clicking a button in the room you are in, or move to adjacent lights on room }
Now you only need to run a search algorithm on the possible paths.
Possible search algorithms:
BFS - simplest to program, though slowest run time
bi - directional BFS - since there is only one target node,
a bi-directional search will work here, it is expected to be much
faster then BFS
A* - find an admissible heurstic function and run
informed A* on the problem. It is harder to program it then the rest - but if you find a good heurisitc, it will most likely perform much better.
(*) All of the above are both complete [will find a solution if one exists] and optimal [will find the shortest solution, if one exists]
(*) This solution runs in exponential time on the number of rooms, but it should end up for d <= 10 as indicated in the problem in reasonable time.