To begin with, you are given a square grid map of size **N x N**, detailing the number of people, **C** residing in each grid segment. Since constructing your tracks would require all inhabitants of the utilized land to relocate, you are to decide on a potential railway connecting train stations **A** and **B**, with the coordinates () and () respectively, such that the number of people forced to relocate are kept to a minimum and output that number. Do note that there may be certain areas in which you cannot build your train tracks (e.g. unstable land, hills etc.).

You are also reminded that you cannot build diagonal train tracks and only build in the 4 main directions (e.g. left, right, up, down).

**Problem Source : MCO 2015**

**Input**

Line 1: An integer **N**, the length of the square grid of the map.

Line 2: Four integers and which signifies the x and y-coordinates (from top-left to bottom-right) of the two stations A and B. You will be guaranteed that the two train stations will be situated at distinct locations.

Line 3 to (N+2): **N** integers with a value, **C** each detailing the number of inhabitants of a particular area and separated by spaces. Areas in which you are not allowed to build train tracks on will be given a value of -1.

**Output**

A single line stating the minimum number of inhabitants that will have to be relocated. Output -1 if it is impossible to construct the tracks without building on the areas in which you are not allowed to build tracks.

**Constraints**

- Time Limit : 1s
- Memory Limit : 64 MB

**Sample Input**

5 1 3 5 4 10 30 20 50 10 10 20 -1 25 10 99 10 -1 10 10 10 10 -1 10 10 10 10 -1 99 12

**Sample Output**

363

**Explanation**

The path is [99, 10, 10, 30, 20, 50, 25, 10, 10 ,99] with sum of cost 363.

**Solution**

The idea is to explore every neighboring nodes from the starting points. Each time, update their data, store them into a priority queue and mark them as visited. Using this method, every visited node will be in its lowest possible cost. Repeat this steps until the ending node is reached or the entire graph has been visited.

**C++**

#include <cstdio> #include <queue> using namespace std; struct node{ long long cost; int x, y; bool v; }; class CompareCost{ public: bool operator()(node a, node b){ if (a.cost > b.cost) return true; else return false; } }; node a[400][400]; priority_queue< node, vector<node>, CompareCost > pq; int N, Ax, Ay, Bx, By, i, j; node k; int main(){ scanf("%d%d%d%d%d", &N, &Ax, &Ay, &Bx, &By); Ax--; Ay--; Bx--; By--; for (i=0; i<400; i++){ for (j=0; j<400; j++){ a[i][j].v = 1; // 1 for cannot be visited } } for (i=0; i<N; i++){ for (j=0; j<N; j++){ scanf("%lld", &a[i][j].cost); a[i][j].x = j; a[i][j].y = i; if (a[i][j].cost != -1) a[i][j].v = 0; } } pq.push(a[Ay][Ax]); a[Ay][Ax].v = 1; while (!pq.empty()){ if (a[By][Bx].v) break; k = pq.top(); pq.pop(); if (k.y+1 < N && !a[k.y+1][k.x].v){ a[k.y+1][k.x].cost += k.cost; pq.push(a[k.y+1][k.x]); a[k.y+1][k.x].v = 1; } if (k.y-1 >= 0 && !a[k.y-1][k.x].v){ a[k.y-1][k.x].cost += k.cost; pq.push(a[k.y-1][k.x]); a[k.y-1][k.x].v = 1; } if (k.x+1 < N && !a[k.y][k.x+1].v){ a[k.y][k.x+1].cost += k.cost; pq.push(a[k.y][k.x+1]); a[k.y][k.x+1].v = 1; } if (k.x-1 >= 0 && !a[k.y][k.x-1].v){ a[k.y][k.x-1].cost += k.cost; pq.push(a[k.y][k.x-1]); a[k.y][k.x-1].v = 1; } } if (a[By][Bx].v && a[Ay][Ax].cost != -1){ printf("%lld",a[By][Bx].cost); } else printf("%d",-1); return 0; }

]]>

- Contiguous subarray
- Non-contiguous (not necessarily contiguous) subarray.

Empty subarrays / subsequences should not be considered.

**Problem Source : Hackerrank**

**Input**

First line of the input has an integer . cases follow.

Each test case begins with an integer . In the next line, integers follow representing the elements of array .

