From last couple of days I am seeing that people are asking same questions related to LOC July2017 again and again. I have answered all of them here or there, So Here I am just attaching link of questions where I have already answered them because official editorial is taking too much time. Hope It will help people:
Problem 1: Boss and his Brother BOSSLOSS
There are two ways from which this problem can be approached:
-
Use simple inequality method and solve this quadratic as i(i+1)/2 <= m => i^2+i-2m <= 0 ; You can follow my solution here.
-
Second approach can be using binary search over [1,10^18] for n. Assume you answer is n (mid value in range) then simply calculate n*(n+1)/2 if it’s less than m then move lower pointer if greater then move upper pointer, then choose mid point again, until lower and upper value are equal are equal.
lower = 1 upper = 10^18 mid = None while(upper - lower > 1): mid = (lower+upper)/2 if mid*(mid+1)/2 < m: lower = mid elif mid*(mid+1)/2 > m: upper = mid else: break print mid
I am not sure if this code is taking some corner cases… But it’s pretty much gist of what I was saying in 2nd approach.
Here I am using DP to solve this problem.
At every point person can either come from previous checkpoint or it’s similar last checkpoint. here I am iterating through string and taking minimum of both cost:
-
Cost to come from last element = costMap[ s[i-1] ] + abs( ord(s[i]) - ord(s[i-1]) )
-
Cost to come from similar last element, costMap[ s[i] ]
If same element has not come till now then he can only come from last element so cost would be: costMap[ s[i-1] ] + abs( ord(s[i]) - ord(s[i-1]) ), same as 1
and hence answer would be equal to cost of last element in string.
for _ in range(input()):
s = raw_input()
l = len(s)
costMap = {}
costMap[s[0]] = 0
for i in range(1,l):
if not(s[i] in costMap):
costMap[s[i]] = costMap[s[i-1]] + abs(ord(s[i])-ord(s[i-1]))
else:
costMap[s[i]] = min(costMap[s[i]], costMap[s[i-1]] + abs(ord(s[i])-ord(s[i-1])))
print costMap[s[-1]]
Problem 3: Amit And Nitin AMITNITI
Just click on above link and find my solution in answers.
Problem 4: Region of Calabria MAAFIA (I have added another explanation below in answers for this problem)
Problem 5: Magical Cave And Horse CAVECOIN
Just click on above link and find my solution in answers.
Here are my codes for different problems, if it helps:
Problem 1: Boss and his Brother BOSSLOSS
Problem 3: Amit And Nitin AMITNITI
Problem 4: Region of Calabria MAAFIA
Problem 5: Magical Cave And Horse CAVECOIN This solution is for 50 Points, for explanation for 100 Points you can follow this link where I have tried to explain it.
You have any doubt regarding above problems and need an explanation for same, You can ask them below…