Recently I read a problem on trees But I was finding difficulty in approaching this problem. Here is problem:
There is country with n cities (2 to 10^5) and (n-1) bidirectional roads, such that It is possible to travel between any pair of cities. We have 1 magic Truck which can travel between cities but It will take 1 unit of time (if it's loaded) and 0 unit time (if not loaded) in traveling between adjacent cities, and can hold at max 1 unit of product.
Now You can have a customer in any city who requires exactly 2 units of products and cannot wait more than 2 units of time.
Now question is, we have to minimise total number of storages with given restrictions:
- A city cannot have more than one storage.
- A storage can only store 1 unit of product.
Assign Storages in country so that you can fill atleast first order on time. Given that order can be placed in any city.
Time Limit: 1sec
What I have tried:
Worst approach I can think is Brute force. Try to place storage in every city(2^n possibilities) and check if every city order can be fulfilled with help of neighbouring cities. But Time Complexity of this will be (n*2^n). So will not work at all.
Second approach I am thinking is using DP on trees somehow. And I am also not sure If this will be optimal. From above problem I can ensure that leaves should have 1 storage for sure. And I was thinking DP like, start from root and check if children can help in fulfilling it's order and assign storage to that city accordingly, With base case on leaves. But problem Here is that children can also fulfil order from parent so it's making circular loops. So, It did not help me too.
Last approach I was thinking to apply binary search on answer itself. As answer can lie between(1,n) then answer may be found in nLog(n) order. But again problem is, I could not think an optimal way to assign storages in cities with given number of storages.
So, Thats it.. I was trying hard but could not solve this. Any help would be appreciated. :)
Note: I don't know why they make problem statement so complicated like this. They could easily explain problem in much simpler way. Resulting I cannot find this problem on web any more. It was somewhere on codeforces I guess.