結果

問題 No.261 ぐるぐるぐるぐる!あみだくじ!
ユーザー rpy3cpprpy3cpp
提出日時 2015-09-19 03:56:17
言語 Python3
(3.11.6 + numpy 1.26.0 + scipy 1.11.3)
結果
AC  
実行時間 20 ms / 5,000 ms
コード長 1,362 bytes
コンパイル時間 708 ms
コンパイル使用メモリ 10,884 KB
実行使用メモリ 8,208 KB
最終ジャッジ日時 2023-08-25 02:17:53
合計ジャッジ時間 2,875 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 16 ms
8,164 KB
testcase_01 AC 16 ms
8,036 KB
testcase_02 AC 16 ms
8,108 KB
testcase_03 AC 17 ms
8,052 KB
testcase_04 AC 19 ms
8,112 KB
testcase_05 AC 18 ms
8,052 KB
testcase_06 AC 17 ms
8,028 KB
testcase_07 AC 16 ms
7,984 KB
testcase_08 AC 18 ms
7,980 KB
testcase_09 AC 17 ms
8,052 KB
testcase_10 AC 17 ms
8,164 KB
testcase_11 AC 17 ms
8,072 KB
testcase_12 AC 17 ms
8,008 KB
testcase_13 AC 18 ms
8,008 KB
testcase_14 AC 18 ms
8,084 KB
testcase_15 AC 18 ms
8,064 KB
testcase_16 AC 20 ms
8,164 KB
testcase_17 AC 19 ms
8,072 KB
testcase_18 AC 19 ms
8,088 KB
testcase_19 AC 19 ms
8,040 KB
testcase_20 AC 19 ms
8,080 KB
testcase_21 AC 18 ms
8,040 KB
testcase_22 AC 19 ms
8,004 KB
testcase_23 AC 18 ms
8,008 KB
testcase_24 AC 19 ms
8,080 KB
testcase_25 AC 19 ms
8,040 KB
testcase_26 AC 20 ms
8,084 KB
testcase_27 AC 18 ms
8,124 KB
testcase_28 AC 20 ms
8,068 KB
testcase_29 AC 20 ms
8,116 KB
testcase_30 AC 19 ms
8,192 KB
testcase_31 AC 18 ms
7,984 KB
testcase_32 AC 20 ms
8,084 KB
testcase_33 AC 20 ms
8,088 KB
testcase_34 AC 19 ms
8,064 KB
testcase_35 AC 19 ms
8,148 KB
testcase_36 AC 19 ms
8,004 KB
testcase_37 AC 17 ms
8,008 KB
testcase_38 AC 18 ms
8,104 KB
testcase_39 AC 18 ms
8,208 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

def find_cycle(N, amida, idx, cycles, mypos):
    mypos[idx] = 0
    a = amida[idx]
    count = 1
    while a != idx:
        mypos[a] = count
        a = amida[a]
        count += 1
    cycles[idx] = count

def chinese_remainder(a, cycles, pos):
    xy = []
    for ai, cycle, mypos in zip(a, cycles, pos):
        x = mypos[ai - 1]
        if x == -1: return -1
        xy.append((x, cycle))
    return CRT(xy)

def gcd_ext(m, n):
    x, u = 1, 0
    while n:
        k, m = divmod(m, n)
        m, n = n, m
        x, u = u, x - u * k
    return m, x

def solve2(x1, y1, x2, y2):
    gcd, a = gcd_ext(y1, y2)
    lcm = y1 * y2 // gcd
    k, r = divmod(x1 - x2, gcd)
    if r != 0: return -1, lcm
    z = (x1 - k * a * y1) % lcm
    return z, lcm

def CRT(xy):
    x0, y0 = xy[0]
    if len(xy) == 1: return x0 if x0 else y0
    for x1, y1 in xy[1:]:
        x0, y0 = solve2(x0, y0, x1, y1)
        if x0 == -1: return -1
    return x0 if x0 else y0

N = int(input())
K = int(input())
amida = list(range(N))
for k in range(K):
    x, y = map(int, input().split())
    amida[x-1], amida[y-1] = amida[y-1], amida[x-1]
Q = int(input())
As = [list(map(int, input().split())) for q in range(Q)]
cycles = [0] * N
pos = [[-1] * N for n in range(N)]
for idx in range(N): find_cycle(N, amida, idx, cycles, pos[idx])
for a in As: print(chinese_remainder(a, cycles, pos))
0