**Output**

Two, space separated, integers denoting the maximum contiguous and non-contiguous subarray. At least one integer should be selected and put into the subarrays (this may be required in cases where all elements are negative).

**Constraints**

**Sample Input**

2 4 1 2 3 4 6 2 -1 2 3 4 -5

**Sample Output**

10 10 10 11

**Explanation**

In the first case:

The max sum for both contiguous and non-contiguous elements is the sum of ALL the elements (as they are all positive).

In the second case:

[2 -1 2 3 4] –> This forms the contiguous sub-array with the maximum sum.

For the max sum of a not-necessarily-contiguous group of elements, simply add all the positive elements.

**Solution**

It would be relatively easier if the problem allows an empty subarray. Then, we could simply apply **Kadane’s Algorithm**, an algorithm to find the *maximum subarray* with runtime efficiency.

**Pseudocode**

tmax = smax = 0 for x in A: tmax = max(0 , tmax + x) smax = max(tmax , smax) print smax

**Properties of a maximum subarray**

- It’s either empty or consists of elements with positive summation.
- It only starts and ends with a positive number.
- The absolute value of the negative number in the maximum subarray is smaller than the sum of elements at its left.

With these properties in hand, the motivation behind Kadane’s Algorithm is clear. `tmax`

looks for all positive contiguous sum of the array till the point `x`

. When `tmax`

is negative, it violates the third property of a maximum subarray. Hence, it starts the sum from 0 again and continue searching for positive contiguous segments. Everytime `tmax`

has a new value, it is compared with `smax`

to check if it’s the largest sum so far.

The problem, however, is that empty array is not allowed. Kadane’s Algorithm returns 0 when all the elements are negatives instead of the largest negative numbers. Fortunately, a slight variation of Kadane’s Algorithm can solve the problem.

tmax = smax = A[0] for i = 1 to N-1: tmax = max(A[i] , tmax + A[i]) smax = max(smax , tmax) print smax

In this variation, `tmax`

compares the current element with the contiguous sum. If the contiguous sum is smaller than the current element, it means that the previous contiguous sum is negative, so we only have to pick the current element at the moment. After we iterate through the array, if all of its elements are negatives, `smax`

will return the largest negative element.

The other problem is to find the maximum sum of a non-contiguous subarray. We only have to take the sum of all positive integers in the array. If all of its elements are negatives, return the largest negative element ( Hint : `smax`

). In the following code, the maximum sum of a non-contiguous subarray is denoted as `pmax`

.

**C++**

#include <iostream> using namespace std; int max(int a, int b){ return (a > b ? a : b); } int A[100001]; int main(){ int T; cin >> T; int N, smax, tmax, pmax; for (int i=0; i<T; i++){ cin >> N; cin >> A[0]; smax = tmax = A[0]; pmax = max(0, A[0]); for (int j=1; j<N; j++){ cin >> A[j]; tmax = max(A[j], tmax + A[j]); smax = max(smax, tmax); pmax += max(0, A[j]); } cout << smax << " " << (smax < 0 ? smax : pmax); cout << endl; } return 0; }

]]>

We will analyze every piece of the conversation. Always remember : Albert knows the *month*, Bernard knows the *day*.

**Albert : I don’t know when Cheryl’s birthday is.**

This is obvious. No matter what month he gets, he couldn’t possibly know Cheryl’s birthday as they are more than one date in each month. We cannot get any information from here.

**Albert : I know that Bernard does not know too.**

Bernard knows Cheryl’s birthday if and only if the day he got only occurs once among the possible dates, which in this case 19 and 18. The dates that have 19 or 18 in it are May 19 and June 18. Since Albert is pretty sure that Bernard doesn’t know Cheryl’s birthday, *the month he received must not be May nor June.*

Remaining dates : July 14, July 16, August 14, August 15, August 17.

**Bernard : At first I don’t know when Cheryl’s Birthday is, but know I know.**

Remember that Bernard also knows what we’ve concluded (he’s intelligent!). After he get the conclusion, he is then confident about Cheryl’s birthday. Again, Bernard knows Cheryl’s birthday if and only if the day he got only occurs once among the possible dates, which is 15, 16, 17.

Remaining dates : July 16, August 15, August 17.

