I am able to get the understanding of the question but unable to code it out - data-structures

Harry and John want to do a competition of weightlifting in which they can lift as many weights as they want. There are N weights numbered from 1 to N where ith weight has a value weight[i]. We have to find the total weight lifted by both of them separately after the competition ends.
Competition ends when all the weights have been lifted by them. The rules of the game are as follows-
Harry will lift the weight from left to right and John will lift the weight from right to left.
Harry will start the game and in the first move he can only lift one weight i.e. weight[0].
After the first move, the players will play alternatively i.e. after the first move the John will lift, then again Harry boy and so on…..
The boy will lift the least possible weight just greater than the weight lifted by the other boy in the previous move i.e. if one boy lifts weight equal to 8 in the previous turn, then the other boy has to lift a weight greater than 8 (using one or more weights).
Sample Input 1
1
11
3 1 4 1 5 9 2 6 5 3 5
Sample Output 1
23 21
How to get this output?

Related

Finding a graph based algorithm to clean a room with some robots in the shortest time. The map/maze is given

I need help solving the following problem:
Given a room (matrix), where each square can be: a dirty spot that needs to be cleaned, an empty spot, a wall, or a starting position for a robot, I need to find the fastest way my robot network can clean the room. I must only print the time (number of squares passed by the longest running robot until all dirty spots are visited/cleaned).
The tile where the robot started from and the cleaned square will also act like normal squares, without any constraints. 2 robots can pass by the same empty tile at the same time (no crashing case), robots only "interact" to choose where to go, not physically.
Test cases accept maximum 4 robots, but the matrix can reach 1000x1000, and you can reach any part of the room with any robot.
Robot can move in the 4 directions as long as there is no wall in the next cell.
I know I have to use graphs and I believe backtracking will be an undesired solution and it will most likely not meet the time constraints, i am looking for a smarter solution.
I will post the given examples, should be a lot easier to understand, the red spots are dirty and need to be reached:
In this example the robot that goes up need 9 seconds to finish his route while the one that goes down needs 13 seconds so the answer is 13.
In the second picture the answer is 11, how much the robot "in the middle" requires to reach it's assigned spot.
Step 1: prepare a base graph for all your dirty squares (named DirtyGraph):
All dirty squares becomes a node in your graph;
Construct a fully connected graph with edge weight equals to the steps between dirty squares;
Example:
Step 2: for each Robot, clone DirtyGraph, add the robot as a new node to this graph, calculate and add all edges to this cloned graph so it's still a fully connected graph. Name these graph Robot1G, Robot2G, etc.
Example:
Step 3: Generate all combinations of partitioning the dirty nodes into N partitions, where N is the number of robots.
Example: 2 robots:
1 | 2 3 4 5 6
2 | 1 3 4 5 6
3 | 1 2 4 5 6
4 | 1 2 3 5 6
5 | 1 2 3 4 6
6 | 1 2 3 4 5
1 2 | 3 4 5 6
1 3 | 2 4 5 6
1 4 | 2 3 5 6
1 5 | 2 3 4 6
1 6 | 2 3 4 5
2 3 | 1 4 5 6
2 4 | 1 3 5 6
.....
Step 4, for each combination of partition, assign the partitions to all combinations of robots, extract sub-graph from Robot?G and solve it as a Traveling Salesman Problem (TSP). With an "answer" you got the time for each robot to complete its own partition of dirty nodes.
Example: Partition 1 2 3 for R1 and 4 5 6 for R2
max() of time required for all robots in their own partition BECOMES the "time required for THIS combination of partition".
Step 5, after you calculation all combinations of partitions, the partition combination uses the minimal time will be the ANSWER you want, and the TSP results of the robot sub-graphs of (ANSWER) is the robot path.
This is also an answer:
Let's burn the CPU for the "correct" BEST path!
Add every square that is not a wall as a vertex to to your favorite graph theory library
Add an undirected edge between every adjacent square
Assign every red square to the nearest robot. On first pass use Pythagorean distance. Later take into account walls by using the A* algorithm.
Calculate best path for each robot to reach its assigned squares using the travelling salesman algorithm.
Output length of longest path.
Note that this will give a feasible answer, but not the optimum. For example, in your first example the red square in the 4th row ( 1-based ) will be assigned to the robot in the 6th row, instead of to the one in the 4th.

Data structure challenge Tree DFS

