ACM ICPC Programming competition problem [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can you answer this 2009 ACM International Collegiate Programming Contest Finals problem?
Hi,
I am attempting to do question 1 here-> http://cm.baylor.edu/ICPCWiki/attach/Problem%20Resources/2009WorldFinalProblemSet.pdf
and cannot really come up with a good algorithm to solve it :
Basically, there are n planes, n is read in from standard input. There are then n intervals for times in which the planes can arrive, you must compute the largest interval between all planes that is possible. So, say
n = 3
and you are given the inputs
0 10
5 15
10 15
The answer is : 7: 30, the largest possible interval between planes.
Not really sure how I would go about solving this. Any tips ?

For the first plane, select the earliest possible arrival time
For the last plane, select the latest possible arrival time
For elements 2 through element n-1:
Search for a midpoint plane by dividing the range between element 1 and element n
(Hopefully, that will be close to the element n/2)
recursivly call the same function for element 1 and the midpoint element
recursivly call the same function for the element after the midpoint element and element n
That will evenly divide up the time available within the constraints of the planes scheduled windows.
Once you have roughly evenly spaced windows, select the smallest window and test it with its neighboring planes to see if they can shift some to expand the smallest window. Repeat this process until the smallest window can't shift a significent amount.

Related

Ways to reach the start city using n trips [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
In some programming contest, I saw this question:
A person wants to travel some cities and come back to the city where
he/she started. Total 5 cities are present and each city is connected
to its adjacent city i.e.: c1 - c2, c2 - c3, c3 - c4, c4 - c5, c5 -
c1. The person will start the journey from city 1. Also, the person
has some limited number of trips to use for traveling. Traveling from one city to another costs him/her 1 trip. We need to find the
total number of ways a person can travel the given cities and come
back to city 1 using the allocated number of trips.
Example:
Input: 4
(means 4 trips are allowed)
Output: 6
(As the output can be large, so it should be modulo 10^9+7)
the possible ways are:
1-2-1-2-1
1-2-1-5-1
1-5-1-2-1
1-5-1-5-1
1-2-3-2-1
1-5-4-5-1
If the question has limits on the number of trips to be less than 10^9 then its easy to solve as the problem has optimal substructure and overlapping subproblems. But the constraint given was 1<=n<=10^18. I couldn't initialize an array with a dimension that long, so couldn't apply dp. Please help me on how to solve this using dp. Or is this question just a permutation or combinations type of question?
Thanks.
I would suggest:
Store the number of ways to reach each city in a vector
Work out a matrix that allows you to update this vector by 1 step
Raise the matrix to the power n using binary exponentiation
Multiple this power matrix by the starting vector (1,0,0,0,0)
Read off in entry 1 the number of ways to reach city 1 after n steps
(edit)
Sorry read your question a bit too fast.
If all cities are connected then this is a simple permutation problem.
If not you can see it as a graph problem and solve it with an extended breadth first search that caps off as soon as you have reached the limit of possible trips.
This problem is purely mathematical; the answer is a mathematical formula which, once computed on paper, you just plot in your program.
You can reach the initial point either by going back and forth (requiring a multiple of 2 steps), or by doing complete circles(requiring a multiple of 5 steps). Thus you need to check the divisibility of n with 2 and 5, or, to put it in a mathematical form, check if n=2*k or n=5*q. We will compute the number of paths independently for the 2 cases, but if n is divisible with both 2 and 5, we will add the two results (since n steps can be done in both ways, either as a multiple of 2 or multiple of 5).
If n=5*q, we will do our n steps as q cycles of 5 steps. Each cycle can be in either direction, clockwise or counter clockwise. For the first cycle, there are 2 possibilities (the 2 directions), for the second cycle, another 2 possibilities, independent of the previous cycle, and so on. Thus, the number of paths is 2*2*2... = 2q .
If n=2*k, we will do our n steps as k back-and-forth paths (one step forward, one step backward). For each of these k paths, there are two directions to go, thus, for k closed-paths, there are 2k paths.
Note: I have given the name back-and-forth path, or closed path, for paths such as 1-2-1. Actually, from the graph theory perspective, they are cycles too, but i did not name them cycles as not to confound them with the 1-2-3-4-5-1 cycles.
The above computation, however, does not take into account the paths such as 1-2-3-2-1, but only 1-2-1-2-1, or 1-2-1-5-1. I am still working on that> I will post this answer the way it is right now as to give inspiration on how the computation might look like.
Another aspect to take into account is the number of ways we could write n as 2*a + 5*b, giving 2a * 5b paths. I think n=2*a+5*b is a dyophantic equation.

Optimal Edge Weights

There is a state (territory) which is a tree rooted at node 1. All the cities (numbered from 1 to N+1)
in this state are connected via bidirectional roads. You have to add toll tax on each road. There are N roads which connect the cities of the state. You have to assign toll taxes on the roads so as to maximize the function Toll described below:
for(i=1;i<=number of cities;i++)
{
for(j=i+1;j<=number of cities;j++)
{
toll+=(toll required to pay to travel from i to j)
}
}
You have to maximize the toll tax. Assign the roads by toll taxes from the given array A(using each value exactly once). Find the maximum toll obtained.
Input Format:
First line contains
N and an integer whose value is always 2.
Then,
N roads follow containing 2 integers u and v, denoting the cities
between which the road is.
Next line contains N space separated values denoting elements of array A.
Output Format
Print the maximum toll which can be obtained.
Input Constraints
1≤N≤2∗10^5
1≤A[i]≤1000
1≤u,v≤N+1
Sample Input
2 2
1 3
2 3
5 7
Sample Output
24
Explanation
Assign 5 to edge (1- 3) and 7 to edge (2 - 3). This leads to an maximum toll tax of 24.
First, when you look at your Toll function code and Sample Input, then you'll see that this function counts just paths:
from 1 to 3
from 2 to 3
but not 3 to 1
and not 3 to 2,
because j is always more than i, so this leads us that 24 is incorrect answer (or you have incorrect Toll) function.
Second, according to the task (but I believe it just was described wrong) the answer will be always equal to sum of elements from array A, because the task sounds like : put elements to a symmetric matrix and then calculate a sum above (or below) a diagonal, but it is going to be all of the same elements from array A.
The Question you asked belongs to Graph.
Three cities are given from 1 -> 3. If you randomly assign values from A[] and use that in the toll function you will get the following output:
Assume you assigned 5 to Edge 1-3, and 7 to edge 2-3,
The graph would be like 1------3------2
Then According to the toll function, you will get the following routes:
1-2 === 7 + 5 = 12
1-3 === 5
2-3 === 7
So , the total toll would be = 12+5+7 = 24.
Hence, you need to first construct the graph . then assign the tolls randomly and find toll money for all the possible combinations.
or else,
you can use concept of Minimum Spanning Tree for Graph. You just need to inverse the use of kruskal or Prim's algorithm to find a route with maximum toll
PS: The meaning of bi-directional road is that suppose your first for loop starts from 3 and second for loop starts from 1, then you can also go 3->1 whose toll would be same as you used before for 1->3.
Hope this helps. :)

Find the lowest sum path from 2d Array

Just thinking about the one algorithm below is the statement for that
Given a matrix, with each node having a value. You start from 0,0 and have to reach n,m. From i,j you can either go to i+1,j or i,j+1. When you step on each block, the value on that block gets added to your current score. What’s the minimum initial score you must carry so that you can always reach n,m(through any possible path) having positive score at the end.
Eg:
Matrix -> 2 3 4
-5 -6 7
8 3 1
Ans -> 6 – for path 2,-5,-6,3,1 we need initial score of 6 so that when we land on 1, we have a positive score of 1
So I can do this using brute force and Dynamic programming, but still thinking for approach which could be better then this, please share ur thoughts, just thoughts/idea I do not need implementation, as I can do this.
There's many search algorithm, i encourage you reading these Wikipedia pages :
https://en.wikipedia.org/wiki/Pathfinding
https://en.wikipedia.org/wiki/Tree_traversal
One possible solution, is to transform the array to graph and apply shortest paths algorithms to it, another solution is to use some IA algorithms such as A*.
Link to Wikipedia for A* (prounced A Star) :
https://en.wikipedia.org/wiki/A*_search_algorithm

How to reduce the time complexity of bucket filling program?

I was solving a problem which states following:
There are n buckets in a row. A gardener waters the buckets. Each day he waters the buckets between positions i and j (inclusive). He does this for t days for different i and j.
Output the volume of the waters in the buckets assuming initially zero volume and each watering increases the volume by 1.
Input: first line contains t and n seperated by spaces.
The next t lines contain i and j seperated by spaces.
Output: a single line showing the volume in the n buckets seperated by spaces.
Example:
Input:
2 2
1 1
1 2
Output:
2 1
Constraints:
0 <= t <= 104; 1 <= n <= 105
I tried this problem. But I use O(n*t) algorithm. I increment each time the bucket from i to j at each step. But this shows time limit error. Is there any efficient algorithm to solve this problem. A small hint would suffice.
P.S: I have used C++ and Java as tags bcoz the program can be programmed in both the languages.
Instead of remembering the amount of water in each bucket, remember the difference between each bucket and the previous one.
have two lists of the intervals, one sorted by upper, one by lower bound
then iterate over n starting with a volume v of 0.
On each iteration over n
check if the next interval starts at n
if so increase v by one and check the next interval.
do the same for the upper bounds but decrease the volume
print v
repeat with the next n
I think the key observation here is that you need to figure out a way to represent your (possibly) 105 buckets without actually allocating space for each and every one of them, and tracking them separately. You need to come up with a sparse representation to track your buckets, and the water inside.
The fact that your input comes in ranges gives you a good hint: you should probably make use of ranges in your sparse representation. You can do this by just tracking the buckets on the ends of each range.
I suggest you do this with a linked list. Each list node will contain 2 pieces of information:
a bucket number
the amount of water in that bucket
You assume that all buckets between the current bucket and the next bucket have the same volume of water.
Here's an example:
Input:
5 30
1 5
4 20
7 13
25 30
19 27
Here's what would happen on each step of the algorithm, with step 1 being the initial state, and each successive step being what you do after parsing a line.
1:0→NULL (all buckets are 0)
1:1→6:0→NULL (1-5 have 1, rest are 0)
1:1→4:2→6:1→21:0→NULL (1-3 have 1, 4-5 have 2, 6-20 have 1, rest have 0)
1:1→4:2→6:1→7:2→14:1→21:0→NULL
1:1→4:2→6:1→7:2→14:1→21:0→25:1→NULL
1:1→4:2→6:1→7:2→14:1→19:2→21:1→25:2→28:1→NULL
You should be able to infer from the above example that the complexity with this method is actually O(t2) instead of O(n×t), so this should be much faster. As I said in my comment above, the bottleneck this way should actually be the parsing and output rather than the actual computation.
Here's an algorithm with space and time complexity O(n)
I am using java since I am used to it
1) Create a hashset of n elements
2) Each time a watering is made increase the respective elements count
3) After file parsing is complete then iterate over hashset to calculate result.

