Harryxun/GPT-100-sft-dataset huggingface dataset:
Problem p02703 (python)

Fixed submission:
import heapq


n, m, s = map(int, input().split())
if s >= 2500:
    s = 2499

edges = [[] for _ in range(n)]
for _ in range(m):
    from_, to, cost, time = map(int, input().split())
    edges[from_-1].append((to-1, cost, time))
    edges[to-1].append((from_-1, cost, time))

banks = [(0, 0) for _ in range(n)]
for i in range(n):
    coin, time = map(int, input().split())
    banks[i] = (coin, time)

INF = float('INF')
DP = [INF] * (n * 2500)
ans = [INF] * n


def to_one_dimension(node, coin):
    return node * 2500 + coin


def push_todo(node, coin, time):
    if coin < 0:
        return
    if time >= DP[to_one_dimension(node, coin)]:
        return
    heapq.heappush(todo, (time, node, coin))


def charge(node, current_coin, current_time):
    coin, time = banks[node]
    new_coin = current_coin + coin
    if new_coin >= 2500:
        new_coin = 2499
    push_todo(node, new_coin, current_time+time)


todo = [(0, 0, s)]
while todo:
    current_time, node, current_coin = heapq.heappop(todo)
    if current_time < ans[node]:
        ans[node] = current_time

    one_d_idx = to_one_dimension(node, current_coin)
    if current_time >= DP[one_d_idx]:
        continue

    DP[one_d_idx] = current_time
    charge(node, current_coin, current_time)

    for to, cost, time in edges[node]:
        push_todo(to, current_coin-cost, current_time+time)

for a in ans[1:]:
    print(a)

Buggy submission (verdict: Runtime Error):
def main():
    import heapq

    n, m, s = map(int, input().split())

    edges = [[] for _ in range(n)]
    max_cost = 0
    for _ in range(m):
        from_, to, cost, time = map(int, input().split())
        edges[from_-1].append((to-1, cost, time))
        edges[to-1].append((from_-1, cost, time))
        if cost > max_cost:
            max_cost = cost

    banks = []
    for i in range(n):
        coin, time = map(int, input().split())
        banks.append((coin, time))

    max_coin = max_cost * (n-1)
    if s > max_coin:
        s = max_coin

    INF = float('INF')
    DP = [[INF] * max_coin for _ in range(n)]
    DP[0][s] = 0
    ans = [INF] * n

    def push_todo(node, coin, time):
        if coin < 0:
            return
        if time >= DP[node][coin]:
            return
        heapq.heappush(todo, (time, node, coin))
        DP[node][coin] = time

    def charge(node, current_coin, current_time):
        coin, time = banks[node]
        new_coin = current_coin + coin
        if new_coin >= max_coin:
            new_coin = max_coin-1
        push_todo(node, new_coin, current_time+time)

    todo = [(0, 0, s)]  # time, node, coin
    while todo:
        current_time, node, current_coin = heapq.heappop(todo)
        if current_time > DP[node][current_coin]:
            continue

        if current_time < ans[node]:
            ans[node] = current_time

        charge(node, current_coin, current_time)

        for to, cost, time in edges[node]:
            push_todo(to, current_coin-cost, current_time+time)

    for a in ans[1:]:
        print(a)


if __name__ == '__main__':
    main()
Problem p02774 (python)

Fixed submission:
import numpy as np

n, k = map(int, input().split())

A = np.array(input().split(), np.int64)

A.sort()

posA = A[A > 0]
negA = A[A < 0]
zeros = (A==0).sum()

left = -10**18
right = 10**18

