Table of Contents

ExplanationImplementation

Explanation

We can turn this into a graph problem, or more precisely, a tree. Let's add an edge from uu to vv if the maximum length of the subarray that starts at vv has to end at u1u-1, and so the next subarray must start at uu. Remember the array is cyclic, so uu is not necessarily greater than vv. 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 kk. 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 nn elements.

Implementation

Time Complexity: O(nlogn)\mathcal O(n \log n)

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 = 200001
LOG = 20
# next[i][j] stores the start point of the next
# 2^j'th subarray if we choose this subarray starting at i
nxt = [[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!