Java permutations of offsets

Had a question regarding generating a list of 10-digit phone numbers on a PhonePad, given a set of possible moves and a starting number.
The PhonePad:
1 2 3
4 5 6
7 8 9
* 0 #
Possible moves:
The same number of moves a Queen in chess can make (so north, south, east, west, north-east, north-west, south-east, south-west... n-spaces per each orientation)
Starting number: 5
So far I have implemented the PhonePad as a 2-dimensional char array, implemented the possible moves a Queen can make in a HashMap (using offsets of x and y), and I can make the Queen move one square using one of the possible moves.
My next step is to figure out an algorithm that would give me all 10-digit permutations (phone numbers), using the possible moves in my HasMap. Repetition of a number is allowed. * and # are not allowed in the list of phone numbers returned.
I would imagine starting out with
- 5555555555, 5555555551, 5555555552... and so on up to 0,
- 5555555515, 5555555155, 5555551555.. 5155555555.. and with the numbers 2 upto 0
- 5555555151, 5555551515, 5555515155.. 5151555555.. and with numbers 2 upto 0
... and so on for a two digit combination
Any suggestions on a systematic approach generating 10-digit combinations? Even a pseudocode algorithm is appreciated! Let me know if further clarification is required.
Thanks in advance! :)
In more detail, the simplest approach would be a recursive method, roughly like:
It accepts a prefix string initially empty, a current digit (initially '5'), and a number of digits to generate (initially 10).
If the number of digits is 1, it will simply output the prefix concatenated with the current digit.
If the number of digits is greater than 1, then it will make a list of all possible next digits and call itself recursively with (prefix + (current digit), next digit, (number of digits)-1 ) as the arguments.
Other approaches, and refinements to this one, are possible of course. The "output" action could be writing to a file, adding to a field in the current class or object, or adding to a local variable collection (List or Set) that will be returned as a result. In that last case, the (ndigits>1) logic would have to combine results from multiple recursive calls to get a single return value.

Categories