Frog Traveler (Codeforces 1601B)
Tags: DP, shortest paths

Frog Gorf is traveling through Swamp kingdom. Unfortunately, after a poor jump, he fell into a well of $$$n$$$ meters depth. Now Gorf is on the bottom of the well and has a long way up.The surface of the well's walls vary in quality: somewhere they are slippery, but somewhere have convenient ledges. In other words, if Gorf is on $$$x$$$ meters below ground level, then in one jump he can go up on any integer distance from $$$0$$$ to $$$a_x$$$ meters inclusive. (Note that Gorf can't jump down, only up).Unfortunately, Gorf has to take a break after each jump (including jump on $$$0$$$ meters). And after jumping up to position $$$x$$$ meters below ground level, he'll slip exactly $$$b_x$$$ meters down while resting.Calculate the minimum number of jumps Gorf needs to reach ground level.

Input: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the depth of the well.The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le i$$$), where $$$a_i$$$ is the maximum height Gorf can jump from $$$i$$$ meters below ground level.The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le n - i$$$), where $$$b_i$$$ is the distance Gorf will slip down if he takes a break on $$$i$$$ meters below ground level.

Output: If Gorf can't reach ground level, print $$$-1$$$. Otherwise, firstly print integer $$$k$$$ — the minimum possible number of jumps.Then print the sequence $$$d_1,\,d_2,\,\ldots,\,d_k$$$ where $$$d_j$$$ is the depth Gorf'll reach after the $$$j$$$-th jump, but before he'll slip down during the break. Ground level is equal to $$$0$$$.If there are multiple answers, print any of them.

Note: In the first example, Gorf is on the bottom of the well and jump to the height $$$1$$$ meter below ground level. After that he slip down by meter and stays on height $$$2$$$ meters below ground level. Now, from here, he can reach ground level in one jump.In the second example, Gorf can jump to one meter below ground level, but will slip down back to the bottom of the well. That's why he can't reach ground level.In the third example, Gorf can reach ground level only from the height $$$5$$$ meters below the ground level. And Gorf can reach this height using a series of jumps $$$10 \Rightarrow 9 \dashrightarrow 9 \Rightarrow 4 \dashrightarrow 5$$$ where $$$\Rightarrow$$$ is the jump and $$$\dashrightarrow$$$ is slipping during breaks.

Sample Inputs:
3
0 2 2
1 1 0

2
1 1
1 0

10
0 1 2 3 5 5 6 7 8 5
9 8 7 1 5 4 3 2 0 0

Sample Outputs:
2
1 0

-1

3
9 4 0

Solution (Python):
from collections import deque
n = int(input())
a = [0] + list(map(int, input().split()))
b = [0] + list(map(int, input().split()))

def find_path_to_zero():
    paths = {n: (n, n)}
    queue = deque([n])
    curr_min_height = n + 1
    while queue:
        height = queue.popleft()
        if height <= a[height]:
            paths[0] = (height, 0)
            path = []
            curr_node = 0
            count = 0
            while curr_node != n:
                path.append(paths[curr_node][1])
                curr_node = paths[curr_node][0]
                count += 1
            return (count, path[::-1])
        for node in range(curr_min_height - 1, height - a[height] - 1, -1):
            new_height = node + b[node]
            if new_height not in paths:
                paths[new_height] = (height, node)
                queue.append(new_height)
        curr_min_height = min(curr_min_height, height - a[height])
    return (-1, [])
(num_steps, path) = find_path_to_zero()
print(num_steps)
print(*path)

Solution (Python):
import math
import random
import time
import sys, threading
sys.setrecursionlimit(3 * 10 ** 5 + 2)
threading.stack_size(80000000)
from collections import defaultdict
contor = 0
matricea = {}
alfabet = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}
alfabet_2 = {'1': 'a', '2': 'b', '3': 'c', '4': 'd', '5': 'e', '6': 'f', '7': 'g', '8': 'h', '9': 'i', '10': 'j', '11': 'k', '12': 'l', '13': 'm', '14': 'n', '15': 'o', '16': 'p', '17': 'q', '18': 'r', '19': 's', '20': 't', '21': 'u', '22': 'v', '23': 'w', '24': 'x', '25': 'y', '26': 'z'}
from bisect import bisect_left as lower_bound
from bisect import bisect_right as upper_bound

