Basic Dynamic Programming
Given Frog’s location on the X axis and they can communicate their message to another frog only if the distance are less than or equal to K , now you need to answer if given two frogs can communicate or not. Assumption : Frog’s are cooperative in nature and will transfer the message without editing it .
Find for each frog the maximum distance which his message can reach. Two Frogs can only communicate if their maximum distance of communication are same.
You can easily proof by contradiction. Let us assume that there are two frogs 1 and 2 which can communicate but their maximum distances are different. You can easily contradict this , proof is left as an exercise for the reader.
Only Challenge left is to calculate the maximum distance which each frog can message.
The First point to note is that one of the optimal strategy of each frog(say f) will be to send message to it’s nearest frog(say f1) and then it will be the responsibility of the nearest frog to carry it further.
One Line Proof : Frog’s reachable from the f in the direction of f1 is also reachable from f1.
Another point to note is that the frog on the extreme positive side of X axis(i.e Maximum A[i] , say A[j]) can communicate till A[j] + K.
Using these observation , one can use a simple dp to calculate the maximum distance . But how ?
Sort A[i]'s but do not loose the index of frog’s while sorting. Let the sorted array be Frog . Now if Frog[i] can communicate to Frog[i+1] , then Frog[i] can communicate as mcuh distance as Frog[i+1] can communicate.
Pre-Compute ( A , K ): sort(A,A+N); //Sorted in Decreasing Order of X . Max_Distance[A.ind]=A.v+K; for(int i=1;i<N;i++) if((A[i-1].x-A[i].x)<=K) Max_Distance[A[i].ind] = Max_Distance[A[i-1].ind]; else Max_Distance[A[i].ind] = A[i].x + K; Answer ( x , y ): if ( Max_Distance[x] == Max_Distance[y] ): return "Yes" else return "No"
O(N*log(N)), N * logN for sorting N integers.
AUTHOR’S and TESTER’S SOLUTIONS:
Author’s solution to be uploaded soon.