while left+1 < right:
    num = (left+right)//2
    
    less_count = 0
    
    if num >= 0:
        less_count += zeros * n
    
    limit_pair_for_pos = num // posA
    limit_idxs = np.searchsorted(A, limit_pair_for_pos, side='right')
    less_count += limit_idxs.sum()

    limit_pair_for_neg = -(num // -negA)
    limit_idxs = n - np.searchsorted(A, limit_pair_for_neg, side='left')
    less_count += limit_idxs.sum()

    duplicate_cases = (A**2 <= num).sum()
    less_count -= duplicate_cases
    less_count //= 2
    
    if less_count >= k:
        right = num
    else:
        left = num

print(right)

Buggy submission (verdict: Runtime Error):
n, k = map(int, input().split())
A = list(map(int, input().split()))

P = [a for a in A if a > 0]
Z = [a for a in A if a == 0]
M = [a for a in A if a < 0]

P.sort()
Z.sort()
M.sort(reverse=True)

minus_count = len(P) * len(M)
zero_count = len(Z) * (len(P)+len(M))
if len(Z) >= 2:
    zero_count += (len(Z) * (len(Z)-1)) // 2

left = -10**18 - 1
right = 10**18 + 1

while left + 1 < right:
    num = (left + right) // 2
    count = 0

    if num >= 0:
        count += zero_count + minus_count

        limit_idx = len(P)-1
        for idx, p in enumerate(P):
            pair = num / p
            while P[limit_idx] > pair and limit_idx > idx:
                limit_idx -= 1

            pattern = limit_idx - idx
            if pattern == 0:
                break
            count += pattern

        limit_idx = len(M) - 1
        for idx, m in enumerate(M):
            pair = num / m
            while M[limit_idx] < pair and limit_idx > idx:
                limit_idx -= 1

            pattern = limit_idx - idx
            if pattern == 0:
                break
            count += pattern

    elif num < 0:
        for idx, p in enumerate(P):
            pair = num / p

            limit_idx = len(M) - 1
            while M[limit_idx] <= pair and limit_idx >= 0:
                limit_idx -= 1

            pattern = len(M) - limit_idx - 1
            count += pattern

    if count >= k:
        right = num
    else:
        left = num

print(right)
Problem p02780 (python)

Fixed submission:
n, k = map(int, input().split())
P = list(map(int, input().split()))


E = [0] * 1001

total = 0
for i in range(1, 1001):
    total += i
    e = total / i
    E[i] = e

P_to_E = [E[p] for p in P]


candidate = sum(P_to_E[:k])
candidates = [candidate]

for i in range(n-k):
    drop = P_to_E[i]
    add = P_to_E[i+k]
    candidate += add - drop
    candidates.append(candidate)

print(max(candidates))

Buggy submission (verdict: Runtime Error):
n, k = map(int, input().split())
P = list(map(int, input().split()))


E = [0] * 1001

total = 0
for i in range(1, 1001):
    total += i
    e = total / i
    E[i] = e

P_to_E = [E[p] for p in P]

candidates = []
candidate = sum(P_to_E[:k])

for i in range(n-k):
    drop = P_to_E[i]
    add = P_to_E[i+k]
    candidate += add - drop
    candidates.append(candidate)

print(max(candidates))
Problem p02787 (python)

Fixed submission:
import sys
input = sys.stdin.readline

max_size = 2*10**4 + 1
h, n = map(int, input().split())
DP = [float('INF')] * max_size
DP[0] = 0

for _ in range(n):
    damage, cost = map(int, input().split())
    for idx in range(damage, max_size):
        DP[idx] = min(DP[idx], DP[idx-damage] + cost)

print(min(DP[h:]))

Buggy submission (verdict: Runtime Error):
import numpy as np
import sys
input = sys.stdin.readline


max_size = 10**4 + 2 * 10**3
h, n = map(int, input().split())
DP = np.ones(max_size, dtype=np.int64) * 10**9
DP[0] = 0

for _ in range(n):
    power, cost = map(int, input().split())
    for i in range((h+power-1)//power):
        np.minimum(DP[(i+1)*power: (i+2)*power], DP[(i)*power: (i+1)*power] + cost, DP[(i+1)*power: (i+2)*power])

print(DP[h:].min())
Problem p02804 (python)

Fixed submission:
P = 10**9 + 7
N = 1000000
inv_t = [0]+[1]
for i in range(2,N):
    inv_t += [inv_t[P % i] * (P - int(P / i)) % P]



n, k = map(int, input().split())
A = list(map(int, input().split()))
mod = 10 ** 9 + 7

A.sort()

mini_count = 0
maxim_count = 0
pattern = 1
for i in range(n-k, -1, -1):
    mini = A[i]
    mini_count += mini * pattern % mod
    mini_count %= mod
    pattern = pattern * (n-i) * inv_t[n-i-k+1] % mod


pattern = 1
for i in range(n-k+1, 0, -1):
    maxim = A[-i]
    maxim_count += maxim * pattern % mod
    maxim_count %= mod
    pattern = pattern * (n-i+1) * inv_t[n-i-k+2] % mod

ans = maxim_count - mini_count
ans %= mod

print(ans)

Buggy submission (verdict: Runtime Error):
n, k = map(int, input().split())
A = list(map(int, input().split()))
mod = 10 ** 9 + 7

P = 10**9 + 7
N = n-k+1
inv_t = [0]+[1]  # 逆元
for i in range(2, N):
    inv_t += [inv_t[P % i] * (P - int(P / i)) % P]

A.sort()
mini_count = 0
maxim_count = 0
pattern = 1
"""
minX, maxXとして選ばれるのはそれぞれ
minX:sortAの右からk番目(大きい数値からk個取った時の最小値)とそれより左の要素
maxX:sortAの左からk番目(小さい数値からk個取った時の最大値)とそれより右の要素
選ばれるパターンはminXの場合自分の要素より右にある要素からk-1個を選ぶパターン数
つまり最初は(k-1)C(k-1) = 1
選べる要素が一つ増えるごとに
tC(k-1) ⇒ (t+1)C(k-1)のように増えるので
t * t-1 * t-2 ... * t-k ⇒ t+1 * t * t-1 ... * t-k+1 であり
つまりパターン数は (t+1) / (t-k) 倍になる
"""
for idx in range(k, n + 1):
    mini = A[-idx]  #
    mini_count += mini * pattern % mod
    mini_count %= mod

    maxim = A[idx - 1]
    maxim_count += maxim * pattern % mod
    maxim_count %= mod

    pattern = pattern * (idx) * inv_t[idx + 1 - k] % mod # 割り算のmodは逆元をかける

ans = maxim_count - mini_count
ans %= mod

print(ans)
Problem p02821 (python)

Fixed submission:
n, m = map(int, input().split())
A = list(map(int, input().split()))
A.sort(reverse=True)
cumsumA = []

total = 0
for a in A:
    total += a
    cumsumA.append(total)
cumsumA.append(0)

l = 0
r = 10 ** 6
while l + 1 < r:
    num = (l+r)//2
    pair_idx = n-1
    count = 0
    for a in A:
        while a + A[pair_idx] < num and pair_idx >= 0:
            pair_idx -= 1

        count += pair_idx+1

    if count < m:
        r = num
        continue
    elif count >= m:
        l = num


ans = 0
count = 0
num = l
pair_idx = n-1
for a in A:
    while a + A[pair_idx] < num and pair_idx >= 0:
        pair_idx -= 1

    count += pair_idx+1
    ans += cumsumA[pair_idx] + a*(pair_idx+1)

diff = count - m
ans -= num * diff
print(ans)

Buggy submission (verdict: Runtime Error):
import heapq


n, m = map(int, input().split())
A = list(map(int, input().split()))
A.sort(reverse=True)

idx_dict = {}
for i in range(n):
    idx_dict[i] = i+1

ans = [A[i]+A[i] for i in range(n)]
candidates = [[-(A[i]+A[i+1]), i] for i in range(n-1)]
heapq.heapify(candidates)

for i in range(m//2):
    num, idx = heapq.heappop(candidates)
    ans.append(-num)
    ans.append(-num)
    idx_dict[idx] += 1
    new_pair = idx_dict[idx]
    if new_pair >= n:
        continue
    candidate = A[idx] + A[new_pair]
    heapq.heappush(candidates, [-candidate, idx])

ans.sort(reverse=True)
print(sum(ans[:m]))
Problem p02822 (python)

Fixed submission:
import sys
sys.setrecursionlimit(2*10**5)
input = sys.stdin.readline


def calc_counts(n, edges):
    counts = [0] * n
    seen = [False] * n
    dfs(0, edges, seen, counts)
    return counts


def dfs(node, edges, seen, counts):
    count = 1
    seen[node] = True
    for to in edges[node]:
        if seen[to]:
            continue
        count += dfs(to, edges, seen, counts)
    counts[node] = count
    return count


def calc_blank(node, counts: list, edges, all, mod=10**9+7):
    n = len(counts)
    paths = edges[node]
    if len(paths) <= 1:
        return 0
    base = counts[node]
    result = all - 1
    for v in paths:
        count = counts[v]
        if count > base:
            count = n - base
        result -= pow(2, count, mod) - 1
        result %= mod

    return result


def main():
    mod = 10**9 + 7
    n = int(input())
    edges = [[] for _ in range(n)]
    for _ in range(n-1):
        a, b = map(int, input().split())
        edges[a-1].append(b-1)
        edges[b-1].append(a-1)

    counts = calc_counts(n, edges)
    all = pow(2, n-1, mod)
    blanks = 0
    for node in range(n):
        blank = calc_blank(node, counts, edges, all)
        blanks += blank
        blanks %= mod

    inv_denominator = pow(pow(2, n, mod), mod-2, mod)
    ans = blanks * inv_denominator % mod
    print(ans)


if __name__ == "__main__":
    main()

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline


def calc_counts(n, edges):
    counts = [0] * n
    seen = [False] * n
    dfs(0, edges, seen, counts)
    return counts


def dfs(node, edges, seen, counts):
    count = 1
    seen[node] = True
    for to in edges[node]:
        if seen[to]:
            continue
        count += dfs(to, edges, seen, counts)
    counts[node] = count
    return count


def calc_blank(node, counts: list, edges, all, mod=10**9+7):
    n = len(counts)
    paths = edges[node]
    if len(paths) <= 1:
        return 0
    base = counts[node]
    result = all - 1
    for v in paths:
        count = counts[v]
        if count > base:
            count = n - base
        result -= pow(2, count, mod) - 1
        result %= mod

    return result


def main():
    mod = 10**9 + 7
    n = int(input())
    edges = [[] for _ in range(n)]
    for _ in range(n-1):
        a, b = map(int, input().split())
        edges[a-1].append(b-1)
        edges[b-1].append(a-1)

    counts = calc_counts(n, edges)
    all = pow(2, n-1, mod)
    blanks = 0
    for node in range(n):
        blank = calc_blank(node, counts, edges, all)
        blanks += blank
        blanks %= mod

    inv_denominator = pow(pow(2, n, mod), mod-2, mod)
    ans = blanks * inv_denominator % mod
    print(ans)


if __name__ == "__main__":
    main()
Problem p02845 (python)

Fixed submission:
n = int(input())
A = list(map(int, input().split()))
mod = 10**9 + 7

ans = 3
hats = [1, 0, 0]

if n == 1:
    if A[0] == 0:
        print(3)
    else:
        print(0)
    exit()


if A[0] != 0:
    print(0)
    exit()
for a in A[1:]:
    count = hats.count(a)
    if count == 0:
        print(0)
        exit()

    idx = hats.index(a)
    hats[idx] += 1
    ans *= count
    ans %= mod

print(ans)

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline
mod = 10**9 + 7

def main():
    n = int(input())
    A = list(map(int, input().split()))
    candidates = [0] * n
    candidates[0] = 3
    ans = 1

    for a in A:
        ans *= candidates[a]
        ans %= mod
        candidates[a] -= 1
        candidates[a+1] += 1

    print(ans)


if __name__ == "__main__":
    main()

Buggy submission (verdict: Runtime Error):
n = int(input())
A = list(map(int, input().split()))
mod = 10**9 + 7

ans = 3
hats = [1, 0, 0]

for a in A[1:]:
    count = hats.count(a)
    idx = hats.index(a)
    hats[idx] += 1
    ans *= count
    ans %= mod

print(ans)
Problem p02850 (python)

Fixed submission:
import sys
input = sys.stdin.readline


n = int(input())
routes = []
dic = [{}] * n
edges = [[]for _ in range(n)]
used = [0]*n

for i in range(n-1):
    a, b = map(int, input().split())
    routes.append([a-1, b-1])
    edges[a-1].append(b-1)

for node in range(n):
    unanle = used[node]
    count = 1
    if count == unanle:
        count += 1
    for to in edges[node]:
        dic[node][to] = count
        used[to] = count
        count += 1
        if count == unanle:
            count += 1

print(max(used))
for _from, to in routes:
    print(dic[_from][to])

Buggy submission (verdict: Runtime Error):
import sys
read = sys.stdin.read


n, *ab = map(int, read().split())
ans = [0]*(n-1)
edges = [[]for _ in range(n)]
used = [0]*n

for i, a, b in zip(range(n-1), *[iter(ab)] * 2):
    edges[a].append([b, i])

for node in range(n):
    unable = used[node]
    color = 1

    for to, id in edges[node]:
        if color == unable:
            color += 1
        ans[id] = str(color)
        used[to] = color
        color += 1

print(max(used))
print('\n'.join(ans))
Problem p02852 (python)

Fixed submission:
n, m = map(int, input().split())
S = input()

ans = []
x = len(S) - 1
while x:
    for step in range(m, 0, -1):
        if x - step < 0:
            continue
            
        to = S[x-step]
        if to == '1':
            continue
        else:
            x -= step
            ans.append(str(step))
            break
    else:
        print(-1)
        exit()

print(' '.join(ans[::-1]))

Buggy submission (verdict: Runtime Error):
n, m = map(int, input().split())
S = input()

ans = []
x = len(S) - 1
while x:
    for step in range(m, 0, -1):
        to = S[x-step]
        if x - step < 0:
            continue
        if to == '1':
            continue
        else:
            x -= step
            ans.append(str(step))
            break
    else:
        print(-1)
        exit()

print(' '.join(ans[::-1]))
Problem p02889 (python)

Fixed submission:
from scipy.sparse.csgraph import csgraph_from_dense
from scipy.sparse.csgraph import floyd_warshall

n, m, energy = map(int, input().split())
edges = [[float('INF')]*n for _ in range(n)]

for i in range(m):
    a, b, c = map(int, input().split())
    edges[a-1][b-1] = c
    edges[b-1][a-1] = c

G = csgraph_from_dense(edges, null_value=float('INF'))
dist = floyd_warshall(G)

L_edges = [[float('INF')]*n for _ in range(n)]
for i in range(n-1):
    for j in range(i, n):
        if dist[i][j] <= energy:
            L_edges[i][j] = 1
            L_edges[j][i] = 1

G = csgraph_from_dense(L_edges, null_value=float('INF'))
answers = floyd_warshall(G)

Q = int(input())
for i in range(Q):
    s, t = map(int, input().split())
    ans = answers[s-1][t-1] - 1
    if ans == float('INF'):
        ans = -1
    print(int(ans))

Buggy submission (verdict: Runtime Error):
import sys
from scipy.sparse.csgraph import csgraph_from_dense
from scipy.sparse.csgraph import floyd_warshall
input = sys.stdin.readline


n, m, energy = map(int, input().split())
edges = [[float('INF')]*n for _ in range(n)]

for i in range(m):
    a, b, c = map(int, input().split())
    edges[a-1][b-1] = c
    edges[b-1][a-1] = c

G = csgraph_from_dense(edges, null_value=float('INF'))
dist = floyd_warshall(G)

L_edges = [[float('INF')]*n for _ in range(n)]
for i in range(n-1):
    for j in range(i, n):
        if dist[i][j] <= energy:
            L_edges[i][j] = 1
            L_edges[j][i] = 1

G = csgraph_from_dense(L_edges, null_value=0)
answers = floyd_warshall(G)

Q = int(input())
for i in range(Q):
    s, t = map(int, input().split())
    ans = answers[s-1][t-1] - 1
    print(int(ans))

Buggy submission (verdict: Runtime Error):
for i in range(m):
    a, b, c = map(int, input().split())
    edges[a-1].append([b-1, c])
    edges[b-1].append([a-1, c])


def dijkstra(num_of_node, edge, start, limit):
    distance = [float('INF')] * num_of_node
    reachable = []
    distance[start] = 0
    todo = []
    heapq.heapify(todo)
    heapq.heappush(todo, [0, start])

    while todo:
        d, node = heapq.heappop(todo)
        if d > limit:
            break
        reachable.append(node)
        for new_node, cost in edge[node]:
            if distance[new_node] > d + cost:
                distance[new_node] = d + cost
                heapq.heappush(todo, [d+cost, new_node])

            else:
                continue
    return reachable


L_edges = [[]*n for _ in range(n)]

for i in range(n):
    L_edges[i] = dijkstra(n, edges, i, full)

dist = [[float('INF')] * n for _ in range(n)]

for start in range(n):
    dist[start][start] = 0
    todo = deque([])
    todo.append([-1, start])

    while todo:
        d, node = todo.popleft()

        for new_node in L_edges[node]:
            if dist[start][new_node] > d + 1:
                dist[start][new_node] = d + 1
                todo.append([d+1, new_node])

            else:
                continue

Q = int(input())
for i in range(Q):
    s, t = map(int, input().split())
    ans = dist[s-1][t-1]
    if ans == float('INF'):
        ans = -1
    print(ans)
Problem p02901 (python)

Fixed submission:
n, m = map(int, input().split())

keys = []

for i in range(m):
    cost, num = map(int, input().split())
    C = list(map(int, input().split()))
    can_open = 0
    for c in C:
        can_open += 2 ** (c-1)
    keys.append([cost, can_open])

DP = {}
for i in range(2**n):
    DP[i] = float('INF')
DP[0] = 0

for cost, can_open in keys:
    for key in DP.keys():
        pre_cost = DP[key]
        next_key = key | can_open
        DP[next_key] = min(DP[next_key], pre_cost+cost)


full_open = (1 << n) - 1

if DP[full_open] == float('INF'):
    print(-1)
else:
    print(DP[full_open])

Buggy submission (verdict: Runtime Error):
def main():
    n, m = map(int, input().split())
	all_patterns = 2**n
    DP = [10**9] * all_patterns
    DP[0] = 0
    for _ in range(m):
        cost, types = map(int, input().split())
        to_open = list(map(int, input().split()))

        openable = 0
        for open in to_open:
            openable += 1 << (open-1)

        for opened in range(all_patterns):
            pattern = opened | openable
            new_cost = DP[opened] + cost
            if DP[pattern] > new_cost:
                DP[pattern] = new_cost

    full_open = 2**n - 1
    ans = DP[full_open]

    if ans == 10 ** 9:
        ans = -1

    print(ans)

if __name__ == '__main__':
    main()
Problem p02902 (python)

Fixed submission:
n, m = map(int, input().split())
edges = [[] for _ in range(n)]

for _ in range(m):
    a, b = map(int, input().split())
    edges[a-1].append(b-1)


def get_first_cycle(n, edges):
    seen = [-1] * n  # seen: -1: 未確認, 0: 非cycleのnode, 1: cycle候補
    for start in range(n):
        if seen[start] == 0:
            continue
        seen[start] = 1
        path = [start]
        while path:
            now = path[-1]
            if not edges[now]:
                path.pop()
                seen[now] = 0
                continue

            next_node = edges[now].pop()
            if seen[next_node] == -1:
                path.append(next_node)
                seen[next_node] = 1

            elif seen[next_node] == 1:
                idx = path.index(next_node)
                cycle = path[idx:]
                return cycle
    return False


cycle = get_first_cycle(n, edges)
if not cycle:
    print(-1)
    exit()

nodes = set(cycle)
length = len(cycle)
i = 0
while i < length:
    now = cycle[i]
    routes = edges[now]
    while routes:
        to = routes.pop()
        if to in nodes:
            update = True
            idx = cycle.index(to)
            cycle = cycle[:i+1] + cycle[idx:]
            nodes = set(cycle)
            length = len(cycle)
            break
    i += 1

print(len(cycle))
for node in cycle:
    print(node+1)

Buggy submission (verdict: Runtime Error):
from collections import deque


n, m = map(int, input().split())
edges = [set() for _ in range(n)]
r_edges = [set() for _ in range(n)]
out_deg = [0]*n

for _ in range(m):
    a, b = map(int, input().split())
    edges[a-1].add(b-1)
    r_edges[b-1].add(a-1)
    out_deg[a-1] += 1

out_deg_node = sorted(range(len(out_deg)), key=lambda k: out_deg[k])
ng_node = set()

for node in out_deg_node:
    if out_deg[node] == 0:
        for rev in r_edges[node]:
            out_deg[rev] -= 1

        ng_node.add(node)
        edges[node] = []

    else:
        break

for i in range(n):
    edges[i] -= ng_node


def bfs(node):
    seen = [0] * n
    todo = deque([])
    for to in edges[node]:
        todo.append([to, 1, {to}])

    while todo:
        now, distance, path = todo.popleft()
        seen[now] = distance
        if now == node:
            return distance, path

        for next_node in edges[now]:  # type: int
            if seen[next_node] != 0:
                continue
            new_path = path | {next_node}
            todo.append([next_node, distance + 1, new_path])

    return float('INF'), set()


cycle_size = [float('INF')] * n
cycle_nodes = [set()] * n

for i in range(n):
    if i in ng_node:
        continue
    cycle_size[i], cycle_nodes[i] = bfs(i)

mini_cycle = min(cycle_size)
if mini_cycle == float('INF'):
    print(-1)
else:
    idx = cycle_size.index(mini_cycle)
    ans = cycle_nodes[idx]
    print(mini_cycle)
    for node in ans:
        print(node+1)