我是用DP做的。因为可以看到所有人的代码,所以把第一名的代码下载来看了看,他的也是DP。
后来看到官方的解答,其实用贪心+hash可以达到O(n)的效率。
rem的代码
我自己的代码
官方解答摘要
Working in the opposite direction, (*) is all we need to achieve; as long as you can partition the list of queries into such segments, it corresponds to a plan of saving the universe. You don't even care about which engine is used for one segment; any engine not appearing as a query on that segment will do. However, you might sometimes pick the same engine for two consecutive segments, laughing at yourself when you realize it; why don't I just join the two segments into one? Because your task is to use as few segments as possible, it is obvious that you want to make each segment as long as possible.
This leads to the greedy solution: Starting from the first query, add one query at a time to the current segment until the names of all S search engines have been encountered. Then we continue this process in a new segment until all queries are processed.
贪心+hash的代码