Explanation
We can turn this into a graph problem, or more precisely, a tree. Let's add an edge from to if the maximum length of the subarray that starts at has to end at , and so the next subarray must start at . Remember the array is cyclic, so is not necessarily greater than . This can be found using basic two pointers. We can iterate through the array with our left pointer and increment our right pointer if the sum between the two pointers is less than or equal to . This will ensure that the subarray starting at the left pointer is as big as possible.
We can use binary lifting for each possible starting position to determine the number of jumps required to cover exactly elements.
Implementation
Time Complexity:
C++
#include <iostream>const int MAX_N = 2e5 + 1;const int LOG = 20;/** next[i][j] stores the start point of the next* 2^j'th subarray if we choose this subarray starting at i*/int nxt[2 * MAX_N][LOG];
Python
Warning!
Submit the solution in PyPy3 to avoid TLE.
MAX_N = 200001LOG = 20# next[i][j] stores the start point of the next# 2^j'th subarray if we choose this subarray starting at inxt = [[0] * LOG for _ in range(2 * MAX_N)]n, k = map(int, input().split())arr = list(map(int, input().split()))
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!