onsider a graph of five vertices whose vertices are labelled 1 to 5. The only edges present in the graph are one each from 1 to 2, 1 to 3, 1 to 4 and 1 to 5. Let the time taken to travel from 1 to 2, 3, 4 and 5 be 5, 5, 1 and 1 units respectively. Also assume that if it takes time t to travel from vertex a to b, then it takes the same time to travel from b to a.We wish to select a walk from vertex 1 to some other vertex, back to vertex 1 and so on till each vertex (except vertex 1 - the source) is visited exactly once.
Let the initial instant be t = 0. Let the times of visit of vertices 2, 3, 4 and 5 from t = 0 be t2, t3, t4 and t5.We wish to minimise the sum of t2, t3, t4 and t5.
Find out the minimum possible sum of the given times.
i am unable to understand the question itself
This is my understanding of the question:
If you visit nodes 2, 3 ,4, and 5 in that order, the times will be:
t2 = 5 (going from 1 to 2),
t3 = 15 (5 to get to 2, 5 to return from 2 back to 1, and 5 to go from 1 to 3),
t4 = 21 (15 + 5 + 1),
t5 = 23 (21 + 1 + 1).
The sum is 64. You can get a better time with a different order, your task is to find the best (minimum) sum.
To minimise the total time of visiting, we select the path which takes minimum time first because this time piles up on all other vertices. After we come back to 1,we then select the path with second minimum time and we repeat this process each time after we come back to 1.
Let the times in sorted order be a,b,c and d for vertices v1,v2,v3 and v4. Then vertex v1 is visited at time t = a.We come back to 1 at t = 2a.We then reach the second vertex at t = 2a + b and come back to 1 at t = 2a + 2b. Continuing similarly, vertex v3 is visited at t = 2a + 2b + c and v4 is visited at t = 2a + 2b + 2c + d. So, the minimum value of the sum of times would be 7a + 5b + 3c + d.
So, the answer is 32.
so can we start the walk with vertex 5 =1+1=2
vertex 4 = 1+1=2
vertex 3=5+5=10
vertex 2= 5
total=2+2+10+5=19
Note that your total never changes, no matter the order in which you visit the nodes, so you cannot minimize it. You may want to clarify this with the teacher, but the problem definition states "time instance," not duration.
Think of it as starting a timer at time t-1 Then, for your path above (t-1 = 0): t-5(vertex-5) = 1, t-4 = 3, t-2 = 9, t-3 = 19. The sum is 32. Much better than 64, so you are on the right track!
Dijkstra's is used to find the shortest path between nodes, and it doesn't apply here. This problem is much easier.
Related
We have an undirected acyclic graph where there is only a single path between two connected nodes that may look something like this.
Simple guide to the image:
Black numbers: Node id's (note that each node contains a resource collector)
Resource collectors: Every resource collector collects resources on edges that are right next to it (so a collector on node 0 cannot reach resource deposits past node 1 and so on). A resource collector also requires fuel to operate - the amount of fuel a resource collector needs is directly connected to its range - the range determines the furthest resource node it can reach on the allowed edges (the range of the collectors is the blue circle on some nodes in the image). The fuel consumption of a collector is then calculated like this: fuel = radius of the circle (meaning that in the example case node 0 consumes 1 fuel and node 1 and 3 consume 2 fuel each, and since all the resource deposits have been covered our final fuel requirement is 5 (nodes 2, 5 and 4 do not use any fuel, since their radii are 0)).
Black lines: Graph edges
Red dots: Resource deposits, we only receive the number of deposits on a specific edge and all the deposits are evenly spaced apart on their respective edge.
Our task is to find the best configuration for our resource collectors (that is, find the configuration that consumes the lowest amount of fuel, and reaches all resource nodes) By this is meant: set the collector radius.
Things I've tried to solve this problem:
At first I've tried locating the "central" node of the graph and then traversing it with BFS while checking one node ahead and determining the amount of fuel from there, this did work for some graphs, but it became unstable in more complex ones.
After that I've tried basically the same thing, but I chose the leaf nodes as the starting points, this produced similar, imperfect, results.
This is an allocation problem.
Set "cost" of each pair of collector and deposit it can reach to be the distance from collector to deposit. Other pairs, where the deposit is unreachable, have infinite cost and can be omitted from the input.
Set collector/deposit pair with ( next ) lowest cost. Allocate deposit to collector. Repeat until all deposits allocated.
Set radius of each collector to be the distance from the collector to the furthest deposit assigned to it.
Here is the cost of each pair in your example. 031 means the first deposit on the edge from 0 to 3
Note that you renumbered the nodes in your example!!! The numbers in the table refer to the original diagram which looked like this
collector
deposit
cost
0
031
1
0
032
2
0
033
3
3
031
3
3
032
2
3
033
1
3
351
1
3
361
1
3
362
2
3
371
1
3
372
2
5
351
1
5
581
1
5
582
2
6
361
2
6
362
1
7
371
2
7
372
1
8
581
2
8
582
1
Note that this algorithm will assign deposit 231 to collector 2. This is different from your answer, but has the same total fuel cost. However 142 will go to 4 and 152 will go to 5, which increases the total fuel cost.
To handle this situation, collectors with more than 2 connections to other nodes need to be looked at, to see if the fuel cost can be further reduced by increasing their radius, "robbing" deposits from their neighbors.
This is not an allocation problem. There is a greedy optimal solution in O(n).
Here is the essence of the solution:
Let R(V,W) be the # of resource collectors on an edge between V & W. Note: R(V,W) == R(W,V) given the graph is undirected.
Set weight(V) = 0 for all vertices in the graph
1. A connected undirected acyclic graph is a forest.
2. Either the graph has 1 node (terminal case), or there is at least 1 vertex with degree 1. If the graph has 1 node, the algorithm is finished.
3. Select any vertex with degree 1. Let V be the vertex. Let W represent the other vertex connected to V.
4. weight(V) + weight(W) >= # of resource collectors on the edge(V,W)
5. Since V has degree 1, it is strictly better to use fuel from node W.
6. Set weight(W) = max(weight(W), R(V,W) - weight(V)).
7. Remove V and E(V,W) from the graph. The resulting graph is still a connected undirected acyclic graph. Repeat until the graph is a single vertex.
Test case #1:
A - B - C - D - E. All edges have 1 resource collector
Select A. weight(B) = 1, since R(A,B) - weight(A) = 1.
Select B. weight(C) = 0, since R(B,C) - weight(B) = 0.
Select C. weight(D) = 1, since R(C,D) - weight(C) = 1.
Select D. weight(E) = 0, since R(D,E) - weight(D) = 0.
Test case #2:
A - B - C - D - E. R(A,B) = R(D,E) = 1. R(B,C) = R(C,D) = 2.
Select A. weight(B) = 1, since R(A,B) - weight(A) = 1.
Select E. weight(D) = 1, since R(D,E) - weight(E) = 1.
Select B. weight(C) = 1, since R(B,C) - weight(B) = 1.
Select C. weight(D) = 1, since max(weight(D), R(C,D) - weight(C)) = 1.
Can anyone tell the algorithm for finding the maximum path cost in a NxM matrix starting from top left corner and ending with bottom right corner with left ,right , down movement is allowed in a matrix and contains negative cost. A cell can be visited any number of times and after visiting a cell its cost is replaced with 0
Constraints
1 <= nxm <= 4x10^6
INPUT
4 5
1 2 3 -1 -2
-5 -8 -1 2 -150
1 2 3 -250 100
1 1 1 1 20
OUTPUT
37
Explanation is given in the image
Explanation of Output
Since you have also negative costs then use bellman-ford. What you do is that you change sign of all the costs(convert negative signs to positive and positive to negative) then find the shortest path and this path will be the longest because you have changed the signs.
If the sign is never becoms negative then use dijkstra shrtest-path but before that make all values negative and this will return you the longest path with it's cost.
You matrix is a direct graph. In your image you are trying to find a path(max or min) from index (0,0) to (n-1,n-1).
You need these things to represent it as a graph.
You need a linkedlist and in each node you have a first_Node, second_Node,Cost to move from first node to second.
An array of linkedlist. In each array index you save a linkedlist.If for example there is a path from 0 to 5 and 0 to 1(it's an undirected graph) then your graph will look like this.
If you want a direct-graph then simply add in adj[0] = 5 and do not add in adj[5] = 0 , this means that there is path from 0 to 5 but not from 5 to zero.
Here linkedlist represents only nodes which are connected not there cost. You have to add extra variable there which keep cost for each two nodes and it will look like this.
Now instead of first linkedlist put this linkedlist in your array and you have a graph now to run shortest or longest path algorithm.
If you want an intellgent algorithm then you can use A* with heuristic, i guess manhattan will be best.
If cost of your edges is not negative then use Dijkstra.
If cost is negative then use bellman-ford algorithm.
You can always find the longest path by converting the minus sign to plus and plus to minus and then run shortest path algorithm. Path founded will be longest.
I answered this question and as you said in comments to look at point two. If that's a task then main idea of this assignment is ensure the Monotonocity.
h stands for heuristic cost.
A stands for accumulated cost.
Which says that each node the h(A) =< h(A) + A(A,B). Means if you want to move from A to B then cost should not be decreasing(can you do something with your values such that this property will hold) but increasing and once you satisfy this condition then everyone node which A* chooses , that node will be part of your path from source to Goal because this is the path with shortest/longest value.
pathMax You can enforece monotonicity. If there is path from A to B such that f(S...AB) < f(S ..B) then set cost of the f(S...AB) = Max(f(S...AB) , f(S...A)) where S means source.
Since moving up is not allowed, paths always look like a set of horizontal intervals that share at least 1 position (for the down move). Answers can be characterized as, say
struct Answer {
int layer[N][2]; // layer[i][0] and [i][1] represent interval start&end
// with 0 <= layer[i][0] <= layer[i][1] < M
// layer[0][0] = 0, layer[N][1] = M-1
// and non-empty intersection of layers i and i+1
};
An alternative encoding is to note only layer widths and offsets to each other; but you would still have to make sure that the last layer includes the exit cell.
Assuming that you have a maxLayer routine that finds the highest-scoring interval in each layer (const O(M) per layer), and that all such such layers overlap, this would yield an O(N+M) optimal answer. However, it may be necessary to expand intervals to ensure that overlap occurs; and there may be multiple highest-scoring intervals in a given layer. At this point I would model the problem as a directed graph:
each layer has one node per score-maximizing horizontal continuous interval.
nodes from one layer are connected to nodes in the next layer according to the cost of expanding both intervals to achieve at least 1 overlap. If they already overlap, the cost is 0. Edge costs will always be zero or negative (otherwise, either source or target intervals could have scored higher by growing bigger). Add the (expanded) source-node interval value to the connection cost to get an "edge weight".
You can then run Dijkstra on this graph (negate edge weights so that the "longest path" is returned) to find the optimal path. Even better, since all paths pass once and only once through each layer, you only need to keep track of the best route to each node, and only need to build nodes and edges for the layer you are working on.
Implementation details ahead
to calculate maxLayer in O(M), use Kadane's Algorithm, modified to return all maximal intervals instead of only the first. Where the linked algorithm discards an interval and starts anew, you would instead keep a copy of that contender to use later.
given the sample input, the maximal intervals would look like this:
[0]
1 2 3 -1 -2 [1 2 3]
-5 -8 -1 2 -150 => [2]
1 2 3 -250 100 [1 2 3] [100]
1 1 1 1 20 [1 1 1 1 20]
[0]
given those intervals, they would yield the following graph:
(0)
| =>0
(+6)
\ -1=>5
\
(+2)
=>7/ \ -150=>-143
/ \
(+7) (+100)
=>12 \ / =>-43
\ /
(+24)
| =>37
(0)
when two edges incide on a single node (row 1 1 1 1 20), carry forward only the highest incoming value.
For each element in a row, find the maximum cost that can be obtained if we move horizontally across the row, given that we go through that element.
Eg. For the row
1 2 3 -1 -2
The maximum cost for each element obtained if we move horizontally given that we pass through that element will be
6 6 6 5 3
Explanation:
for element 3: we can move backwards horizontally touching 1 and 2. we will not move horizontally forward as the values -1 and -2, reduces the cost value.
So the maximum cost for 3 = 1 + 2 + 3 = 6
The maximum cost matrix for each of elements in a row if we move horizontally, for the input you have given in the description will be
6 6 6 5 3
-5 -7 1 2 -148
6 6 6 -144 100
24 24 24 24 24
Since we can move vertically from one row to the below row, update the maximum cost for each element as follows:
cost[i][j] = cost[i][j] + cost[i-1][j]
So the final cost matrix will be :
6 6 6 5 3
1 -1 7 7 -145
7 5 13 -137 -45
31 29 37 -113 -21
Maximum value in the last row of the above matrix will be give you the required output i.e 37
We all know that the minimum number of moves required to solve the classical towers of hanoi problem is 2n-1. Now, let us assume that some of the discs have same size. What would be the minimum number of moves to solve the problem in that case.
Example, let us assume that there are three discs. In the classical problem, the minimum number of moves required would be 7. Now, let us assume that the size of disc 2 and disc 3 is same. In that case, the minimum number of moves required would be:
Move disc 1 from a to b.
Move disc 2 from a to c.
Move disc 3 from a to c.
Move disc 1 from b to c.
which is 4 moves. Now, given the total number of discs n and the sets of discs which have same size, find the minimum number of moves to solve the problem. This is a challenge by a friend, so pointers towards solution are welcome. Thanks.
Let's consider a tower of size n. The top disk has to be moved 2n-1 times, the second disk 2n-2 times, and so on, until the bottom disk has to be moved just once, for a total of 2n-1 moves. Moving each disk takes exactly one turn.
1 moved 8 times
111 moved 4 times
11111 moved 2 times
1111111 moved 1 time => 8 + 4 + 2 + 1 == 15
Now if x disks have the same size, those have to be in consecutive layers, and you would always move them towards the same target stack, so you could just as well collapse those to just one disk, requiring x turns to be moved. You could consider those multi-disks to be x times as 'heavy', or 'thick', if you like.
1
111 1 moved 8 times
111 collapse 222 moved 4 times, taking 2 turns each
11111 -----------> 11111 moved 2 times
1111111 3333333 moved 1 time, taking 3 turns
1111111 => 8 + 4*2 + 2 + 1*3 == 21
1111111
Now just sum those up and you have your answer.
Here's some Python code, using the above example: Assuming you already have a list of the 'collapsed' disks, with disks[i] being the weight of the collapsed disk in the ith layer, you can just do this:
disks = [1, 2, 1, 3] # weight of collapsed disks, top to bottom
print sum(d * 2**i for i, d in enumerate(reversed(disks)))
If instead you have a list of the sizes of the disks, like on the left side, you could use this algorithm:
disks = [1, 3, 3, 5, 7, 7, 7] # size of disks, top to bottom
last, t, s = disks[-1], 1, 0
for d in reversed(disks):
if d < last: t, last = t*2, d
s = s + t
print s
Output, in both cases, is 21, the required number of turns.
It completely depends on the distribution of the discs that are the same size. If you have n=7 discs and they are all the same size then the answer is 7 (or n). And, of course the standard problem is answered by 2n-1.
As tobias_k suggested, you can group same size discs. So now look at the problem as moving groups of discs. To move a certain number of groups, you have to know the size of each group
examples
1
n=7 //disc sizes (1,2,3,3,4,5,5)
g=5 //group sizes (1,1,2,1,2)
//group index (1,2,3,4,5)
number of moves = sum( g-size * 2^( g-count - g-index ) )
in this case
moves = 1*2^4 + 1*2^3 + 2*2^2 + 1*2^1 + 2*2^0
= 16 + 8 + 8 + 2 + 2
= 36
2
n=7 //disc sizes (1,1,1,1,1,1,1)
g=1 //group sizes (7)
//group index (1)
number of moves = sum( g-size * 2^( g-count - g-index ) )
in this case
moves = 7*2^0
= 7
3
n=7 //disc sizes (1,2,3,4,5,6,7)
g=7 //group sizes (1,1,1,1,1,1,1)
//group index (1,2,3,4,5,6,7)
number of moves = sum( g-size * 2^( g-count - g-index ) )
in this case
moves = 1*2^6 + 1*2^5 + 1*2^4 + 1*2^3 + 1*2^2 + 1*2^1 + 1*2^0
= 64 + 32 + 16 + 8 + 4 + 2 + 1
= 127
Interesting note about the last example, and the standard hanoi problem: sum(2n-1) = 2n - 1
I wrote a Github gist in C for this problem. I am attaching a link to it, may be useful to somebody, I hope.
Modified tower of Hanoi problem with one or more disks of the same size
There are n types of disks. For each type, all disks are identical. In array arr, I am taking the number of disks of each type. A, B and C are pegs or towers.
Method swap(int, int), partition(int, int) and qSort(int, int) are part of my implementation of the quicksort algorithm.
Method toh(char, char, char, int, int) is the Tower of Hanoi solution.
How it is working: Imagine we compress all the disks of the same size into one disk. Now we have a problem which has a general solution to the Tower of Hanoi. Now each time a disk moves, we add the total movement which is equal to the total number of that type of disk.
I have already read What is an "external node" of a "magic" 3-gon ring? and I have solved problems up until 90 but this n-gon thing totally baffles me as I don't understand the question at all.
So I take this ring and I understand that the external circles are 4, 5, 6 as they are outside the inner circle. Now he says there are eight solutions. And the eight solutions are without much explanation listed below. Let me take
9 4,2,3; 5,3,1; 6,1,2
9 4,3,2; 6,2,1; 5,1,3
So how do we arrive at the 2 solutions? I understand 4, 3, 2, is in straight line and 6,2,1 is in straight line and 5, 1, 3 are in a straight line and they are in clockwise so the second solution makes sense.
Questions
Why does the first solution 4,2,3; 5,3,1; 6,1,2 go anti clock wise? Should it not be 423 612 and then 531?
How do we arrive at 8 solutions. Is it just randomly picking three numbers? What exactly does it mean to solve a "N-gon"?
The first doesn't go anti-clockwise. It's what you get from the configuration
4
\
2
/ \
1---3---5
/
6
when you go clockwise, starting with the smallest number in the outer ring.
How do we arrive at 8 solutions. Is it just randomly picking three numbers? What exactly does it mean to solve a "N-gon"?
For an N-gon, you have an inner N-gon, and for each side of the N-gon one spike, like
X
|
X---X---X
| |
X---X---X
|
X
so that the spike together with the side of the inner N-gon connects a group of three places. A "solution" of the N-gon is a configuration where you placed the numbers from 1 to 2*N so that each of the N groups sums to the same value.
The places at the end of the spikes appear in only one group each, the places on the vertices of the inner N-gon in two. So the sum of the sums of all groups is
N
∑ k + ∑{ numbers on vertices }
k=1
The sum of the numbers on the vertices of the inner N-gon is at least 1 + 2 + ... + N = N*(N+1)/2 and at most (N+1) + (N+2) + ... + 2*N = N² + N*(N+1)/2 = N*(3*N+1)/2.
Hence the sum of the sums of all groups is between
N*(2*N+1) + N*(N+1)/2 = N*(5*N+3)/2
and
N*(2*N+1) + N*(3*N+1)/2 = N*(7*N+3)/2
inclusive, and the sum per group must be between
(5*N+3)/2
and
(7*N+3)/2
again inclusive.
For the triangle - N = 3 - the bounds are (5*3+3)/2 = 9 and (7*3+3)/2 = 12. For a square - N = 4 - the bounds are (5*4+3)/2 = 11.5 and (7*4+3)/2 = 15.5 - since the sum must be an integer, the possible sums are 12, 13, 14, 15.
Going back to the triangle, if the sum of each group is 9, the sum of the sums is 27, and the sum of the numbers on the vertices must be 27 - (1+2+3+4+5+6) = 27 - 21 = 6 = 1+2+3, so the numbers on the vertices are 1, 2 and 3.
For the sum to be 9, the value at the end of the spike for the side connecting 1 and 2 must be 6, for the side connecting 1 and 3, the spike value must be 5, and 4 for the side connecting 2 and 3.
If you start with the smallest value on the spikes - 4 - you know you have to place 2 and 3 on the vertices of the side that spike protrudes from. There are two ways to arrange the two numbers there, leading to the two solutions for sum 9.
If the sum of each group is 10, the sum of the sums is 30, and the sum of the numbers on the vertices must be 9. To represent 9 as the sum of three distinct numbers from 1 to 6, you have the possibilities
1 + 2 + 6
1 + 3 + 5
2 + 3 + 4
For the first group, you have one side connecting 1 and 2, so you'd need a 7 on the end of the spike to make 10 - no solution.
For the third group, the minimal sum of two of the numbers is 5, but 5+6 = 11 > 10, so there's no place for the 6 - no solution.
For the second group, the sums of the sides are
1 + 3 = 4 -- 6 on the spike
1 + 5 = 6 -- 4 on the spike
3 + 5 = 8 -- 2 on the spike
and you have two ways to arrange 3 and 5, so that the group is either 2-3-5 or 2-5-3, the rest follows again.
The solutions for the sums 11 and 12 can be obtained similarly, or by replacing k with 7-k in the solutions for the sums 9 resp. 10.
To solve the problem, you must now find out
what it means to obtain a 16-digit string or a 17-digit string
which sum for the groups gives rise to the largest value when the numbers are concatenated in the prescribed way.
(And use pencil and paper for the fastest solution.)
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I am doing a problem CCHESS, here is the link ( http://www.spoj.pl/problems/CCHESS/ ) to the problem.
The question is as follows:
In the country of Rome, Chess is a royal game. For evey move the players had to give some bucks to the Emperor Jurg. The LGMs or Little Green Men, are very good player of chess. But as the chess is a expensive game, thats why it is royal, they asked you to help them find the minimum bucks which they had to pay for moving their Knight from one position to another. Any number of steps can be used to reach the destination.
Constraints:
The chess has a dimension of 8X8, and the index of left bottom cell (0, 0).
Knight move only in a standard way, i.e. 2 row and 1 col or 1 row and 2 col.
If in a step Knight move from (a, b) to (c, d), then LGM had to pay a*c + b*d bucks to Emperor Jurg.
0 ≤ a, b, c, d ≤ 7
Input
There are 100-150 test cases. Each test case is composed of four space separeated integers.The first two numbers, a, b, are the starting position of the Knight and the next two, c, d, are the destination of the Knight. Read upto End Of File.
Output
For each test case, print the minimum amount of bucks they had to pay in separate line. If its impossible to reach the destination then print -1.
Example
Input:
2 5 5 2
4 7 3 2
1 2 3 4
Output:
42
78
18
Explanation for test case #1:
2 5 5 2
For moving Knight from
(2, 5) to (5, 2)
in minimum cost, one of the path is
(2, 5) -> (3, 3) ->(5, 2)
Bucks paid:
(2, 5) = 0
(2, 5) -> (3, 3) = 0 + (2*3 + 5*3) = 21
(3, 3) -> (5, 2) = 21 + (3*5 + 3*2) = 42
To infinity and beyond...
I have done this problem using brute force, i.e. checking recursively all the possible paths but i think i am missing somewhere to find a direct approach, because numerous submissions are of 0.00 where as my recursive approach got accepted in 0.3s .
Any help would be appreciated.
Construct a graph G=(V,E) where
V is the set of coordinates in the grid {v=(x,y)}
E is the set of edges between vertices
Assign weights on the edges where weight is (v1.x * v2.x + v1.y*v2.y)
Use Dijkstra's algorithm to find the shortest path (1 source - 1 destination)
source = (a,b) and destination = (c,d)
If there is no path report -1.
The number of vertices are limited to (8*8) = 64
The number of edges are limited to 64 * (8) = 512
as the knight can move to at most 8 other coordinates from one place.
Try A* algorithm, with heuristic = manhattan_distance/3 .