**Albert : Then I also know when Cheryl’s Birthday is.**

Albert is also very clever, and his information (remaining dates) are as same as ours. Among the dates, there is only one with July, but two with August. He couldn’t know which is Cheryl’s birthday if the month he received is August. Hence, *the month is July*.

Cheryl’s birthday is **July 16**!

]]>

During lunch time, dirty plates are passed to Linas through a small window. There are different sizes of plates, and Linas sorts the plates to different piles. When Linas gets a new plate, he washes it, quickly dries it and then, depending on the size of the plate, places it on the appropriate pile.

Since there’s not much room in the kitchen, Linas keeps his coffee pot on top of a pile of plates. If Linas wants to place a new plate on a pile with the coffee pot, he has to move the coffee pot to another pile.

Linas can’t stop thinking: “if I knew the order in which plates arrive, I could move the coffee pot less often.” Can you help Linas solve this task?

**Task**

Given the order of the plates that are passed to Lines, find the smallest possible number of coffee pot moves. At the beginning the pot can be placed on any pile.

**Input**

The first line contains two integers: the number of plates and the number of piles

.

Each of the next lines contains a single integer , the pile where -th plate has to be placed. These numbers are provided in the order of Linas getting the plates.

**Output**

Output a single integer – the smallest possible number of coffee pot moves Linas would have to make while washing the dishes.

**Sample Input**

8 3 3 1 2 1 1 3 3 2

**Sample Output**

2

The minimum number of coffee pot moves is 2. Before he starts his work, Linas can put the coffee pot on the first pile, and after washing the second plate – move the pot to the third pile. After washing the sixth plate, Linas should move the pot back to the first pile.

It is not possible to finish the job with fewer coffee pot moves, however the same result can be achieved differently.

Problem Source : Lithuanian Olympiad in Informatics

Solution

#include <iostream> #include <vector> #include <algorithm> #include <string.h> using namespace std; int main(){ int N, K; cin >> N >> K; // create vector vector<int> dish; int d; for (int i=0; i<N; i++){ cin >> d; dish.push_back(d); } // remove similar consecutives vector<int>::iterator it = unique(dish.begin(), dish.end()); dish.resize(distance(dish.begin(), it)); // start search bool pile[K+1]; memset(pile, 0, sizeof(pile)); int move = 0; int full = 0; for (it = dish.begin(); it != dish.end(); it++){ if (full == -1){ full = 0; move++; } if (pile[*it] == 0){ full++; pile[*it] = 0; } if (full == K-1){ full = -1; memset(pile, 0, sizeof(pile)); } } cout << move << endl; return 0; }

]]>

In each operation, you can swap any two numbers in A.

Your task is to determine the least number of operations needed to transform A to B.

**Input**

- The first line of the input contains an integer N, representing the size of arrays A and B.
- The second line contains the elements of the array A, where consecutive elements are separated by a single space.
- The third line contains the elements of the array B, where consecutive elements are separated by a single space.

**Output**

Output the minimum number of operations needed to transform A to B.

**Constraints**

- Time Limit: 1s
- Memory Limit: 64MB
- 1 ≤ N ≤ 1,000,000

**Sample Input**

4 1 4 2 3 4 3 1 2

**Sample Output**

3

The 3 swap operations to transform [1,4,2,3] into [4,3,1,2] are:

Swap 1, 4

Swap 2, 3

Swap 1, 3

**Problem Source : MCO 2014**

**Solution :**

#include <iostream> using namespace std; void s(int &a, int &b){ a = a + b; b = a - b; a = a - b; } int main(){ int N; cin >> N; int A[N+1]; for (int i=1; i<=N; i++){ cin >> A[i]; } int X[N+1]; for (int i=1; i<=N; i++){ cin >> X[A[i]]; } int Y[N+1]; for (int i=1; i<=N; i++){ Y[X[i]] = i; } int cnt = 0; for (int i=1; i<=N; i++){ if (X[i] != i){ cnt++; s(X[i], X[Y[i]]); s(Y[X[i]], Y[X[Y[i]]]); } } cout << cnt; return 0; }

The problem statement is pretty straightforward, but the solution was harder than I thought, since the time efficiency of a brute-force solution is .

My approach is to rearrange sequence `A`

to an ascending order, and the positions of elements in sequence `B`

