Running Competition (Codeforces 1398G)
Tags: Math, fft

A running competition is going to be held soon. The stadium where the competition will be held can be represented by several segments on the coordinate plane:  two horizontal segments: one connecting the points $$$(0, 0)$$$ and $$$(x, 0)$$$, the other connecting the points $$$(0, y)$$$ and $$$(x, y)$$$;  $$$n + 1$$$ vertical segments, numbered from $$$0$$$ to $$$n$$$. The $$$i$$$-th segment connects the points $$$(a_i, 0)$$$ and $$$(a_i, y)$$$; $$$0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x$$$. For example, here is a picture of the stadium with $$$x = 10$$$, $$$y = 5$$$, $$$n = 3$$$ and $$$a = [0, 3, 5, 10]$$$:  A lap is a route that goes along the segments, starts and finishes at the same point, and never intersects itself (the only two points of a lap that coincide are its starting point and ending point). The length of a lap is a total distance travelled around it. For example, the red route in the picture representing the stadium is a lap of length $$$24$$$.The competition will be held in $$$q$$$ stages. The $$$i$$$-th stage has length $$$l_i$$$, and the organizers want to choose a lap for each stage such that the length of the lap is a divisor of $$$l_i$$$. The organizers don't want to choose short laps for the stages, so for each stage, they want to find the maximum possible length of a suitable lap.Help the organizers to calculate the maximum possible lengths of the laps for the stages! In other words, for every $$$l_i$$$, find the maximum possible integer $$$L$$$ such that $$$l_i \bmod L = 0$$$, and there exists a lap of length exactly $$$L$$$.If it is impossible to choose such a lap then print $$$-1$$$.

Input: The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n, x, y \le 2 \cdot 10^5$$$, $$$n \le x$$$).The second line contains $$$n + 1$$$ integers $$$a_0$$$, $$$a_1$$$, ..., $$$a_n$$$ ($$$0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x$$$).The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of stages.The fourth line contains $$$q$$$ even integers $$$l_1$$$, $$$l_2$$$, ..., $$$l_q$$$ ($$$4 \le l_i \le 10^6$$$) — the lengths of the stages. 

Output: Print $$$q$$$ numbers. The $$$i$$$-th number should be equal to the maximum possible length of a suitable lap for the $$$i$$$-th stage, or $$$-1$$$ if it is impossible to choose a lap for that stage.


Sample Inputs:
3 10 5
0 3 5 10
6
24 30 14 16 18 10

Sample Outputs:
24 30 14 16 -1 -1

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 0)
(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()
        import math
        inf = math.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 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='')

