P.S. I feel very sorry that I thought it was a traditional DP problem with only 800B code and didn't realize some participants were not familiar with such kind of problems, so I said it was easy.
Let a[i] be the distance from hill 1 to hill i, s[i]=a+a+…+a[i].
Firstly, we sort the cats by (Ti-a[i]). Then we can divide the cats into P consecutive parts, and plan a feeder for each part. Dynamic Programming can solve this problem.
Let f[i,j] indicates the minimum sum of waiting time with i feeders and j cats.
f[i,j] = f[i-1,k]+a[j]*(j-k)-s[j]+s[k] = a[j]*j-s[j] + f[i-1,k]+s[k]-a[j]*k
That’s O(PM^2). It’ll get TLE.
Let p>q, if p is "better" than q, then:
So we can use Convex hull trick with a queue. Then we get O(MP), which can pass the problem.
Firstly, we solve such a problem: if we can go exactly k,k1,k2……or kp cells forward each step, what cells can we reach?
We divide the H cells into k groups: Group 0,1……k-1. The i-th cell should be in Group (i mod k).
- If we reach Cell x in Group (x mod k), we can also reach Cell (x+kj , 1<=j<=p) in Group ((x+kj)mod k).
- If we reach Cell x in Group (x mod k), we can also reach Cell (x+k) in the same group.
Let D[i] be the minimum cell we can reach in Group i. Then we can reach all the cells which number are bigger then D[i] in Group i.
Regard the groups as points. Regard k,k1,k2……kp as edges. And use a Shortest-Path Algorithm to calculate all D[i].
Notice that there are at most 20 operations of type 1, we are able to run such an algorithm after each of these operations. The total time complexity is O(20*k*20*log(k)) with Dijkstra.
Secondly, we build a binary-heap to solve operations of type 2 and 3.
- Type1 – If a D[i] becomes smaller, we put the new cells we can reach into the heap.
- Type2 – Decrease a value of a node in the heap, or a cell in the “Treasure Cell” array.
- Type3 – Ask the biggest node in the heap and delete it.
These are basic operations of binary-heap. The time complexity is O(NlogN). In C++, you can also use priority_queue from STL and lazy-tags. So we can solve the whole problem in O(400klogk+NlogN).
We only need to find out if “miao.” is a prefix of the sentence, and if “lala.” is a suffix of the sentence. Pay attention to the situation when both conditions are satisfied.