should also follow their responding element in sequence `A`

. For example, instead of

1 4 2 3 4 3 1 2

we rearrange it to

1 2 3 4 4 1 2 3

In my solution, the second sequence is stored in `X`

(line 21 ~ 24). With this, we can compare sequence `X`

only by index :

for (int i=1; i<=N; i++){ if (X[i] != i){ // do something } }

When we found out that the element in `X`

is not same with its responding index, we should find for the right element to swap with it. The problem is, where and how do we find the right element to swap? For example in the first case, we know that `4`

should be changed to `1`

, but how do we find the position of `1`

?

Of course, you can scan through the entire sequence, but that gives you a time efficiency of . The better idea is to record the index of every element in sequence `X`

. For example in sequence

4 1 2 3

We should record the index of `1`

, which is `2`

(I prefer counting from `1`

instead of `0`

in this problem). Similarly, `2`

will be record as `3`

, and go on we have a sequence

2 3 4 1

In my solution, I named this sequence as `Y`

. With the aid of this sequence, when we found an element in sequence `X`

that differs from its index, we do as follow :

if (X[i] != i){ swap(X[i] , X[Y[i]]); }

After we swapped the two elements, there would also be a minor change in sequence `Y`

, since it recorded the indexes of elements in sequence `X`

. Since the position of `X[i]`

and `X[Y[i]]`

are swapped, their indexes are also swapped.

swap(Y[X[i]], Y[X[Y[i]]]);

Finally, we have all the tools to solve this problem! Good luck problem solving!

]]>

Someone from Gmail could probably answer this better, but here are some factors that make mail search harder in some ways:

- The total contents of the web is actually smaller than the sum of the sizes of the contents of everyone’s gmail. [1] This means it could take more servers to hold all the indexes for mail search than for web search. Yes, users are only searching across their own mail, but servers are still needed to store all the indexes so that every user can do this.
- When you search the web, for the most part, you’re getting the same results for your query as anyone else would get for that query. This means caching works well for web search. Most search engines have a small “hot index” with the most popular content that can handle the majority of queries which is replicated out to lots of local datacenters, giving low average response time even if the worst case is slow.
- Gmail search results are sorted by time and need to be perfect matches, whereas web search results are sorted by relevance and approximations can be made to cut corners.

Also, from an economic perspective, Gmail generates relatively low revenue for Google compared to web search, so they have less of a reason to invest in it.

Why does Gmail take longer to search my inbox than Google takes to search the entire web?

]]>

What were the weights of the pieces?

Spoilers ahead! You might want to try it yourself.

This problem stems from the French mathematician Claude Gaspard Bachet de Meziriac (1581-1638), who solved it in his famous book *Problemes plaisants et dilectables qui se font par les nombres*, published in 1624.

Bachet was the earliest writer who discussed the solution of indeterminate equations by means of continued fractions. He also did work in number theory and found a method of constructing magic squares. Some credible sources also name him the founder of the Bézout’s identity.

*Source : Wikipedia*

We can distinguish the two scales of the balance as the *weight scale* and the *load scale*. On the former we will place only pieces of the measuring weight; whereas on the latter we will place the load and any additional measuring weights. It is necessary to place measuring weights on the load scale. For example, in order to weigh one pound with a two-pound and a three-pound piece, we place the two-pound piece on the load scale and the three-pound piece on the weight scale.

For the sake of explanation, we introduce the term *preponderance*. If two pieces weighing 5 and 10 pounds each are on one scale, and three pieces weighing 1, 3, and 4 pounds each are on the other, we say that these pieces give the first scale a preponderance of 7 pounds.

Suppose that we have a series of measuring weights which enable us to weigh all the integral weights from 1 through *N*, then if we were to chose another measuring weight *P* such that the range of possible weight measurement is maximized, what should be the weight of *P*?

Let the weight of *P* be *X > N*. For the arrangement to measure weight *K*, if we place *P* on the weight scale, this will give the weight scale a preponderance of *X+K*; if we place *P* on the load scale, this will give the load scale a preponderance of *X-K*, which leads to swapping roles between the two scales.

