Problem:


Score : 500 points

Problem Statement

Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G.
G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.

First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.

Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq \min(10^5, N (N-1))

1 \leq u_i, v_i \leq N(1 \leq i \leq M)

u_i \neq v_i (1 \leq i \leq M)

If i \neq j, (u_i, v_i) \neq (u_j, v_j).

1 \leq S, T \leq N

S \neq T

Input

Input is given from Standard Input in the following format:

N M
u_1 v_1
:
u_M v_M
S T

Output

If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1.
If he can, print the minimum number of ken-ken-pa needed to reach vertex T.

Sample Input 1

4 4
1 2
2 3
3 4
4 1
1 3

Sample Output 1

2

Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.

Sample Input 2

3 3
1 2
2 3
3 1
1 2

Sample Output 2

-1

Any number of ken-ken-pa will bring Ken back to Vertex 1, so he cannot reach Vertex 2, though he can pass through it in the middle of a ken-ken-pa.

Sample Input 3

2 0
1 2

Sample Output 3

-1

Vertex S and Vertex T may be disconnected.

Sample Input 4

6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6

Sample Output 4

2



Sample input:
4 4
1 2
2 3
3 4
4 1
1 3


Sample output:
2

Submission status: Wrong Answer

Solution code:
from collections import deque

N, M = map(int, input().split())

graph = [[] for _ in range(N)]

for i in range(M):
    u, v = map(int, input().split())
    graph[u - 1].append(v - 1)

S, T = map(int, input().split())
S -= 1
T -= 1

q = deque([(S, 0)])
visited = [[0]*3 for _ in range(N)]
visited[S][0] = 1

res = -1
while q:
    v = q.pop()
    for n_v in graph[v[0]]:
        n_dist = v[1] + 1
        if n_v == T and n_dist % 3 == 0:
            res = n_dist // 3
            break
        if visited[n_v][n_dist % 3] <= 2:
            visited[n_v][n_dist % 3] += 1
            q.append((n_v, n_dist))

print(res)

Submission status: Wrong Answer

Solution code:
from collections import deque

N, M = map(int, input().split())

graph = [[] for _ in range(N)]

for i in range(M):
    u, v = map(int, input().split())
    graph[u - 1].append(v - 1)

S, T = map(int, input().split())
S -= 1
T -= 1

q = deque([(S, 0)])
visited = [[0]*3 for _ in range(N)]
visited[S][0] = 1

res = -1
while q:
    v = q.pop()

    for n_v in graph[v[0]]:
        n_dist = v[1] + 1
        if n_v == T and n_dist % 3 == 0:
            res = n_dist // 3
            break
        if not visited[n_v][n_dist % 3]:
            visited[n_v][n_dist % 3] = 1
            q.append((n_v, n_dist))

print(res)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix

def main():

  n,m=map(int,input().split())
  d=[[0 for i in range(n)] for i in range(n)]
  to=[[] for i in range(n)]
  for i in range(m):
    u,v=map(lambda x:int(x)-1,input().split())
    to[u].append(v)
  s,t=map(lambda x:int(x)-1,input().split())

  #print(to)

  # calc d (after 3 times dist)
  for i in range(n):
    first,second=[],[]
    for j in to[i]:
      first.append(j) # ken
    for j in first:
      for k in to[j]:
        second.append(k) # ken
    for j in second:
      for k in to[j]:
        d[i][k]=1 # pa

  #ans=dijkstra(csr_matrix(d),indices=s).astype(int)
  #print(ans[t] if ans[t]>0 else -1)


if __name__=='__main__':
  main()

Submission status: Wrong Answer

Solution code:
from collections import deque
n, m = map(int, input().split())
edges = [[] for _ in range(n)]
for _ in range(m):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    edges[u].append(v)

s, t = map(int, input().split())
s -= 1
t -= 1
#dfs
from_s = [[-1]*3 for _ in range(n)]
d_s = deque()
d_s.append((s, 0))
from_s[s][0] = 0
while d_s:
    p, count = d_s.pop()
    next_count = (count + 1) % 3
    for c in edges[p]:
        if from_s[c][next_count] != -1:
            continue
        from_s[c][next_count] = from_s[p][count] + 1
        d_s.append((c, next_count))
if from_s[t] == -1:
    print(-1)
