Maximum Reduction (Codeforces 1037F)
Tags: Math, combinatorics

Given an array $$$a$$$ of $$$n$$$ integers and an integer $$$k$$$ ($$$2 \le k \le n$$$), where each element of the array is denoted by $$$a_i$$$ ($$$0 \le i < n$$$). Perform the operation $$$z$$$ given below on $$$a$$$ and print the value of $$$z(a,k)$$$ modulo $$$10^{9}+7$$$.function z(array a, integer k):    if length(a) < k:        return 0    else:        b = empty array        ans = 0        for i = 0 .. (length(a) - k):            temp = a[i]            for j = i .. (i + k - 1):                temp = max(temp, a[j])            append temp to the end of b            ans = ans + temp        return ans + z(b, k)

Input: The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 10^6$$$) — the length of the initial array $$$a$$$ and the parameter $$$k$$$.The second line of input contains $$$n$$$ integers $$$a_0, a_1, \ldots, a_{n - 1}$$$ ($$$1 \le a_{i} \le 10^9$$$) — the elements of the array $$$a$$$.

Output: Output the only integer, the value of $$$z(a,k)$$$ modulo $$$10^9+7$$$.

Note: In the first example:   for $$$a=(9,1,10)$$$, $$$ans=19$$$ and $$$b=(9,10)$$$,  for $$$a=(9,10)$$$, $$$ans=10$$$ and $$$b=(10)$$$,  for $$$a=(10)$$$, $$$ans=0$$$. So the returned value is $$$19+10+0=29$$$.In the second example:   for $$$a=(5,8,7,1,9)$$$, $$$ans=25$$$ and $$$b=(8,8,9)$$$,  for $$$a=(8,8,9)$$$, $$$ans=9$$$ and $$$b=(9)$$$,  for $$$a=(9)$$$, $$$ans=0$$$. So the returned value is $$$25+9+0=34$$$.

Sample Inputs:
3 2
9 1 10

5 3
5 8 7 1 9

Sample Outputs:
29

34

Solution (Python):
import sys
readline = sys.stdin.readline

def Cartesian_Tree(lst, maximum=False):
    N = len(lst)
    parents = [None] * N
    stack = []
    for i in range(N):
        prev = None
        if maximum:
            while stack and lst[i] > lst[stack[-1]]:
                prev = stack.pop()
        else:
            while stack and lst[i] < lst[stack[-1]]:
                prev = stack.pop()
        if prev != None:
            parents[prev] = i
        if stack:
            parents[i] = stack[-1]
        stack.append(i)
    graph = [[] for x in range(N)]
    for x in range(N):
        if parents[x] != None:
            graph[parents[x]].append(x)
        else:
            root = x
    return (graph, root)
(N, K) = map(int, readline().split())
A = list(map(int, readline().split()))
mod = 10 ** 9 + 7
(graph, root) = Cartesian_Tree(A, maximum=True)

def cnt(le):
    return (le + le % (K - 1)) * (le // (K - 1) + 1) // 2 % mod
stack = [(0, root, N)]
ans = 0
while stack:
    (l, root, r) = stack.pop()
    if r - l < K:
        ans += sum(A[l:r])
    else:
        ans += A[root] * (cnt(r - l) - cnt(root - l) - cnt(r - root - 1))
        for x in graph[root]:
            if x < root:
                stack.append((l, x, root))
            if root < x:
                stack.append((root + 1, x, r))
ans -= sum(A)
ans %= mod
print(ans)

Solution (Python):
import os, sys
from random import randint, shuffle
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from heapq import heappush, heappop
from functools import lru_cache
from itertools import accumulate, permutations
import math
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, k) = list(map(int, input().split()))
a = list(map(int, input().split()))
stack = []
stack1 = []
l = [-1] * n
for i in range(n):
    while stack and stack[-1] < a[i]:
        stack.pop()
        stack1.pop()
    l[i] = stack1[-1] if stack1 else -1
    stack.append(a[i])
    stack1.append(i)
stack = []
stack1 = []
r = [-1] * n
for i in range(n)[::-1]:
    while stack and stack[-1] <= a[i]:
        stack.pop()
        stack1.pop()
    r[i] = stack1[-1] if stack1 else n
    stack.append(a[i])
    stack1.append(i)
ans = 0
for i in range(n):
    (x, y) = (i - l[i] - 1, r[i] - i - 1)
    if x > y:
        (x, y) = (y, x)
    for j in range(x + 1):
        ans += ((j + y) // (k - 1) - (j - 1 if j > 0 else 0) // (k - 1)) * a[i]
print(ans % (10 ** 9 + 7))

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 1)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        inf = float('inf')

        def I():
            return input()

        def II():
            return int(input())

        def MII():
            return map(int, input().split())

        def LI():
            return list(input().split())

        def LII():
            return list(map(int, input().split()))

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import math
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import merge, heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        class FastIO(IOBase):
            newlines = 0

            def __init__(self, file):
                self._fd = file.fileno()
                self.buffer = BytesIO()
                self.writable = 'x' in file.mode or 'r' not in file.mode
                self.write = self.buffer.write if self.writable else None

            def read(self):
                while True:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    if not b:
                        break
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines = 0
                return self.buffer.read()

            def readline(self):
                while self.newlines == 0:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    self.newlines = b.count(b'\n') + (not b)
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines -= 1
                return self.buffer.readline()

            def flush(self):
                if self.writable:
                    os.write(self._fd, self.buffer.getvalue())
                    (self.buffer.truncate(0), self.buffer.seek(0))

        class IOWrapper(IOBase):

            def __init__(self, file):
                self.buffer = FastIO(file)
                self.flush = self.buffer.flush
                self.writable = self.buffer.writable
                self.write = lambda s: self.buffer.write(s.encode('ascii'))
                self.read = lambda : self.buffer.read().decode('ascii')
                self.readline = lambda : self.buffer.readline().decode('ascii')
        sys.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')

def main():
    mod = 10 ** 9 + 7
    (n, k) = MII()
    nums = LII()
    left = [-1] * n
    right = [n] * n
    stack = []
    for i in range(n):
        while stack and nums[stack[-1]] <= nums[i]:
            right[stack.pop()] = i
        if stack:
            left[i] = stack[-1]
        stack.append(i)
    k -= 1
    ans = 0
    for i in range(n):
        x = i - left[i] - 1
        y = right[i] - i - 1
        if x < y:
            (x, y) = (y, x)
        (u, v, w) = (x // k, y // k, (x + y) // k)
        ans += nums[i] * (u * (u + 1) // 2 * k + u + (v - u) * (x + 1) - (v + w + 1) * (w - v) // 2 * k + (x + y + 1) * (w - v))
    print(ans % mod)
    return
t = 1
for _ in range(t):
    main()