In summary, by adding *P* we can measure weight [*X-N,X+N*]. Since we are able to measure weights [*1,N*] already, to maximize the range we shall greedily merge both ranges, in result having [*1,X+N*]. To achieve this, the lower bound of [*X-N,X+N*] should be followed by the higher bound of [*1,N*], thus the equation:

We will approach this problem using casework (aka *brute-force*). Starting with 1, we will get the following table :

Piece | Weight | Range |
---|---|---|

1 | 1 | 1 |

2 | 3 | 4 |

3 | 9 | 13 |

4 | 27 | 40 |

Their sum is indeed 40, indicates that this is our desired answer.

Bachet’s Weight Problem was generalized by the English mathematician MacMahon. In Volume 21 of the *Quarterly Journal of Mathematics* (1886) MacMahon determined all the conceivable sets of integral weights with which all loads of 1 to *N* lbs can be weighed.

]]>

Lake Natron in Tanzania is one of the most serene lakes in Africa, but it’s also the source of some of the most phantasmagorical photographs ever captured — images that look as though living animals had instantly turned to stone.

The alkaline water in Lake Natron has a pH as high as 10.5 and is so caustic it can burn the skin and eyes of animals that aren’t adapted to it. The water’s alkalinity comes from the sodium carbonate and other minerals that flow into the lake from the surrounding hills. And deposits of sodium carbonate — which was once used in Egyptian mummification — also acts as a fantastic type of preservative for those animals unlucky enough to die in the waters of Lake Natron. The blood-red color of the lake is the result of the photosynthesis of a kind of bacteria. The only type of fish that can survive its deadly alkalinity is *tilapia grahami*.

“No one knows for certain exactly how they die, but the water has an extremely high soda and salt content, so high that it would strip the ink off my Kodak film boxes within a few seconds.” says photographer Nick Brandt.

“I took these creatures as I found them on the shoreline, and then placed them in ‘living’ positions, bringing them back to ‘life,’ as it were,” Brandt wrote, referring to the way he repositioned the animals. “Reanimated, alive again in death.”

Source :

Lake That Turns Animals to Stone? Not Quite

Deadly Lake Waters Turn Birds to Stone

]]>

**Image Credit : wired.com**

Motion in Two Dimensions is a very important topic in Physics. In this post, I am going to demonstrate my strategies for solving this kind of problems. First, we revise the formula we have learnt :

These formulas are useful. However, it may not be the best choice to solve problems using *only* formulas. In fact, equations would be tedious if you do not know how to apply it well.

Before introducing my strategy, I’ll share another useful but not commonly used formula

This formula is used to calculate the displacement of the particle at the -axis for given displacement at the -axis. The derivation of the formula is actually pretty simple.

The partial displacement at the -axis and -axis is respectively

Substitute to the first equation

**Example Problem 0.1 :**

A canon ball is being launched at speed and in respect to the horizontal. If the target is at height , what is the horizontal distance should the canon be placed?

**Solution 0.1 :**

Apply the formula above, we have

Solve the quadratic equation we get or .

**Strategy 1 : Graphic ( 图解法 )**

Graph is a useful tool that is commonly ignored by most students. Solving problems using graphics can help you visualize the problem. The best graph, in my opinion, is the graph, because it can show us two things:

- Displacement – area under the function
- Acceleration – slope of the function

**Example Problem 1.1 :**

Consider the free fall of a particle at position with height . Given that and the time for the particle to travel from to is .

- What is the time traveled from to , in seconds?
- What is the height , in meters?

**Practice Problem 1.2 :**

A particle at rest starts moving with acceleration . Until it reaches the speed , it immediately decelerates with until it stops. The total time consumed is . Prove that:

- The displacement of the particle is .

Discuss your solution here.

一个静止的质点以 的加速度加速至 . 过后，马上以减速度 减速至静止为止。这整个过程共用了 时间。试证：

- 质点的位移为 .

**Strategy 2 : Relative Motion ( 相对运动 )**

This strategy is often used to solve problems that has more than two moving objects involved. The formula of relative motion is :

Once you got the idea, the formula is not necessary to be memorized.

**Example Problem 2.1 :**

A boat can travel at a speed of on still water. A boatman wants to cross a river whilst covering the shortest possible distance. In what direction should he row with respect to the bank if the speed of the water is

Assume that the speed of the water is the same everywhere.

**Practice Problem 2.2 :**

