結果

問題 No.261 ぐるぐるぐるぐる!あみだくじ!
ユーザー maspymaspy
提出日時 2020-05-05 02:08:39
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
AC  
実行時間 68 ms / 5,000 ms
コード長 2,402 bytes
コンパイル時間 122 ms
コンパイル使用メモリ 12,928 KB
実行使用メモリ 11,264 KB
最終ジャッジ日時 2024-06-25 14:21:02
合計ジャッジ時間 3,753 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
import itertools
from math import gcd

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
K = int(readline())
XY = tuple(tuple(map(int, readline().split())) for _ in range(K))
Q = int(readline())

P = list(range(N+1))
for x, y in XY:
    P[x], P[y] = P[y], P[x]

period = [[] for _ in range(N+1)]
for i in range(N+1):
    A = [i]
    j = i
    while True:
        j = P[j]
        if j == i:
            break
        A.append(j)
    period[i] = A

def solve(A):
    Y = []
    X = []
    for i, x in enumerate(itertools.chain([0], A)):
        if x not in period[i]:
            return -1
        Y.append(len(period[i]))
        X.append(period[i].index(x))
    
    def to_coprime_case(D1, A1, D2, A2):
        """ x=A1 mod D1, x=A2 mod D2. iff x=A1' mod D1', x=A2' mod D2'"""
        D = gcd(D1, D2)
        if A1 % D != A2 % D:
            return None
        A = D2 // D
        D2 = A
        while True:
            g = gcd(D, A)
            if g == 1:
                break
            D //= g
            D2 *= g
        D1 //= gcd(D1, D2)
        A1 %= D1
        A2 %= D2
        return D1, A1 % D1, D2, A2 % D2


    def extgcd(a, b):
        s = a
        sx = 1
        sy = 0
        t = b
        tx = 0
        ty = 1
        while t:
            q, r = divmod(s, t)
            s, sx, sy, t, tx, ty = t, tx, ty, r, sx - tx * q, sy - ty * q
        return sx, sy


    def Garner(D, A, MOD):
        N = len(D)
        coefs = [0] * N
        for i in range(N):
            mod = D[i]
            prod = 1
            num = A[i]
            for j, x in enumerate(D[:i]):
                num -= coefs[j] * prod
                prod *= x
                prod %= mod
            x, _ = extgcd(prod, mod)
            coefs[i] = x * num % mod
        ret = 0
        prod = 1
        for c, mod in zip(coefs, D):
            ret += prod * c
            prod *= mod
            prod %= MOD
        return ret % MOD

    for i, j in itertools.combinations(range(N), 2):
        ret = to_coprime_case(Y[i], X[i], Y[j], X[j])
        if ret is None:
            return -1
        else:
            Y[i], X[i], Y[j], X[j] = ret
    
    X = [(x - 1) % y for x, y in zip(X, Y)]
    x = Garner(Y, X, 10**19)
    x += 1
    return x

for query in readlines():
    A = map(int, query.split())
    print(solve(A))
0