CF1791G2 Teleporters (Hard Version)

Description

The only difference between the easy and hard versions are the locations you can teleport to. Consider the points $ 0,1,\dots,n+1 $ on the number line. There is a teleporter located on each of the points $ 1,2,\dots,n $ . At point $ i $ , you can do the following: - Move left one unit: it costs $ 1 $ coin. - Move right one unit: it costs $ 1 $ coin. - Use a teleporter at point $ i $ , if it exists: it costs $ a_i $ coins. As a result, you can choose whether to teleport to point $ 0 $ or point $ n+1 $ . Once you use a teleporter, you can't use it again. You have $ c $ coins, and you start at point $ 0 $ . What's the most number of teleporters you can use?

Input Format

N/A

Output Format

N/A

Explanation/Hint

In the first test case, you can move one unit to the right, use the teleporter at index $ 1 $ and teleport to point $ n+1 $ , move one unit to the left and use the teleporter at index $ 5 $ . You are left with $ 6-1-1-1-1 = 2 $ coins, and wherever you teleport, you won't have enough coins to use another teleporter. You have used two teleporters, so the answer is two. In the second test case, you go four units to the right and use the teleporter to go to $ n+1 $ , then go three units left and use the teleporter at index $ 6 $ to go to $ n+1 $ , and finally, you go left four times and use the teleporter. The total cost will be $ 4+6+3+4+4+9 = 30 $ , and you used three teleporters. In the third test case, you don't have enough coins to use any teleporter, so the answer is zero.