else:
    print(from_s[t][0]//3)

Submission status: Wrong Answer

Solution code:
from collections import deque
n, m = map(int, input().split())
edges = [[] for _ in range(n)]
for _ in range(m):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    edges[u].append(v)

s, t = map(int, input().split())
s -= 1
t -= 1
#dfs
from_s = [[-1]*3 for _ in range(n)]
d_s = deque()
d_s.append(s)
from_s[s][0] = 0
count = 0
while d_s:
    p = d_s.pop()
    next_count = (count + 1) % 3
    for c in edges[p]:
        if from_s[c][next_count] != -1:
            continue
        from_s[c][next_count] = from_s[p][count] + 1
        d_s.append(c)
    count = next_count
if from_s[t] == -1:
    print(-1)
else:
    print(from_s[t][0]//3)

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
to = [[] for i in range(N+1)]
for i in range(M):
    a, b = map(int, input().split())
    to[a].append(b)

S, T = map(int, input().split())

q = [(S, 0)]
v = [[-1] * 3 for i in range(N+1)]

while q != []:
    a, t = q.pop()
    b = t % 3
    if v[a][b] != -1:
        continue
    v[a][b] = t
    t += 1
    for x in to[a]:
        q.append((x, t))

if v[T][0] == -1:
    print("-1")
else:
    print(v[T][0] // 3)

Submission status: Wrong Answer

Solution code:
# ABC132 E
from collections import deque

f=lambda:map(int,input().split())
N,M=f()
G=[[] for _ in [0]*(N+1)]
for _ in [0]*M:
    a,b=f()
    G[a].append(b)
S,T=f()
S=(S,0)
T=(T,0)

q=deque()
q.append(S)
F=set()
res=-1
while q:
    node,r=q.pop()
    if (node,r%3) in F:
        continue
    if (node,r%3) == T:
        res=r//3
        break
    F.add((node,r%3))
    for next_node in G[node]:
        if (next_node,(r+1)%3) in F:
            continue
        q.append((next_node,r+1))
print(res)

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())

G = [[] for _ in range(N)]
for i in range(M):
    u, v = map(lambda x: int(x) - 1, input().split())
    G[u].append(v)
    G[v].append(u)

print(G)

S, T = map(int, input().split())

G2 = [[] for _ in range(N)]

for i in range(N):
    # 1歩で行ける頂点
    x1 = set(G[i])
    print(i, x1)
    # 2歩で行ける頂点
    x2 = set()
    for j in x1:
        tmp = G[j]
        for k in tmp:
            x2.add(k)
    print(i, x2)
    x3 = set()
    for j in x2:
        tmp = G[j]
        for k in tmp:
            x3.add(k)
    print(i, x3)
    G2[i] = list(x3)

print(G2)

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())

G = [[] for _ in range(N)]
for i in range(M):
    u, v = map(lambda x: int(x) - 1, input().split())
    G[u].append(v)
    G[v].append(u)

S, T = map(int, input().split())

G2 = [[] for _ in range(N)]

for i in range(N):
    # 1歩で行ける頂点
    x1 = set(G[i])
    print(i, x1)
    # 2歩で行ける頂点
    x2 = set()
    for j in x1:
        tmp = G[i]
        for k in tmp:
            x2.add(j)
    print(i, x2)
    x3 = set()
    for j in x2:
        tmp = G[i]
        for k in tmp:
            x3.add(j)
    print(i, x3)
    G2[i] = list(x3)

print(G2)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict
from queue import Queue


def main():
    input = sys.stdin.buffer.readline
    n, m = map(int, input().split())
    path = defaultdict(list)
    for _ in range(m):
        u, v = map(int, input().split())
        path[u].append(v)
    s, t = map(int, input().split())
    visited = [False] * 110000
    q = Queue()
    q.put((s, 0))
    visited[s] = True
    while not q.empty():
        now, num_move = q.get()
        if visited[now]:
            continue
        for nxt_1 in path[now]:
            for nxt_2 in path[nxt_1]:
                for nxt_3 in path[nxt_2]:
                    if nxt_3 == t:
                        print(num_move + 1)
                        sys.exit()
                    if not visited[nxt_3]:
                        q.put((nxt_3, num_move + 1))
        visited[now] = True
    print(-1)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
n, m = map(int, input().split())

graph = [[] for _ in range(n+1)]
for _ in range(m):
    u, v = map(int, input().split())
    graph[u].append(v)

s, t = map(int, input().split())

inf = 10**10
dist = [[-3] * 3 for _ in range(n+1)]
dist[s][0] = 0

q = deque([(s, 0)])

while q:
    now, c = q.pop()
    ne = (c+1) % 3
    for node in graph[now]:
        if dist[node][ne] != -3:
            continue
        dist[node][ne] = dist[now][c] + 1
        q.append((node, ne))

print(dist[t][0] // 3)

Submission status: Wrong Answer

Solution code:
from collections import deque
n, m = map(int, input().split())

graph = [[] for _ in range(n+1)]
for _ in range(m):
    u, v = map(int, input().split())
    graph[u].append(v)

s, t = map(int, input().split())

inf = 10**10
dist = [[-3] * 3 for _ in range(n+1)]
dist[s][0] = 0

q = deque([(s, 0)])

while q:
    now, c = q.pop()
    ne = (c+1) % 3
    for node in graph[now]:
        if dist[node][ne] != -1:
            continue
        dist[node][ne] = dist[now][c] + 1
        q.append((node, ne))

print(dist[t][0] // 3)

Submission status: Wrong Answer

Solution code:
from collections import deque
n, m = map(int, input().split())

graph = [[] for _ in range(n+1)]
for _ in range(m):
    u, v = map(int, input().split())
    graph[u].append(v)

s, t = map(int, input().split())

inf = 10**10
dist = [[-1] * 3 for _ in range(n+1)]
dist[s][0] = 0

q = deque([(s, 0)])

while q:
    now, c = q.pop()
    ne = (c+1) % 3
    for node in graph[now]:
        if dist[node][ne] != -1:
            continue
        dist[node][ne] = dist[now][c] + 1
        q.append((node, ne))

print(dist[t][0] // 3)

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())

graph = [[] for i in range(N)]

for i in range(M):
  u,v = map(int,input().split())
  graph[u - 1].append(v - 1)

S,T = map(int,input().split())
S -= 1
T -= 1

from collections import deque
q = deque([])
q.append([S, 0, 0])

seen = set()

while q:
  v,cost,step = q.pop()
  if step == 0:
    if v == T:
      print(cost)
      break
    if v in seen:
      continue
    seen.add(v)
    cost += 1
    step = 3
  step -= 1
  for u in graph[v]:
    q.append([u, cost, step])
else:
  print(-1)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix

input = sys.stdin.readline

int1 = lambda x: int(x) - 1
N, M = map(int, input().split())

if M == 0:
    print(-1)
    exit()

UV = np.array([tuple(map(int1, input().split())) for _ in range(M)])
frm = UV[:, 0].repeat(3) + np.tile(np.arange(3), M)
to = UV[:, 1].repeat(3) + np.tile((np.arange(3) + 1) % 3, M)

S, T = map(int1, input().split())
matr = csr_matrix(([1] * (3 * M), (frm, to)), shape=(3 * N, 3 * N))
way = dijkstra(matr, indices=3 * S).astype(int)

res = way[3 * T]
print(res // 3 if res >= 0 else -1)

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
e=[[]for _ in range(3*(n+1))]
d=[-3]*(3*(n+1))
for _ in range(m):
  a,b=map(int,input().split())
  e[a]+=[b+n]
  e[a+n]+=[b+2*n]
  e[a+2*n]+=[b]
s,t=map(int,input().split())
q=[s]
d[s]=0
while q:
  now=q.pop()
  for to in e[now]:
    if d[to]!=-3:continue
    d[to]=d[now]+1
    q+=[to]
print(d[t]//3)

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
e=[[]for _ in range(3*(n+1))]
d=[-3]*(3*(n+1))
for _ in range(m):
  a,b=map(int,input().split())
  e[3*a]+=[3*b+1]
  e[3*a+1]+=[3*b+2]
  e[3*a+2]+=[3*b]
s,t=map(int,input().split())
q=[3*s]
d[3*s]=0
while q:
  now=q.pop()
  for to in e[now]:
    if d[to]!=-3:continue
    d[to]=d[now]+1
    q+=[to]
print(d[3*t]//3)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():

    ##########################################
    import heapq
    class Dijkstra():
        """
        ・有向 / 無向は問わない(無向の場合は，逆向きの辺もたす)
        ・負のコストがない場合のみ
        ・計算量はO(E log|V|)　
        ・heapを使うことで頂点を走査する必要がなくなる（代わりに，距離更新したものは確定でなくともqueに入れておく）
        ・復元なし
        """

        #最短のpathをたす


        class Edge():
            #重み付き有向辺

            def __init__(self, _to, _cost):
                self.to =_to
                self.cost = _cost

        def __init__(self, V):
            #引数Vは頂点数
            self.inf=10**20
            self.G = [[] for _ in range(V)] #隣接リストG[u][i]が頂点uのi番目の辺
            self. _E = 0 #辺の数
            self._V = V #頂点数

        #proparty - 辺の数
        def E(self):
            return self._E

        #proparty - 頂点数
        def V(self):
            return self._V

        def add(self, _from, _to, _cost):
            #2頂点と辺のコストを追加
            self.G[_from].append(self.Edge(_to,_cost))
            self._E +=1

        def add2(self, _from, _to, _cost):
            #2頂点と辺のコスト（無向）を追加
            self.G[_from].append(self.Edge(_to, _cost))
            self.G[_to].append(self.Edge(_from, _cost))
            self._E +=2

        def shortest_path(self,s):#,g):
            #始点sから頂点iまでの最短経路長のリストを返す
            que = [] #priority queue
            d = [self.inf] * self.V()

            #prev = [None]*self.V() #prev[j]は，sからjへ最短経路で行くときのjの一つ前の場所
            #復元で使う

            d[s] = 0
            heapq.heappush(que,(0,s)) #始点の距離と頂点番号をヒープに追加

            while len(que)!=0:
                #キューに格納されてある中で一番コストが小さい頂点を取り出す
                cost,v = heapq.heappop(que)

                #キューに格納された最短経路長候補がdの距離よりも大きい場合に処理をスキップ
                if d[v] < cost:
                    continue

                #頂点vに隣接する各頂点iに対して，vを経由した場合の距離を計算して，これがd[i]よりも小さい場合に更新
                for i in range(len(self.G[v])):
                    e = self.G[v][i] #vのi個目の隣接辺
                    if d[e.to] > d[v] + e.cost:
                        d[e.to] = d[v] + e.cost #更新

                        #prev[e.to] = v
                        #復元で使う

                        heapq.heappush(que,(d[e.to],e.to)) #queに新たな最短経路長候補を追加

            """#sからgまでの最短経路
            path = []
            pos = g #今いる場所，ゴールで初期化
            for _ in range(self.V()+1):
                path.append(pos)
                if pos == s:
                    break
                #print("pos:",format(pos))
                pos = prev[pos]
            path.reverse()
            #print(path)"""

            return d#,path
    ########################
    mod=10**9+7
    N,M=MI()
    djk=Dijkstra(3*N)
    for _ in range(M):
        u,v=MI()
        u-=1
        v-=1
        djk.add(u,v+N,1)
        djk.add(u+N,v+2*N,1)
        djk.add(u+2*N,v,1)
    S,T=MI()
    S-=1
    T-=1
    D=djk.shortest_path(S)
    ans=D[T+2*N]
    
    if ans>10**10:
        ans=-1
        
    print(ans)
        
    


main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, M: int, u: "List[int]", v: "List[int]", S: int, T: int):
    import numpy as np
    from scipy.sparse import csr_matrix
    from scipy.sparse.csgraph import dijkstra
    N = N + 1
    u = np.array(u, dtype=np.int32)
    v = np.array(v, dtype=np.int32)
    u = np.concatenate([u, u+N, u+2*N])
    v = np.concatenate([v+N, v+2*N, v])
    mat = dijkstra(csr_matrix((np.ones(3*M), (u, v)), shape=(3*N, 3*N), dtype=np.int32),
                   indices=S, directed=True)    
    return -1 if np.isinf(mat[2*N+T]) else int(mat[2*N+T])

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    u = [int()] * (M)  # type: "List[int]"
    v = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        u[i] = int(next(tokens))
        v[i] = int(next(tokens))
    S = int(next(tokens))  # type: int
    T = int(next(tokens))  # type: int
    print(solve(N, M, u, v, S, T))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, M: int, u: "List[int]", v: "List[int]", S: int, T: int):
    import numpy as np
    from scipy.sparse import csr_matrix
    from scipy.sparse.csgraph import dijkstra
    N = N + 1
    u = np.array(u, dtype=np.int32)
    v = np.array(v, dtype=np.int32)
    u = np.concatenate([u, u+N, u+2*N])
    v = np.concatenate([v+N, v+2*N, v])
    mat = dijkstra(csr_matrix((np.ones(3*M), (u, v)), shape=(3*N, 3*N), dtype=np.int32),
                   indices=S, directed=False)    
    return -1 if np.isinf(mat[2*N+T]) else int(mat[2*N+T])

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    u = [int()] * (M)  # type: "List[int]"
    v = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        u[i] = int(next(tokens))
        v[i] = int(next(tokens))
    S = int(next(tokens))  # type: int
    T = int(next(tokens))  # type: int
    print(solve(N, M, u, v, S, T))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(200000)

N,M=map(int,input().split())
ways=[[] for _ in range(N)]
for i in range(M):
  u,v=map(int,input().split())
  ways[u-1].append(v-1)
  
s,t=map(int,input().split())
  
nways=[[] for _ in range(N)]
def go(p,nord,step):
  global nways
  if step==3:
    nways[p].append(nord)
    return
  for way in ways[nord]:
    go(p,way,step+1)
    
for i in range(N):
  go(i,i,0)

print(nways)

Submission status: Wrong Answer

Solution code:
N,M=map(int,input().split())
list=[[] for i in range(3*N)]
for i in range(M):
  u,v=map(int,input().split())
  list[3*u-3].append(3*v-2)
  list[3*u-2].append(3*v-1)
  list[3*u-1].append(3*v-3)
s,t=map(int,input().split())
def bfs(a,b):
  visited=[-1 for i in range(3*N)]
  visited[a]=0
  h=[]
  h.append(a)
  while h:
    v=h.pop(0)
    for k in list[v]:
      if visited[k]==-1:
        visited[k]=visited[v]+1
        h.append(k)
  return visited[b]

print(bfs(3*s-3,3*t-1))

Submission status: Wrong Answer

Solution code:
from collections import deque
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix


def bfs(cnt, p, cn, row, col, data):
    cnt += 1
    if cnt < 3:
        for cg in graph[p]:
            d.appendleft([cnt, cg])
    if cnt == 3:
        for cg in graph[p]:
            if not cg in graph_k[cn]:
                graph_k[cn].append(cg)
                row = np.append(row, cn)
                col = np.append(col, cg)
                data = np.append(data, 1)
    return cnt, row, col, data

n, m = map(int,input().split())
edge = []
graph = [[] for i in range(n+1)]
for i in range(m):
    edge.append(list(map(int,input().split())))
    graph[edge[-1][0]].append(edge[-1][1])
s, g = map(int,input().split())

row = np.array([], dtype=int)
col = np.array([], dtype=int)
data = np.array([], dtype=int)

d = deque()
graph_k = [[] for i in range(n+1)]
for cn in range(1, n+1):
    for cg in graph[cn]:
        d.appendleft([1, cg])
    while d:
        cnt, p = d.pop()
        cnt, row, col, data = bfs(cnt, p, cn, row, col, data)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque


class Graph:
    def __init__(self, n, directed=False, decrement=True, destroy=False, edges=[]):
        self.n = n
        self.directed = directed
        self.decrement = decrement
        self.destroy = destroy
        self.edges = [set() for _ in range(self.n)]
        self.visited = [0]*self.n
        self.visited2 = [0]*self.n
        self.info = [-1]*self.n
        for x, y in edges:
            self.add_edge(x,y)

    def add_edge(self, x, y):
        if self.decrement:
            x -= 1
            y -= 1
        self.edges[x].add(y)
        if self.directed == False:
            self.edges[y].add(x)

    def add_adjacent_list(self, i, adjacent_list):
        if self.decrement:
            self.edges[i] = set(map(lambda x: x - 1, adjacent_list))
        else:
            self.edges[i] = set(adjacent_list)

    def bfs(self, start=1, goal=-1, time=0, save=False):
        """
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: （ループがあっても）最短距離。存在しなければ -1
        """
        if self.decrement:
            start -= 1
            goal -= 1
        if not save:
            self.visited = [0] * self.n
        p, t = start, time
        self.visited[p] = 1
        self.visited2[p] = 1
        data1[p] = 0
        next_set = deque([(p, t)])
        i = 0
        while next_set:
            p, t = next_set.popleft()
            for q in self.edges[p]:
                i += 1
                if i > 10**7:
                    return -1
                if (t+1)%3==0:
                    if self.visited2[q] == 1:
                        continue
                    if q == goal:
                        return (t+1)//3
                    self.visited2[q] = 1
                if self.visited[q]==0:
                    data1[q] = t+1
                if self.visited[q]==1:
                    data2[q] = t+1
                self.visited[q] += 1
                next_set.append((q, t + 1))
        return -1

##################################################################################################

N, M = map(int, input().split())
graph = Graph(N, directed=True, decrement=True, destroy=False)
for _ in range(M):
    x, y = map(int, input().split())
    graph.add_edge(x, y)
S, T = map(int, input().split())
data1 = [0]*N
data2 = [0]*N

res = graph.bfs(start=S, goal=T)
if res != -1:
    print(res)
    exit()

if data1[T-1]==0:
    print(-1)
    exit()

if data1[T-1]%3==0:
    print(data1[T-1]//3)
else:
    d = data2[T-1] - data1[T-1]
    if d%3==0:
        print(-1)
    else:
        temp = data1[T-1]
        while temp%3!=0:
            temp += d
        print(temp//3)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque


class Graph:
    def __init__(self, n, directed=False, decrement=True, destroy=False, edges=[]):
        self.n = n
        self.directed = directed
        self.decrement = decrement
        self.destroy = destroy
        self.edges = [set() for _ in range(self.n)]
        self.visited = [0]*self.n
        self.visited2 = [0]*self.n
        self.info = [-1]*self.n
        for x, y in edges:
            self.add_edge(x,y)

    def add_edge(self, x, y):
        if self.decrement:
            x -= 1
            y -= 1
        self.edges[x].add(y)
        if self.directed == False:
            self.edges[y].add(x)

    def add_adjacent_list(self, i, adjacent_list):
        if self.decrement:
            self.edges[i] = set(map(lambda x: x - 1, adjacent_list))
        else:
            self.edges[i] = set(adjacent_list)

    def bfs(self, start=1, goal=-1, time=0, save=False):
        """
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: （ループがあっても）最短距離。存在しなければ -1
        """
        if self.decrement:
            start -= 1
            goal -= 1
        if not save:
            self.visited = [0] * self.n
        p, t = start, time
        self.visited[p] = 1
        self.visited2[p] = 1
        data1[p] = 0
        next_set = deque([(p, t)])
        i = 0
        while next_set:
            p, t = next_set.popleft()
            for q in self.edges[p]:
                i += 1
                if i > 10**7:
                    return -1
                if (t+1)%3==0:
                    if q == goal:
                        return (t+1)//3
                    self.visited2[q] = 1
                if self.visited[q]==0:
                    data1[q] = t+1
                if self.visited[q]==1:
                    data2[q] = t+1
                self.visited[q] += 1
                next_set.append((q, t + 1))
        return -1

##################################################################################################

N, M = map(int, input().split())
graph = Graph(N, directed=True, decrement=True, destroy=False)
for _ in range(M):
    x, y = map(int, input().split())
    graph.add_edge(x, y)
S, T = map(int, input().split())
data1 = [0]*N
data2 = [0]*N

res = graph.bfs(start=S, goal=T)
if res != -1:
    print(res)
    exit()

if data1[T-1]==0:
    print(-1)
    exit()

if data1[T-1]%3==0:
    print(data1[T-1]//3)
else:
    d = data2[T-1] - data1[T-1]
    if d%3==0:
        print(-1)
    else:
        temp = data1[T-1]
        while temp%3!=0:
            temp += d
        print(temp//3)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque


class Graph:
    def __init__(self, n, directed=False, decrement=True, destroy=False, edges=[]):
        self.n = n
        self.directed = directed
        self.decrement = decrement
        self.destroy = destroy
        self.edges = [set() for _ in range(self.n)]
        self.visited = [0]*self.n
        self.visited2 = [0]*self.n
        self.info = [-1]*self.n
        for x, y in edges:
            self.add_edge(x,y)

    def add_edge(self, x, y):
        if self.decrement:
            x -= 1
            y -= 1
        self.edges[x].add(y)
        if self.directed == False:
            self.edges[y].add(x)

    def add_adjacent_list(self, i, adjacent_list):
        if self.decrement:
            self.edges[i] = set(map(lambda x: x - 1, adjacent_list))
        else:
            self.edges[i] = set(adjacent_list)

    def bfs(self, start=1, goal=-1, time=0, save=False):
        """
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: （ループがあっても）最短距離。存在しなければ -1
        """
        if self.decrement:
            start -= 1
            goal -= 1
        if not save:
            self.visited = [0] * self.n
        p, t = start, time
        self.visited[p] = 1
        self.visited2[p] = 1
        data1[p] = 0
        next_set = deque([(p, t)])
        i = 0
        while next_set:
            p, t = next_set.popleft()
            for q in self.edges[p]:
                i += 1
                if i > 5*10**6:
                    return -1
                if (t+1)%3==0:
                    if self.visited2[q] == 1:
                        continue
                    if q == goal:
                        return (t+1)//3
                    self.visited2[q] = 1
                if self.visited[q]==0:
                    data1[q] = t+1
                if self.visited[q]==1:
                    data2[q] = t+1
                self.visited[q] += 1
                next_set.append((q, t + 1))
        return -1

##################################################################################################

N, M = map(int, input().split())
graph = Graph(N, directed=True, decrement=True, destroy=False)
for _ in range(M):
    x, y = map(int, input().split())
    graph.add_edge(x, y)
S, T = map(int, input().split())
data1 = [0]*N
data2 = [0]*N

res = graph.bfs(start=S, goal=T)
if res != -1:
    print(res)
    exit()

if data1[T-1]==0:
    print(-1)
    exit()

if data1[T-1]%3==0:
    print(data1[T-1]//3)
else:
    d = data2[T-1] - data1[T-1]
    if d%3==0:
        print(-1)
    else:
        temp = data1[T-1]
        while temp%3!=0:
            temp += d
        print(temp//3)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque


class Graph:
    def __init__(self, n, directed=False, decrement=True, destroy=False, edges=[]):
        self.n = n
        self.directed = directed
        self.decrement = decrement
        self.destroy = destroy
        self.edges = [set() for _ in range(self.n)]
        self.visited = [0]*self.n
        self.visited2 = [0]*self.n
        self.info = [-1]*self.n
        for x, y in edges:
            self.add_edge(x,y)

    def add_edge(self, x, y):
        if self.decrement:
            x -= 1
            y -= 1
        self.edges[x].add(y)
        if self.directed == False:
            self.edges[y].add(x)

    def add_adjacent_list(self, i, adjacent_list):
        if self.decrement:
            self.edges[i] = set(map(lambda x: x - 1, adjacent_list))
        else:
            self.edges[i] = set(adjacent_list)

    def bfs(self, start=1, goal=-1, time=0, save=False):
        """
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: （ループがあっても）最短距離。存在しなければ -1
        """
        if self.decrement:
            start -= 1
            goal -= 1
        if not save:
            self.visited = [0] * self.n
        p, t = start, time
        self.visited[p] = 1
        self.visited2[p] = 1
        data1[p] = 0
        next_set = deque([(p, t)])
        i = 0
        while next_set:
            p, t = next_set.popleft()
            for q in self.edges[p]:
                i += 1
                if i > 5*10**6:
                    return -1
                if (t+1)%3==0:
                    if self.visited[q] == 1:
                        continue
                    if q == goal:
                        return (t+1)//3
                    self.visited2[q] = 1
                if self.visited[q]==0:
                    data1[q] = t+1
                if self.visited[q]==1:
                    data2[q] = t+1
                self.visited[q] += 1
                next_set.append((q, t + 1))
        return -1

##################################################################################################

N, M = map(int, input().split())
graph = Graph(N, directed=True, decrement=True, destroy=False)
for _ in range(M):
    x, y = map(int, input().split())
    graph.add_edge(x, y)
S, T = map(int, input().split())
data1 = [0]*N
data2 = [0]*N

res = graph.bfs(start=S, goal=T)
if res != -1:
    print(res)
    exit()

if data1[T-1]==0:
    print(-1)
    exit()

if data1[T-1]%3==0:
    print(data1[T-1]//3)
else:
    d = data2[T-1] - data1[T-1]
    if d%3==0:
        print(-1)
    else:
        temp = data1[T-1]
        while temp%3!=0:
            temp += d
        print(temp//3)