class FenwickTree:

    def __init__(self, x):
        bit = self.bit = list(x)
        size = self.size = len(bit)
        for i in range(size):
            j = i | i + 1
            if j < size:
                bit[j] += bit[i]

    def update(self, idx, x):
        """"""
        while idx < self.size:
            self.bit[idx] += x
            idx |= idx + 1

    def __call__(self, end):
        """"""
        x = 0
        while end:
            x += self.bit[end - 1]
            end &= end - 1
        return x

    def find_kth(self, k):
        """"""
        idx = -1
        for d in reversed(range(self.size.bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < self.size and self.bit[right_idx] <= k:
                idx = right_idx
                k -= self.bit[idx]
        return (idx + 1, k)

class SortedList:
    block_size = 700

    def __init__(self, iterable=()):
        self.macro = []
        self.micros = [[]]
        self.micro_size = [0]
        self.fenwick = FenwickTree([0])
        self.size = 0
        for item in iterable:
            self.insert(item)

    def insert(self, x):
        i = lower_bound(self.macro, x)
        j = upper_bound(self.micros[i], x)
        self.micros[i].insert(j, x)
        self.size += 1
        self.micro_size[i] += 1
        self.fenwick.update(i, 1)
        if len(self.micros[i]) >= self.block_size:
            self.micros[i:i + 1] = (self.micros[i][:self.block_size >> 1], self.micros[i][self.block_size >> 1:])
            self.micro_size[i:i + 1] = (self.block_size >> 1, self.block_size >> 1)
            self.fenwick = FenwickTree(self.micro_size)
            self.macro.insert(i, self.micros[i + 1][0])

    def pop(self, k=-1):
        (i, j) = self._find_kth(k)
        self.size -= 1
        self.micro_size[i] -= 1
        self.fenwick.update(i, -1)
        return self.micros[i].pop(j)

    def __getitem__(self, k):
        (i, j) = self._find_kth(k)
        return self.micros[i][j]

    def count(self, x):
        return self.upper_bound(x) - self.lower_bound(x)

    def __contains__(self, x):
        return self.count(x) > 0

    def lower_bound(self, x):
        i = lower_bound(self.macro, x)
        return self.fenwick(i) + lower_bound(self.micros[i], x)

    def upper_bound(self, x):
        i = upper_bound(self.macro, x)
        return self.fenwick(i) + upper_bound(self.micros[i], x)

    def _find_kth(self, k):
        return self.fenwick.find_kth(k + self.size if k < 0 else k)

    def __len__(self):
        return self.size

    def __iter__(self):
        return (x for micro in self.micros for x in micro)

    def __repr__(self):
        return str(list(self))

def prime_generator(nr_elemente_prime):
    vector_prime = [-1] * nr_elemente_prime
    vector_rasp = [0] * nr_elemente_prime
    vector_prime[1] = 1
    vector_rasp[1] = 1
    contor = 2
    for i in range(2, nr_elemente_prime):
        if vector_prime[i] == -1:
            vector_prime[i] = 1
            vector_rasp[contor] = i
            contor = contor + 1
        for j in range(i + i, nr_elemente_prime, i):
            if vector_prime[j] == -1:
                vector_prime[j] = i
    set_prime = set(vector_rasp)
    set_prime.remove(0)
    set_prime.remove(1)
    answ_prime = list(set_prime)
    answ_prime.sort()
    return answ_prime

def binary_search(vectorul, valoarea):
    left = 0
    right = len(vectorul) - 1
    while left <= right:
        centru = (left + right) // 2
        if vectorul[centru] <= valoarea:
            left = centru + 1
        else:
            right = centru - 1
    return left

def binary_search_vectorul(vectorul, valoarea):
    left = 0
    right = len(vectorul) - 1
    while left <= right:
        centru = (left + right) // 2
        if vectorul[centru] <= valoarea:
            left = centru + 1
        else:
            right = centru - 1
    return left

def functie_combinari(vectorul, pozitie, sfarsit):
    global contor
    global matricea
    if pozitie >= sfarsit:
        setul = set()
        for hh in vectorul:
            setul.add(hh)
        if len(setul) == sfarsit:
            contor += 1
            matricea[contor] = vectorul
            print('contor=', contor)
    else:
        for vectorul[pozitie] in range(sfarsit):
            functie_combinari(vectorul, pozitie + 1, sfarsit)

def functie_val(val, poz, dictionarul, prezentul, ciclul, rel):
    if val not in prezentul:
        return val
    else:
        ciclul[val, poz, rel] = 1
        poz = binary_search(dictionarul[val], poz)
        if poz == 0:
            return val
        else:
            return functie_val(dictionarul[val][len(dictionarul[val]) - poz][0], dictionarul[val][len(dictionarul[val]) - poz][1], dictionarul, prezentul, ciclul, dictionarul[val][len(dictionarul[val]) - poz][2])

def factorial_invers(a, modul):
    calcul = pow(a, modul - 2, modul)
    return calcul

def functie_factorial(numar, modul):
    vec_fac = [1] * (numar + 1)
    for i in range(1, numar + 1):
        vec_fac[i] = vec_fac[i - 1] * i % modul
    return vec_fac

def combinari(baza, exponent, modulul):
    numitor = factorialul[baza - exponent] * factorialul[exponent] % modulul
    rasp_partial = factorialul[baza] % modulul * factorial_invers(numitor, modulul) % modulul
    return rasp_partial

def functie_dict(a, b, c, raspunsul, litera_a, litera_b):
    cate = 0
    vec = []
    for initiale in a[1]:
        pozitie = -1
        if len(b[1]) > 0:
            for el in b[1]:
                pozitie = el
                break
        if pozitie > -1:
            b[1].remove(pozitie)
            c[1].add(pozitie)
            vec.append(initiale)
            cate += 1
            raspunsul.append((initiale, litera_a, pozitie, litera_b))
    for toate in vec:
        a[1].remove(toate)
    return cate

def functie_jump(poz, adev, dict_nivel, niveluri, parinte, target, last, val, cadere, ordine, contor, vizitate):
    if adev == 0:
        el = poz
        vizitate[el] = 1
        unde = el + val[target - 1 - el]
        if unde >= target:
            adev = 1
            parinte[target] = el
            dict_nivel[target] = 1 + contor
        elif adev == 0:
            if unde > last:
                maximul = 0
                poz_max = -1
                fix_j = -1
                for j in range(last, unde + 1):
                    next = max(0, j - cadere[target - 1 - j])
                    saritura = j
                    if next + val[target - 1 - next] > maximul:
                        maximul = next + val[target - 1 - next]
                        poz_max = next
                        fix_j = j
                    if poz_max not in vizitate:
                        dict_nivel[poz_max] = 1 + dict_nivel[el]
                        parinte[poz_max] = el
                        ordine[poz_max] = fix_j
                last = unde
        if adev == 0 and poz_max not in vizitate and (poz_max > -1):
            functie_jump(poz_max, adev, dict_nivel, niveluri, parinte, target, last, val, cadere, ordine, contor + 1, vizitate)

def main():
    modul = 998244353
    pp = 10 ** 40
    vec_answ = []
    kuri = []
    answ = []
    for gg in range(1):
        n = int(input())
        val = list(map(int, input().split()))
        cadere = list(map(int, input().split()))
        vizitate = {}
        dict_nivel = {}
        niveluri = defaultdict(list)
        dict_nivel[0] = 0
        niveluri[0].append(0)
        adev = 0
        last = 0
        parinte = {}
        parinte[0] = -1
        ordine = {}
        target = n
        poz = 0
        posibil = 1
        while posibil == 1:
            if adev == 0:
                el = poz
                vizitate[el] = 1
                unde = el + val[target - 1 - el]
                if unde >= target:
                    adev = 1
                    posibil = 0
                    parinte[target] = el
                    dict_nivel[target] = 1 + contor
                elif adev == 0:
                    if unde > last:
                        maximul = 0
                        poz_max = -1
                        fix_j = -1
                        for j in range(last, unde + 1):
                            next = max(0, j - cadere[target - 1 - j])
                            if next + val[target - 1 - next] > maximul:
                                maximul = next + val[target - 1 - next]
                                poz_max = next
                                fix_j = j
                        if poz_max not in vizitate:
                            dict_nivel[poz_max] = 1 + dict_nivel[el]
                            parinte[poz_max] = el
                            ordine[poz_max] = fix_j
                    last = unde
                    if adev == 0 and poz_max not in vizitate and (poz_max > -1):
                        poz = poz_max
                    else:
                        posibil = 0
        if n in parinte:
            answ = []
            poz = n
            answ.append(0)
            while parinte[poz] != 0:
                if poz in parinte:
                    poz = parinte[poz]
                if poz in ordine:
                    answ.append(n - ordine[poz])
            print(len(answ))
            print(*answ[::-1])
        else:
            print(-1)
main()

Solution (Python):
n = int(input())
a = [0] + list(map(int, input().split()))
b = [0] + list(map(int, input().split()))
c = [10 ** 9] * len(a)
for i in range(n, 0, -1):
    c[i] = max(0, i + b[i] - a[i + b[i]])
mn = [10 ** 9 for i in range(len(a) + 2)]
rs = [10 ** 9 for i in range(len(a) + 1)]
for i in range(n, 0, -1):
    if min(i, c[i]) < mn[i + 1]:
        mn[i] = min(i, c[i])
        rs[i] = i
    else:
        mn[i] = mn[i + 1]
        rs[i] = rs[i + 1]
hi = n
ans = []
i = 1
while i <= (n and hi):
    ans.append(rs[hi])
    if mn[hi] >= hi:
        break
    hi = mn[hi]
if hi != 0:
    print(-1)
else:
    print(len(ans))
    for i in ans[1:]:
        print(i, end=' ')
    print(0)