class FFT:

    def __init__(self, MOD=998244353):
        FFT.MOD = MOD
        g = self.primitive_root_constexpr()
        ig = pow(g, FFT.MOD - 2, FFT.MOD)
        FFT.W = [pow(g, FFT.MOD - 1 >> i, FFT.MOD) for i in range(30)]
        FFT.iW = [pow(ig, FFT.MOD - 1 >> i, FFT.MOD) for i in range(30)]

    def primitive_root_constexpr(self):
        if FFT.MOD == 998244353:
            return 3
        elif FFT.MOD == 200003:
            return 2
        elif FFT.MOD == 167772161:
            return 3
        elif FFT.MOD == 469762049:
            return 3
        elif FFT.MOD == 754974721:
            return 11
        divs = [0] * 20
        divs[0] = 2
        cnt = 1
        x = (FFT.MOD - 1) // 2
        while x % 2 == 0:
            x //= 2
        i = 3
        while i * i <= x:
            if x % i == 0:
                divs[cnt] = i
                cnt += 1
                while x % i == 0:
                    x //= i
            i += 2
        if x > 1:
            divs[cnt] = x
            cnt += 1
        g = 2
        while 1:
            ok = True
            for i in range(cnt):
                if pow(g, (FFT.MOD - 1) // divs[i], FFT.MOD) == 1:
                    ok = False
                    break
            if ok:
                return g
            g += 1

    def fft(self, k, f):
        for l in range(k, 0, -1):
            d = 1 << l - 1
            U = [1]
            for i in range(d):
                U.append(U[-1] * FFT.W[l] % FFT.MOD)
            for i in range(1 << k - l):
                for j in range(d):
                    s = i * 2 * d + j
                    (f[s], f[s + d]) = ((f[s] + f[s + d]) % FFT.MOD, U[j] * (f[s] - f[s + d]) % FFT.MOD)

    def ifft(self, k, f):
        for l in range(1, k + 1):
            d = 1 << l - 1
            for i in range(1 << k - l):
                u = 1
                for j in range(i * 2 * d, (i * 2 + 1) * d):
                    f[j + d] *= u
                    (f[j], f[j + d]) = ((f[j] + f[j + d]) % FFT.MOD, (f[j] - f[j + d]) % FFT.MOD)
                    u = u * FFT.iW[l] % FFT.MOD

    def convolve(self, A, B):
        n0 = len(A) + len(B) - 1
        k = n0.bit_length()
        n = 1 << k
        A += [0] * (n - len(A))
        B += [0] * (n - len(B))
        self.fft(k, A)
        self.fft(k, B)
        A = [a * b % FFT.MOD for (a, b) in zip(A, B)]
        self.ifft(k, A)
        inv = pow(n, FFT.MOD - 2, FFT.MOD)
        A = [a * inv % FFT.MOD for a in A]
        del A[n0:]
        return A
(n, x, y) = MII()
nums = LII()
q = II()
queries = LII()
vis = [0] * (x + 1)
for v in nums:
    vis[v] += 1
res = FFT().convolve(vis, vis[::-1])[x:]
notes = [0] * (5 * 10 ** 5 + 1)
for i in range(1, x + 1):
    if res[i]:
        notes[i + y] = i + y
for i in range(1, len(notes)):
    for j in range(i, len(notes), i):
        notes[j] = max(notes[i], notes[j])
ans = []
for v in queries:
    v //= 2
    ans.append(notes[v] * 2 if notes[v] > 0 else -1)
print(' '.join(map(str, ans)))

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def ntt(f, l, x, r, mod):
    (u, v) = (1, l // 2)
    x0 = x
    while v:
        y = [1]
        for _ in range(v):
            y.append(y[-1] * r[x0] % mod)
        for i in range(u):
            a = 2 * i * v
            b = a + v
            for j in range(v):
                (fa, fb) = (f[a + j], f[b + j])
                f[a + j] = (fa + fb) % mod
                f[b + j] = (fa - fb) * y[j] % mod
        u *= 2
        v //= 2
        x0 -= 1
    return

def intt(f, l, ir, mod):
    (u, v) = (1, l // 2)
    x0 = 1
    while v:
        y = [1]
        for _ in range(u):
            y.append(y[-1] * ir[x0] % mod)
        for i in range(v):
            a = 2 * i * u
            b = a + u
            for j in range(u):
                (fa, fb) = (f[a + j], f[b + j])
                f[a + j] = (fa + fb * y[j]) % mod
                f[b + j] = (fa - fb * y[j]) % mod
        u *= 2
        v //= 2
        x0 += 1
    return

def convolve(f, g):
    mod = 998244353
    r = [pow(3, mod - 1 >> i, mod) for i in range(21)]
    ir = [pow(i, mod - 2, mod) for i in r]
    (lf, lg) = (len(f), len(g))
    c = lf + lg - 1
    x = c.bit_length()
    m = pow(2, x)
    f += [0] * (m - lf)
    g += [0] * (m - lg)
    ntt(f, m, x, r, mod)
    ntt(g, m, x, r, mod)
    fg = [i * j % mod for (i, j) in zip(f, g)]
    intt(fg, m, ir, mod)
    im = pow(m, mod - 2, mod)
    ans = [fg[i] * im % mod for i in range(c)]
    return ans
(n, x, y) = map(int, input().split())
a = list(map(int, input().split()))
f = [0] * (x + 1)
g = [0] * (x + 1)
for i in a:
    f[i] = 1
    g[x - i] = 1
b = convolve(f, g)
b = b[x:]
m = pow(10, 6) + 5
ans0 = [-1] * m
for i in range(1, x + 1):
    if not b[i]:
        continue
    u = 2 * (i + y)
    v = u
    while v < m:
        ans0[v] = u
        v += u
q = int(input())
l = list(map(int, input().split()))
ans = [ans0[i] for i in l]
sys.stdout.write(' '.join(map(str, ans)))

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def ntt(f, l, x, r, mod):
    (u, v) = (1, l // 2)
    x0 = x
    while v:
        y = [1]
        for _ in range(v):
            y.append(y[-1] * r[x0] % mod)
        for i in range(u):
            a = 2 * i * v
            b = a + v
            for j in range(v):
                (fa, fb) = (f[a + j], f[b + j])
                f[a + j] = (fa + fb) % mod
                f[b + j] = (fa - fb) * y[j] % mod
        u *= 2
        v //= 2
        x0 -= 1
    return

def intt(f, l, ir, mod):
    (u, v) = (1, l // 2)
    x0 = 1
    while v:
        y = [1]
        for _ in range(u):
            y.append(y[-1] * ir[x0] % mod)
        for i in range(v):
            a = 2 * i * u
            b = a + u
            for j in range(u):
                (fa, fb) = (f[a + j], f[b + j])
                f[a + j] = (fa + fb * y[j]) % mod
                f[b + j] = (fa - fb * y[j]) % mod
        u *= 2
        v //= 2
        x0 += 1
    return

def convolve(f, g):
    mod = 998244353
    r = [pow(3, mod - 1 >> i, mod) for i in range(21)]
    ir = [pow(i, mod - 2, mod) for i in r]
    (lf, lg) = (len(f), len(g))
    c = lf + lg - 1
    x = c.bit_length()
    m = pow(2, x)
    f += [0] * (m - lf)
    g += [0] * (m - lg)
    ntt(f, m, x, r, mod)
    ntt(g, m, x, r, mod)
    fg = [i * j % mod for (i, j) in zip(f, g)]
    intt(fg, m, ir, mod)
    im = pow(m, mod - 2, mod)
    ans = [fg[i] * im % mod for i in range(c)]
    return ans
(n, x, y) = map(int, input().split())
a = list(map(int, input().split()))
f = [0] * (2 * x + 1)
g = [0] * (2 * x + 1)
for i in a:
    f[x - i] = 1
    g[x + i] = 1
b = convolve(f, g)
l = 2 * x
b = b[l:]
m = pow(10, 6) + 5
ans0 = [-1] * m
for i in range(1, x + 1):
    if not b[i]:
        continue
    u = 2 * (i + y)
    v = u
    while v < m:
        ans0[v] = u
        v += u
q = int(input())
l = list(map(int, input().split()))
ans = [ans0[i] for i in l]
sys.stdout.write(' '.join(map(str, ans)))