Let Them Slide (Codeforces 1208E)
Tags: Implement, data structures

You are given $$$n$$$ arrays that can have different sizes. You also have a table with $$$w$$$ columns and $$$n$$$ rows. The $$$i$$$-th array is placed horizontally in the $$$i$$$-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table.You need to find the maximum sum of the integers in the $$$j$$$-th column for each $$$j$$$ from $$$1$$$ to $$$w$$$ independently.  Optimal placements for columns $$$1$$$, $$$2$$$ and $$$3$$$ are shown on the pictures from left to right. Note that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero.

Input: The first line contains two integers $$$n$$$ ($$$1 \le n \le 10^{6}$$$) and $$$w$$$ ($$$1 \le w \le 10^{6}$$$) — the number of arrays and the width of the table.Each of the next $$$n$$$ lines consists of an integer $$$l_{i}$$$ ($$$1 \le l_{i} \le w$$$), the length of the $$$i$$$-th array, followed by $$$l_{i}$$$ integers $$$a_{i1}, a_{i2}, \ldots, a_{il_i}$$$ ($$$-10^{9} \le a_{ij} \le 10^{9}$$$) — the elements of the array.The total length of the arrays does no exceed $$$10^{6}$$$.

Output: Print $$$w$$$ integers, the $$$i$$$-th of them should be the maximum sum for column $$$i$$$.

Note: Illustration for the first example is in the statement.

Sample Inputs:
3 3
3 2 4 8
2 2 5
2 6 3

2 2
2 7 8
1 -8

Sample Outputs:
10 15 16

7 8

Solution (Python):
import sys
import io
import os
import traceback
from collections import deque
from itertools import accumulate
BUFSIZE = 8192

class FastIO(io.IOBase):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.buffer = io.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(io.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')

def print(*args, **kwargs):
    """"""
    (sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop('end', '\n'))
    if kwargs.pop('flush', False):
        file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
    return sys.stdin.readline().rstrip('\r\n')

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

def read_int_tuple():
    return tuple(map(int, input().split()))

def read_int():
    return int(input())
if 'AW' in os.environ.get('COMPUTERNAME', ''):
    test_no = 1
    f = open('inputs')

    def input():
        return f.readline().rstrip('\r\n')
(n, w) = read_int_tuple()
diff = [0] * (w + 1)
for _ in range(n):
    (l, *A) = read_int_tuple()
    if l == w:
        for i in range(l):
            diff[i] += A[i]
            diff[i + 1] -= A[i]
        continue
    d = w - l
    if d >= l - 1:
        hi = 0
        for i in range(l - 1):
            if hi < A[i]:
                hi = A[i]
            diff[i] += hi
            diff[i + 1] -= hi
        if hi < A[l - 1]:
            hi = A[l - 1]
        diff[l - 1] += hi
        diff[w - l + 1] -= hi
        hi = 0
        for i in range(1, l):
            if hi < A[-i]:
                hi = A[-i]
            diff[w - i] += hi
            diff[w - i + 1] -= hi
    else:
        q = deque([(0, -1)])
        for (i, x) in enumerate(A):
            while q and q[-1][0] <= x:
                q.pop()
            q.append((A[i], i))
            while i - q[0][1] >= d + 1:
                q.popleft()
            hi = q[0][0]
            diff[i] += hi
            diff[i + 1] -= hi
        q = deque([(0, 0)])
        for i in range(1, d + 1):
            x = A[-i]
            while q and q[-1][0] <= x:
                q.pop()
            q.append((A[-i], i))
            while i - q[0][1] >= d + 1:
                q.popleft()
            hi = q[0][0]
            diff[w - i] += hi
            diff[w - i + 1] -= hi
diff.pop()
print(*accumulate(diff))

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque

def slidemax(X, k):
    q = deque([])
    ret = []
    for i in range(len(X)):
        while q and q[-1][1] <= X[i]:
            q.pop()
        deque.append(q, (i + k, X[i]))
        if q[0][0] == i:
            deque.popleft(q)
        if i >= k - 1:
            ret.append(q[0][1])
    return ret
(N, W) = map(int, input().split())
A = [0] * W
s = 0
for _ in range(N):
    (l, *B) = map(int, input().split())
    if l * 2 < W:
        C = slidemax([0] * (l - 1) + B + [0] * (l - 1), l)
        m = max(B + [0])
        s += m
        for i in range(l - 1):
            A[i] += C[i] - m
            A[-i - 1] += C[-i - 1] - m
    else:
        C = slidemax([0] * (W - l) + B + [0] * (W - l), W - l + 1)
        A = [a + c for (a, c) in zip(A, C)]
print(*[a + s for a in A])

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque
(n, w) = [int(i) for i in input().rstrip('\n').split()]
arr = []
tem = []
for i in range(n):
    t = [int(i) for i in input().rstrip('\n').split()]
    tem.append(t[0])
    arr.append(t[1:])
l = [0 for i in range(w)]
wi = [0 for i in range(w + 1)]
for j in range(n):
    st = deque()
    c = w - tem[j]
    for i in range(tem[j]):
        while st and st[0] < i - c:
            st.popleft()
        while st and arr[j][st[-1]] < arr[j][i]:
            st.pop()
        st.append(i)
        if arr[j][st[0]] > 0 or (i >= c and i < w - c):
            l[i] += arr[j][st[0]]
    ind = tem[j]
    while st and arr[j][st[0]] > 0:
        wi[ind] += arr[j][st[0]]
        wi[w - (tem[j] - st[0]) + 1] += -arr[j][st[0]]
        ind = w - (tem[j] - st[0]) + 1
        st.popleft()
curr = 0
for i in range(w):
    curr += wi[i]
    l[i] += curr
print(' '.join((str(e) for e in l)))