There are two particles at points and respectively. Particle moves upwards at speed while particle moves towards left at speed . What is the minimum distance can they get between them?

Submit your answer here.

**Practice Problem 2.2 :**

A sandstorm wide is heading towards Adam at speed from distance away. Since Adam is infamous for his laziness, he wants to cross the sandstorm running as slow as possible. What is the minimum speed should Adam run without being hit by the sandstorm?

**Practice Problem 2.3 :**

Three small snails are each at a vertex of an equilateral triangle of side . The first sets out towards the second, the second towards the third and the third towards the first, with a uniform speed of . During their motion each of them always heads towards its respective target snail. How much time has elapsed, and what distance do the snails cover, before they meet?

**Practice Problem 2.4 :**

A small ball falling vertically with constant velocity elastically strikes a massive inclined cart moving with a horizontal velocity . What is the rebound velocity of the ball? ( The velocity of the cart doesn’t change after the collision )

Submit your answer here.

**Practice Problem 2.5 :**

Two ships and are originally at a distance from each other depart at the same time from a straight coastline. Ship moves along a straight line perpendicular to the shore while ship constantly heads for ship , having at the each moment same as the latter. After a sufficiently great interval of time the second ship will be following the first one at a certain distance . Find .

Submit your answer here.

**Strategy 3 : Energy Conservation ( 功能原理 ) :**

The Energy Conservation is useful especially when dealing with projectile motion. Energy can be changed from one form to another without losing its total internal energy. In this case, the internal energy of a particle is consists of its kinetic energy and potential energy.

**Practice Problem 3.1**

A ball with mass is thrown upwards with speed . It is given that when the ball reaches its highest point, the work done by surrounding air on the ball is . What is the highest point can the ball reaches?

**Practice Problem 3.2 :**

Christopher accidentally fell inside a cylindrical well of depth 15 meters and radius 8 meters. Jumping from the center of the bottom of the well, what is the minimum launch speed that Christopher needs to achieve, in order to jump out of the well?

Submit your answer here.

**Practice Problem 3.3 :**

A ball slides along a friction-less ramp of length . As it reaches the bottom, it hits the board and slides up along the slope again. If the speed of the ball after the collision is times the speed of the ball just before the collision, find the total distance traveled by the ball when it comes to a complete stop.

Submit your answer here.

That’s all for now. If you have a good strategy, share it with me! Good Luck Problem Solving!

]]>

You might noticed that most of the physics problem I’ve posted are solved symbolically. This is because solving problems symbolically can have many advantages, especially in physics. From my experience, they are :

**Faster**. We spend less time picking up our calculator.**More Accurate**. Rounding up the answer throughout the calculations may lead to a major error at the end. By solving symbolically, we will only need to perform the round-up once when we are finished with the final substitution.**Less Mistake**. It’s very easy to overlook 6 as a 0, especially when you are nervous in your exam. By solving symbolically, we are not likely to make mistakes for substitutions and arithmetic operations.**Stronger Understanding of Problem**. Does acceleration matters in this problem? If the time increased, will it travel further? Since symbolic answers normally looks nice, all these questions can be answered from it! Other than that, we can determine other special cases in the problem.**Reusable**. When you calculated as instead of the problem requirement , you don’t have to solve the problem all over again but substitute the correct value.

Although it’s better solving problems symbolically, it really depends on the type of problem. For example, you won’t want to solve a system of 3 equations with only symbols. Now, let’s look at a typical problem regarding heat transfer, and solve it symbolically.

Two metals and with length and is wielded together. If we constantly heat up the end of metal and to and , what is the temperature of the wielding section of the rod?

( is the thermal conductivity of metal, with unit )

**Solution :**

The wielding section will reaches thermal equilibrium when the heat transferred from metal and is the same. Hence,

With that formula in hand, we only have to substitute the values into their responding variable :

Since this problem often appears as a sub-problem in the UEC exam, it’s worth to memorize it. Next, let’s solve a similar problem, but UEC-leveled.

What is the value of and ?

Consider the heat transfer between metal and ,

Consider the heat transfer between and ,

Solve the two system of equation :

It is true that the only way to be good at problem solving is through solving problems. However, there’s no point doing the same thing over and over. Fully understand the problem is a much better approach.

]]>