My solution is O(N*P) and will most likely get a TLE. But right now I am not able to figure out why it is giving a WA. The approach that I follow is :
I Sort the array, keeping track of the indices.
For query indices i1 and i2, I look for their appropriate positions in the sorted array.
Starting from x-position of frog at index i1 I move till I reach the x-position of frog at index i2, for each adjacent pair of frogs between frogs at index i1 and i2 I check if pos[i+1]-pos[i]<=k.
If I am able to reach the position of the frog at index i2 , I report Yes otherwise No.
Can any expert out there help me with this solution. Its giving WA. I implemented pseudo-code given in Editorial, but not working. : CodeChef: Practical coding for everyone
@all
can u please provide the test case for which my code gave TLE?? CodeChef: Practical coding for everyone. I checked even the worst case but my code gave correct output within the time limit. Any suggestions for tricky test case ??
problem => passed the test case, now unable to identify where the problem is
my approach => made 2 vectors, one storing the original input and other storing the input after sorting, then ,then iterated from starting frog to target frog in the sorted vector and kept checking that the consecutive distance is less then k
For those who are solving treating frogs as nodes and are imagining an edge between two graphs , if they can communicate ; you need not use matrix or list to store the graph. You can find the different components as follows :
Sort the frogs according to their position on x axis and maintain the indices.
Then, just use the following thing. :
compo=1;
component[a[0].ind]=1;
for(i=1;i<n;i++)
{
if(a[i].val-a[i-1].val<=k)
component[a[i].ind]=compo;
else
component[a[i].ind]=++compo;
}
2 frogs can communicate iff they are part of same component.
Can anyone tell me why the algorithm given below gives TLE…?
let all a[i] form the nodes of an undirected graph.
create a c++ set for all unvisited nodes.(initially containing all a[i])
initialize vis[] by all -1
now, call dfs for all nodes having vis[node]==-1
& set vis[node]=caller function to ensure that vis[node] will have same value for all nodes forming a connected component.
In dfs, recur for all nodes currently in unvisited(set) which have abs(a[i]-node)<=k.
Finally, for each query x and y:
if(vis[x]==vis[y])–>yes
else–>no