I came across an interesting coding challenge and could use help with the best way to do it. Here's the challenge :
It’s a brilliant day while our smart frog prince went on his quest to collect the golden eggs from the castles to break the curse and become the real prince again. He can start with (any) one of the castle tower’s topmost floor where he sees more towers nearby and the fairy sends him a message(input) on location of the golden eggs. He has the power to jump across towers any number of times until he reaches the bottom floor(ground floor) however he cannot climb up again under any circumstances.
While he jumps within the same tower, he can go to the floor below, but if he jumps from one tower to any another tower, he will drop by two floors. Say, if our frog prince is in the 1st tower’s 5th floor and if he wants to jump to the 4th tower, he will lose height (two floors) and land at 4th tower’s 3rd floor. There can be any number of floors for a castle tower, all castle towers will have equal number of floors.
Input Format
Input starts with N value: the number of castle towers.
These are followed by N number of lines,
the first integer in a line indicates the number of eggs in that respective tower,
the following integers indicate the egg’s floor wise position in the tower, also there can be more than one egg on a floor.
Sample Input:
3
5 1 1 1 4 10
8 9 5 7 7 3 9 8 8
5 9 5 6 4 3
Sample output:
12
Explanation:
I need help with the DFS (Or any other algorithm) part of the code.
Try dynamic programming.
Build a graph from the data. the graph will be a DAG (there can't be circles)
do topological sort on the graph
go over the nodes (floors) in the topological order. for each node, calculate the max number of eggs collected up to the node. the value is the max over all it's predecessors plus it's own value.

Given lengths of 3 sides of a triangle, compute an average distance between the middle points of the sides

I have come across a problem. The problem statement is
A team of 3 people, is going to participate in a competition. According to the regulations of this competition, every team is given a single computer, which is located on a triangular table, and three chairs.
Team thinks that the most convenient location of participants is the one where each of the three participants sits at his/her own side of the triangular table, and, what’s important, exactly at the middle of this side. Of course, chairs should be put the same way.
It is important that, during the competition, the participants sit not very far one from another. The Dream Team’s captain thinks that a proper estimation of this factor is an average distance between all the pairs of these participants.
In the case of this competition, one have to compute an average distance between the middle points of the sides of a triangular table. Write a program which computes exactly this. Note that the distance is Euclidean – that is, the distance between (x1,y1) and (x2,y2) is sqrt((x_1 - x_2)^2 + (y_1 - y_2)^2).
Input
The input file contains three positive integer numbers not exceeding 100 – the lengths of sides of the table. It is guaranteed that such a table will have a non-zero area.
Output
Output the average distance between the middle points of the sides of the table, which was described in the input.
Examples
Input Output
3 4 5 2.00000000
5 5 7 2.83333333
I thought of one way to solve this
1. Assume origin as 1 point.
2. If one of the length is 3, assume the point as (3,0).
3. Now, I struck at finding 3rd coordinate
Is my approach, Ok?
Please, give me an algorithm to solve this.
Thank you
Note that segment, connecting middle of edge A and middle of edge B, is half of edge C and the same is true for other sides.
So solution is very simple - average distance for triangle with side lengths A,B,C is
M = (A/2 + B/2 + C/2) / 3 =
(A + B + C ) / 6

Algorithm - matching student examination centers

I have a problem of grouping the students to the nearest examination center. Here are the conditions/constraints:
There are X students and Y examination centers. Each center will hold a different number of students.
The maximum capacity of the total of examination centers can be greater than the number of students, but not smaller.
A student can have the smallest distance to more than 1 examination center.
The examination will hold at the same time for all examination centers.
For example, there are 11500 students and 15 examination centers. 5 centers (1 to 5) will hold 1500 students, 3 for 600 (6 to 8) and the other 7 (9 to 15) will hold 350 students.
I have developed the followings:
A database table with the student's location (register address) to each of the examination centers. Something like below
Student ID Dist-Ex1 Dist-Ex2 ... Dist-Ex14 Dist-Ex15
1 10 70 20 50
2 25 43 5 105
...
11499 35 12 35 55
11500 5 23 5 5
I can add a column of storing the nearest examination center to each of the student, and create a table like below:
Ex centers Nearest for no. of students
1 2000
2 500
...
14 150
15 500
But I don't know how to further proceed. I believe it is some kind of algorithm problem. I would be grateful if anyone would give me some idea.
Thanks a lot in advance!
I understood you are looking for an optimal solution - (all students are assigned to their closest examination center). For this, we will reduce the problem to a max-flow problem
Reduce the problem to a bipartite1 graph G=(V,E) such that V = {students} U {examination centers} U {S,T} (all students, all examination centers, and two extra vertices S and T).
E = CLOSESTS U {S} X {examination centers} U {students} X {T} (S is connected to all centers, all students are connected to T, and CLOSESTS - that we will now discuss).
Where CLOSESTS = { (exam,stud) | exam is the closest examination center to the student sutd}
We also need a weight function f:E->N such that:
f(u,v) = capcity if u=S, v=examination center
f(u,v) = 1 if u is examination center and v is student
f(u,v) = 1 if u is student and v is T
The resulting graph should look something like this sample:
Now, run a max flow algorithm, like edmonds-karp. If the max flow "enters" T is #num_studets, there is an optimal solution and it is denoted by the flow network achieved by the algorithm2. The max-flow algorithm will find how much flow to put in each edge, which is equivalent to how to assign a student to a center, without breaking the capacity limit.
Proof:
If there is max flow of #students, all edges (student,T) are used,
and all student has an incoming flow, and thus is assigned. Also, each examination center has at most capcity students assigned, and the
solution is valid.
If the max flow is smaller then #students, then there is a
student that did not get a flow from an examination center, and is
thus not assigned, and there is no optimal solution.
(1) Not exactly a bipartite graph because we added S and T, without it - it was.
(2)According to Integral Flow Theorem, and since all weights are integers - there is an integral solution.
I suggest you to take a look on Genetic Algorithms here.
Take population of students and their assignments
your fitness function could give the greater value for the students with less overlap.
I've implemented Student/Scheduling problem while being in the university this way, it worked pretty good.
So I believe Genetic Algorithms is a way to go here
Good Luck!
(I know this was asked 2 years ago, but maybe it will help someone)
It can be solved optimal with the hungarian algorithm (https://en.wikipedia.org/wiki/Hungarian_algorithm) creating a bipartite graph as following:
The left nodes represent the students
The right nodes represent the seats of the 15 centers
Insert an edge from each student to each seat with weight = Distance to Center
Compute then a minimum weight matching
Problem: Your matrix has size 11500².
Solution: It is possible to model the problem without 'expanding' the centers to their seats using the following algorithm (I will not go into detail):
https://en.wikipedia.org/wiki/Minimum-cost_flow_problem

SPOJ WATER : Developing a BFS algorithm

I am attempting to solve the following question from SPOJ :
On a rectangular mesh comprising nm fields, nm cuboids were put, one
cuboid on each field. A base of each cuboid covers one field and its
surface equals to one square inch. Cuboids on adjacent fields adhere
one to another so close that there are no gaps between them. A heavy
rain pelted on a construction so that in some areas puddles of water
appeared.
Task
Write a program which:
reads from the standard input a size of the chessboard and heights of cuboids put on the fields
computes maximal water volume, which may gather in puddles after the rain
writes results in the standard output.
Input
The number of test cases t is in the first line of input, then t test
cases follow separated by an empty line. In the first line of each
test case two positive integers 1 <= n <= 100, 1 <= m <= 100 are
written. They are the size of the mesh. In each of the following n
lines there are m integers from the interval [1..10000]; i-th number
in j-th line denotes a height of a cuboid given in inches put on the
field in the i-th column and j-th raw of the chessboard.
Output
Your program should write for each tes case one integer equal to the
maximal volume of water (given in cubic inches), which may gather in
puddles on the construction.
Example
Sample input:
1
3 6
3 3 4 4 4 2
3 1 3 2 1 4
7 3 1 6 4 1
Sample output:
5
I am using a BFS to add how much water will flow from the border elements into the puddle(if theres any path found). But I am unable to handle cases where a puddle maybe like two consecutive cuboids. Can anyone help me with that case?
Here is my answer for the problem. For speaking convenience, I assume the index start from (1,1) to (M,N)
As you can imagine as the flow of water, the water can only travel from the higher cuboid to the lower cuboid ( there is no revert direction i.e. the water from lower cuboid will hit the wall of higher cuboid and stop there).
So we build the graph G = (V,E) such that V are M x N vertices i.e. the cuboid on the matrix. The edge are connected (1-way ONLY) that connected cuboid i(th) to cuboid j(th) when
height(i) >= height(j) and (i and j are physically CONNECTED)
So the problem are just a simple BFS.
By the way, I found another one solve this problem as well. Please take a look
http://www.spojsolutions.com/212-water-among-cubes/

Resources