Two chandeliers (Codeforces 1501D)
Tags: Math, chinese remainder theorem

Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: red – brown – yellow – red – brown – yellow and so on. There are many chandeliers that differs in color set or order of colors. And the person responsible for the light made a critical mistake — they bought two different chandeliers.Since chandeliers are different, some days they will have the same color, but some days — different. Of course, it looks poor and only annoys Vasya. As a result, at the $$$k$$$-th time when chandeliers will light with different colors, Vasya will become very angry and, most probably, will fire the person who bought chandeliers.Your task is to calculate the day, when it happens (counting from the day chandeliers were installed). You can think that Vasya works every day without weekends and days off.

Input: The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 500\,000$$$; $$$1 \le k \le 10^{12}$$$) — the number of colors in the first and the second chandeliers and how many times colors should differ to anger Vasya.The second line contains $$$n$$$ different integers $$$a_i$$$ ($$$1 \le a_i \le 2 \cdot \max(n, m)$$$) that describe the first chandelier's sequence of colors.The third line contains $$$m$$$ different integers $$$b_j$$$ ($$$1 \le b_i \le 2 \cdot \max(n, m)$$$) that describe the second chandelier's sequence of colors.At the $$$i$$$-th day, the first chandelier has a color $$$a_x$$$, where $$$x = ((i - 1) \mod n) + 1)$$$ and the second one has a color $$$b_y$$$, where $$$y = ((i - 1) \mod m) + 1)$$$.It's guaranteed that sequence $$$a$$$ differs from sequence $$$b$$$, so there are will be days when colors of chandeliers differs.

Output: Print the single integer — the index of day when Vasya will become angry.

Note: In the first example, the chandeliers will have different colors at days $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. That's why the answer is $$$5$$$.

Sample Inputs:
4 2 4
4 2 3 1
2 1

3 8 41
1 3 2
1 6 4 3 5 7 2 8

1 2 31
1
1 2

Sample Outputs:
5

47

62

Solution (Python):
def main():
    (n, m, k) = map(int, input().split())
    aa = map(int, input().split())
    bb = map(int, input().split())
    if n < m:
        (n, m, aa, bb) = (m, n, bb, aa)
    x = y2 = 1
    y = x2 = 0
    (g, a) = (n, m)
    while a:
        q = g // a
        (g, a, x, y, x2, y2) = (a, g % a, x2, y2, x - x2 * q, y - y2 * q)
    (nm, nm2, mg) = (n // g * m, n * 2 + 1, m // g)
    (colors, common) = ([-1] * nm2, [-1] * nm2)
    for (i, a) in enumerate(aa):
        colors[a] = i
    for (i, b) in enumerate(bb):
        b = colors[b]
        if b != -1 in colors and (not (b - i) % g):
            common[b] = i
    common = [(a - i) // g * x % mg * n + i for (i, a) in enumerate(common) if a != -1]
    common_count = len(common)
    (res, k) = divmod(k, nm - common_count)
    if not k:
        k = nm - common_count
        res -= 1
    res *= nm
    common.sort()
    a = -1
    for b in common:
        b -= a
        if k < b:
            break
        k -= b - 1
        res += b
        a += b
    print(res + k)
if __name__ == '__main__':
    main()

Solution (Python):
def main():
    (n, m, k) = list(map(lambda x: int(x), str(input()).split(' ')))
    a = list(map(lambda x: int(x), str(input()).split(' ')))
    b = list(map(lambda x: int(x), str(input()).split(' ')))
    if n < m:
        print(solve(m, n, k, b, a))
        return
    print(solve(n, m, k, a, b))

def solve(n, m, k, a, b):
    d = gcd(n, m)
    (x, y) = (0, 0)
    for i in range(1, m):
        if (i * n - d) % m == 0:
            x = i
            y = (i * n - d) // m
            if y == 0:
                x += 1
                y += 1
            break
    common = {}
    common_count = 0
    colors = {}
    com = []
    for i in range(len(a)):
        colors[a[i]] = i
    for i in range(len(b)):
        if b[i] in colors and (colors[b[i]] - i) % d == 0:
            common[colors[b[i]]] = i
            common_count += 1
    for (key, val) in common.items():
        z = (val - key) // d
        com.append(int(z * x % (m // d) * n + key))
    new_k = k % (m * n // d - common_count)
    s = k // (m * n // d - common_count) * m * n // d
    if new_k == 0:
        new_k = m * n // d - common_count
        s -= m * n // d
    com = sorted(com)
    cur = -1
    for c in com:
        if new_k < c - cur:
            s += new_k
            return s
        new_k -= c - cur - 1
        s += c - cur
        cur = c
    return s + new_k

def gcd(n, m):
    if n == m:
        return n
    if n < m:
        return gcd(m, n)
    if n % m == 0:
        return m
    return gcd(m, n % m)
if __name__ == '__main__':
    main()

Solution (Python):
import os
import sys
from io import BytesIO, IOBase
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')
from math import gcd, ceil

def prod(a, mod=10 ** 9 + 7):
    ans = 1
    for each in a:
        ans = ans * each % mod
    return ans

def lcm(a, b):
    return a * b // gcd(a, b)

def binary(x, length=16):
    y = bin(x)[2:]
    return y if len(y) >= length else '0' * (length - len(y)) + y

def check(a, b, k):
    (n, m) = (len(a), len(b))
    ba = []
    ab = []
    while len(ab) != n * m:
        ab += list(a)
    while len(ba) != n * m:
        ba += list(b)
    ans = 0
    i = 0
    while k:
        ans += 1
        if ab[i % (n * m)] != ba[i % (n * m)]:
            k -= 1
        i += 1
    print(ans)
    return ans
for _ in range(int(input()) if not True else 1):
    (n, m, k) = map(int, input().split())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    if n > m:
        (n, m) = (m, n)
        (a, b) = (list(b), list(a))
    kk = k
    its = m
    g = lcm(n, m) // n
    div = gcd(n, m)
    iterations_common = [n] * g
    index = {}
    index2 = [0] * m
    for i in range(m):
        index[b[i]] = i
    taken = [0] * m
    indexes = [0] * m
    oo = []
    for i in range(m):
        if not taken[i]:
            j = i
            x = []
            while not taken[j]:
                taken[j] = len(oo) + 1
                indexes[j] = len(x)
                x += [j]
                j += n
                j %= m
            oo += [x]
    for i in range(n):
        cur = a[i]
        if cur not in index:
            continue
        ind = index[cur]
        if taken[ind] != taken[i]:
            continue
        iterations_common[(indexes[ind] - indexes[i]) % g] -= 1
    for i in range(1, len(iterations_common)):
        iterations_common[i] += iterations_common[i - 1]
    total = iterations_common[-1]
    times = k // total
    if k % total == 0:
        times -= 1
    ans = n * g * times
    k -= total * times
    i = 0
    while iterations_common[i] < k:
        ans += n
        i += 1
    k = k - (iterations_common[i - 1] if i > 0 else 0)
    for j in range(n):
        if not k:
            break
        if a[(n * i + j) % n] != b[(n * i + j) % m]:
            k -= 1
        ans += 1
    print(ans)