Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Depth First Search

  Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.

  This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.

  DFS timestamps each vertex as follows:

$d[v]$ records when $v$ is first discovered.

$f[v]$ records when the search finishes examining $v$’s adjacency list.

  Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:

$G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.

IDs in the adjacency list are arranged in ascending order.

The program should report the discover time and the finish time for each vertex.

When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.

The timestamp starts with 1.

Input

  In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.

Output

  For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 100$

Sample Input 1

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

Sample Output 1

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

Sample Input 2

6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0

Sample Output 2

1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6

  This is example for Sample Input 2 (discover/finish)

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



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


Sample output:
1 1 8
2 2 7
3 4 5
4 3 6

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Jul  8 10:56:33 2018

@author: maezawa
"""
n = int(input())
adj = [[] for _ in range(n)]
d = [0 for _ in range(n)]
f = [0 for _ in range(n)]

for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(k):
        adj[u-1].append(ain[i+2]-1)
    adj[u-1].sort()
    #print(*adj[u-1])

t = 1
stack = [0]

while stack:
    current = stack[-1]
    if d[current] == 0:
        d[current] = t
        t += 1
    flag = 0
    for k in adj[current]:
        if f[k] == 0:
            stack.append(k)
            flag = 1
            break
    if flag == 0:
        f[current] = t
        t += 1
        stack.pop()

    #print('current = {}, t = {}'.format(current, t))
    #print('stack', *stack)

for i in range(n):
    print('{} {} {}'.format(i+1, d[i], f[i]))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Jul  8 10:56:33 2018

@author: maezawa
"""
n = int(input())
adj = [[] for _ in range(n)]
d = [0 for _ in range(n)]
f = [0 for _ in range(n)]

for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(k):
        adj[u-1].append(ain[i+2]-1)
    adj[u-1].sort()
    #print(*adj[u-1])

t = 1
stack = [0]

while stack:
    print(stack)
    current = stack[-1]
    if d[current] == 0:
        d[current] = t
        t += 1
    flag = 0
    for k in adj[current]:
        if d[k] == 0:
            stack.append(k)
            flag = 1
            break
    if flag == 0:
        f[current] = t
        t += 1
        stack.pop()

    #print('current = {}, t = {}'.format(current, t))
    #print('stack', *stack)

for i in range(n):
    print('{} {} {}'.format(i+1, d[i], f[i]))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-


class Graph:
    def __init__(self, n, adj_matrix):
        self.n = n
        self.g = adj_matrix

    def show(self):
        for _ in self.g:
            print(*_)

    def dfs(self, u, init=False):
        if init:
            self.states = [1] * self.n
            self.stack = []
            self.d = [None] * self.n
            self.f = [None] * self.n
            self.time = 0

        self.states[u] = 0
        self.time += 1
        self.d[u] = self.time

        for v, edge in enumerate(self.g[u]):
            if edge and self.states[v]:
                self.dfs(v)

        self.states[u] = 0
        self.time += 1
        self.f[u] = self.time

    def show_dfs(self, start=0):
        self.dfs(u=start, init=True)
        for i, (d, f) in enumerate(zip(self.d, self.f)):
            print(i + 1, d, f)


if __name__ == '__main__':
    n = int(input())
    adj_matrix = [[0] * n for i in range(n)]
    for i in range(n):
        for v in input().split()[2:]:
            adj_matrix[i][int(v) - 1] = 1

    g = Graph(n, adj_matrix)
    g.show_dfs()

Submission status: Wrong Answer

Solution code:
n = int(input())
graph = [[0 for i in range(n)] for j in range(n)]
d = [0] * n
f = [0] * n
g = [0] * n

time = 0

for i in range(n):
   a = list(map(int, input().split()))
   for j in range(0, a[1], 1):
       graph[a[0] - 1][a[2 + j] - 1] = 1

def search(i):
    global time
    time = time + 1
    d[i] = time
    g[i] = 1
    for j in range(i, n):
        if (graph[i][j] == 1) & (g[j] == 0):
            search(j)
    time = time + 1
    f[i] = time if f[i] == 0 else f[i]


search(0)
[print(i+1, d[i], f[i]) for i in range(n)]

Submission status: Wrong Answer

Solution code:
n = int(input())
graph = [[0 for i in range(n)] for j in range(n)]
d = [0] * n
f = [0] * n
g = [0] * n

time = 0

for i in range(n):
   a = list(map(int, input().split()))
   for j in range(0, a[1], 1):
       graph[a[0] - 1][a[2 + j] - 1] = 1

def search(i):
    global time
    time = time + 1
    d[i] = time
    g[i] = 1
    for j in range(i, n):
        if (graph[i][j] == 1) & (g[j] == 0):
            search(j)
    time = time + 1
    f[i] = time


search(0)
[print(i+1, d[i], f[i]) for i in range(n)]

Submission status: Wrong Answer

Solution code:
def dfs(n):
    global t
    S[n] = t
    DP[n]=1
    for i in A[n][2:]:
        if not DP[i]:
            t += 1
            dfs(i)
    t += 1
    F[n] = t
n = int(input())
A = [0]*(n+1)
S = [0]*(n+1)
F = [0]*(n+1)
DP = [0]*(n+1)
for i in range(n):
    A[i+1] = [int(i) for i in input().split()]
t = 1
dfs(1)
for i in range(1,n+1):
    tmp = "{} {} {}".format(i,S[i],F[i])
    print(tmp)

Submission status: Wrong Answer

Solution code:
def dfs():
    tt = 0
    for u in range(N):
        if colors[u] == WHITE:
            dfs_visit(u, tt)

def dfs_visit(u, tt):
    tt += 1
    colors[u] = GLAY
    d[u] = tt
    for v in range(N):
        if adjacency_list[u][v] == 1 and colors[v] == WHITE:
            tt = dfs_visit(v, tt)
    tt += 1
    colors[u] = BLACK
    f[u] = tt
    return tt


N = int(input())
adjacency_list = [[0 for j in range(N)] for i in range(N)]
for _ in range(N):
    u, k, *v = map(int, input().split())
    for i in v:
        adjacency_list[u-1][i-1] = 1

WHITE = 0
GLAY = 1
BLACK = 2
colors = [WHITE for _ in range(N)]
d = [0 for _ in range(N)]
f = [0 for _ in range(N)]


dfs()

for i in range(N):
    print("{} {} {}".format(i+1, d[i], f[i]))

Submission status: Wrong Answer

Solution code:
def depth_search(u, t):
    t += 1
    s.append(u)
    d[u] = t
    for v in range(N):
        if adjacency_list[u][v] == 0:
            continue 
        if d[v] == 0 and v not in s:
            t = depth_search(v, t)
    t += 1
    s.pop()
    f[u] = t
    return t

N = int(input())
adjacency_list = [[0 for j in range(N)] for i in range(N)]
for _ in range(N):
    u, k, *v = input().split()
    for i in v:
        adjacency_list[int(u)-1][int(i)-1] = 1

s = []
d = [0 for _ in range(N)]
f = [0 for _ in range(N)]

t = 0
for u in range(N):
    if d[0] == 0:
        t = depth_search(u, t)

for i in range(N):
    print("{} {} {}".format(i+1, d[i], f[i]))

Submission status: Wrong Answer

Solution code:
#coding: utf-8

n = int(input())
color = ["white" for i in range(n)]
d = [[] for i in range(n)]
global t
t = 0
M = [[False for i in range(n)] for j in range(n)]
for i in range(n):
    data = list(map(int,input().split()))
    u = data[0]
    k = data[1]
    if i == 0:
        start = u
    for v in data[2:2+k]:
        M[u-1][v-1] = True


def search(u,t):
    t += 1
    color[u-1] = "gray"
    d[u-1].append(t)
    for v in range(n):
        if M[u-1][v-1] and color[v-1] == "white":
            t = search(v,t)
    color[u-1] = "black"
    t += 1
    d[u-1].append(t)
    return t

t = search(start, t)
for i in range(n):
    if color[i-1] == "white":
        t += 1
        t = search(i, t)

for i in range(n):
    print(i+1, d[i][0], d[i][1])

Submission status: Wrong Answer

Solution code:
#coding: utf-8

n = int(input())
color = ["white" for i in range(n)]
d = [[] for i in range(n)]
global t
t = 0
M = [[False for i in range(n)] for j in range(n)]
for i in range(n):
    data = list(map(int,input().split()))
    u = data[0]
    k = data[1]
    if i == 0:
        start = u
    for v in data[2:2+k]:
        M[u-1][v-1] = True


def search(u,t):
    t += 1
    color[u-1] = "gray"
    d[u-1].append(t)
    for v in range(n):
        if M[u-1][v-1] and color[v-1] == "white":
            t = search(v,t)
    color[u-1] = "black"
    t += 1
    d[u-1].append(t)
    return t

t = search(start, t)
for i in range(1,n+1):
    if color[i-1] == "white":
        t = search(i, t)

for i in range(n):
    print(i+1, d[i][0], d[i][1])

Submission status: Wrong Answer

Solution code:

#graphの頂点vertex(インデックス、0オリジン)を深さ優先探索。dis_time:最初に訪れた時のtimeを管理するリスト
#fin_time:その頂点に対して、探索が終わった時のtimeを管理するリスト　tmp_time:現在のtime(関数内で変更できるようにリスト)
def DPS(graph,vertex,dis_time,fin_time,tmp_time):
    dis_time[vertex]=tmp_time[0]
    for i in range(len(graph[0])):
        if(graph[vertex][i] !=0 and dis_time[i]==0):#枝先の頂点が探索済みでなかったら、
            tmp_time[0]+=1
            DPS(graph,i,dis_time,fin_time,tmp_time)
    
    if(dis_time[vertex]==tmp_time[0]):#vertexから、どの頂点に対しても調査が進まなかったら
        tmp_time[0]+=1
    fin_time[vertex]=tmp_time[0]
    tmp_time[0]+=1



#グラフの作成
n=int(input())
graph=[[0]*n for loop in range(n)]
for loop in range(n):
    tmp_ope=list(map(int,input().split()))
    for j in range(tmp_ope[1]):
        graph[tmp_ope[0]-1][tmp_ope[j+2]-1]=1

dis_time=[0]*n
fin_time=[0]*n
tmp_time=[1]
DPS(graph,0,dis_time,fin_time,tmp_time)

for i in range(n):
    print(f"{i+1} {dis_time[i]} {fin_time[i]}")

Submission status: Wrong Answer

Solution code:
def DPS(graph,vertex,dis_time,fin_time,tmp_time):
    dis_time[vertex]=tmp_time[0]
    for i in range(len(graph[0])):
        if(graph[vertex][i] !=0 and dis_time[i]==0):#枝先の頂点が探索済みでなかったら、
            tmp_time[0]+=1
            DPS(graph,i,dis_time,fin_time,tmp_time)
    
    if(dis_time[vertex]==tmp_time[0]):#vertexから、どの頂点に対しても調査が進まなかったら
        tmp_time[0]+=1
    fin_time[vertex]=tmp_time[0]
    tmp_time[0]+=1



#グラフの作成
n=int(input())
graph=[[0]*n for loop in range(n)]
for loop in range(n):
    tmp_ope=list(map(int,input().split()))
    for j in range(tmp_ope[1]):
        graph[tmp_ope[0]-1][tmp_ope[j+2]-1]=1


dis_time=[0]*n
fin_time=[0]*n
tmp_time=[1]
for i in range(n):
    if(dis_time[i]==0):
        DPS(graph,i,dis_time,fin_time,tmp_time)

for i in range(n):
    print(f"{i+1} {dis_time[i]} {fin_time[i]}")

Submission status: Wrong Answer

Solution code:
n = int(input())

adj = [0]*n # adjacent list

for i in range(n):
    tmp = list(map( int, input().split() ) )
    adj[tmp[0]-1] = list(map(lambda x : x - 1, tmp[2:]))

c = ['w']*n # color of each vertex
d = [0]*n # discovery time for each vertex
f = [0]*n  # finish time for each vertex
time = 0

def DFS_visit(u):
    global time
    time += 1
    d[u] = time
    c[u] = 'g'
    for v in adj[u]:
        if c[v] == 'w':
            DFS_visit(v)
    c[u] = 'b'
    time += 1
    f[u] = time
    
for u in range(n):
    if c[u] == 'w':
        DFS_visit(u)

Submission status: Wrong Answer

Solution code:
n = int(input())
graph = [[] for _ in range(n)]
for i in range(n):
    in_list = list(map(int, input().split()))
    u = in_list[0]
    graph[u - 1] = in_list[2:]

d = [0 for _ in range(n)]
f = [0 for _ in range(n)]
time = 0


def dfs(now, prev, graph, d, f):
    global time
    time += 1
    d[now] = time
    if not graph[now]:
        f[now] = time + 1
        time += 1
        return
    for k in graph[now]:
        if k - 1 == prev or d[k-1] !=0:
            continue
        dfs(k - 1, now, graph, d, f)
    else:
        time += 1
        f[now] = time
    return d, f


d, f = dfs(0, 0, graph, d, f)
for i in range(1, n + 1):
    print(i, d[i - 1], f[i - 1])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import sys
sys.setrecursionlimit(10 ** 9)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
INF=float('inf')

N=INT()
nodes=[[] for i in range(N)]
for i in range(N):
    l=LIST()
    u=l[0]
    l=l[2:]
    for v in l:
        nodes[u-1].append(v-1)
    nodes[u-1].sort()

ans=[[0]*2 for i in range(N)]
visited=[False]*N
time=0
def rec(u):
    if visited[u]:
        return
    visited[u]=True
    global time
    time+=1
    ans[u][0]=time
    for v in nodes[u]:
        rec(v)
    time+=1
    ans[u][1]=time

rec(0)
for i in range(N):
    d,f=ans[i]
    print(i+1, d, f)

Submission status: Wrong Answer

Solution code:
n = int(input())
A = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    u, k, *v = list(map(int, input().split()))
    for j in v:
        A[int(u)-1][int(j)-1] = 1
        A[int(j)-1][int(u)-1] = 1

# for row in A:
#     msg = ' '.join(map(str, row))
#     # print(msg)

d = [-1] * n
f = [-1] * n

t = 0
d[0] = t

# recursive


def dfs(u):
    global t
    # print('visit:', str(u), str(t))
    t += 1
    d[u] = t
    for i in range(len(A[u])):
        if A[u][i] == 1 and d[i] == -1:
            dfs(i)
    t += 1
    f[u] = t
            

dfs(0)


for i in range(n):
    print(str(i+1), str(d[i]), str(f[i]))

Submission status: Wrong Answer

Solution code:
n = int(input())
A = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    u, k, *v = list(map(int, input().split()))
    for j in v:
        A[int(u)-1][int(j)-1] = 1
        # A[int(j)-1][int(u)-1] = 1

# for row in A:
#     msg = ' '.join(map(str, row))
#     # print(msg)

d = [-1] * n
f = [-1] * n

t = 0
d[0] = t

# recursive


def dfs(u):
    global t
    # print('visit:', str(u), str(t))
    t += 1
    d[u] = t
    for i in range(len(A[u])):
        if A[u][i] == 1 and d[i] == -1:
            dfs(i)
    t += 1
    f[u] = t
            

dfs(0)


for i in range(n):
    print(str(i+1), str(d[i]), str(f[i]))

Submission status: Wrong Answer

Solution code:
n = int(input())
A = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    u, k, *v = list(map(int, input().split()))
    for j in v:
        A[int(u)-1][int(j)-1] = 1
        # A[int(j)-1][int(u)-1] = 1

# for row in A:
#     msg = ' '.join(map(str, row))
#     # print(msg)

d = [-1] * n
f = [-1] * n

t = 0
d[0] = t

# recursive


def dfs(u):
    global t
    # print('visit:', str(u), str(t))
    t += 1
    d[u] = t
    for i in range(len(A[u])):
        if A[u][i] == 1 and d[i] == -1:
            dfs(i)
    t += 1
    f[u] = t
            


for i in range(n):
    if d[i-1] == -1:
        dfs(i-1)


for i in range(n):
    print(str(i+1), str(d[i]), str(f[i]))

Submission status: Wrong Answer

Solution code:
n = int(input())
A = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    u, k, *v = list(map(int, input().split()))
    for j in v:
        A[int(u)-1][int(j)-1] = 1
        # A[int(j)-1][int(u)-1] = 1

# for row in A:
#     msg = ' '.join(map(str, row))
#     # print(msg)

d = [-1] * n
f = [-1] * n

t = 0

# recursive


def dfs(u):
    global t
    # print('visit:', str(u), str(t))
    t += 1
    d[u] = t
    for i in range(len(A[u])):
        if A[u][i] == 1 and d[i] == -1:
            dfs(i)
    t += 1
    f[u] = t
            


for i in range(n):
    if d[i-1] == -1:
        dfs(i-1)


for i in range(n):
    print(str(i+1), str(d[i]), str(f[i]))

Submission status: Wrong Answer

Solution code:
n = int(input())
A = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    u, k, *v = list(map(int, input().split()))
    for j in v:
        A[int(u)-1][int(j)-1] = 1
        # A[int(j)-1][int(u)-1] = 1

for row in A:
    msg = ' '.join(map(str, row))
    # print(msg)

d = [-1] * n
f = [-1] * n

t = 0

# # recursive
# def dfs(u):
#     global t
#     # print('visit:', str(u), str(t))
#     t += 1
#     d[u] = t
#     for i in range(len(A[u])):
#         if A[u][i] == 1 and d[i] == -1:
#             dfs(i)
#     t += 1
#     f[u] = t
            

def get_next(u):
    for i in range(len(A[u])):
        if A[u][i] == 1 and d[i] == -1:
            return i
    return None



def dfs(u):
    t = 1
    s = []
    s.append(u)
    d[u] = t
    while len(s) > 0:
        p = s[-1]
        v = get_next(p)
        # t += 1
        # d[p] = t
        # print('poped:', p)
        t += 1
        if v is None:
            # print('complete:', p)
            s.pop()
            f[p] = t
        else:
            # print('append:', v)

            d[v] = t
            s.append(v)

# def dfs(u):
#     s = []
#     t = 0
#     s.append(u)
    
#     while len(s) > 0:
#         p = s.pop()
#         print('init', str(p), d[p], t)
#         if d[p] > -1:
#             print('完了')
#             t += 1
#             f[p] = t
#         else:
#             t += 1
#             d[p] = t
#             print('---visit:', str(p), str(t), 'at', t)
#             has_node = False
#             for i in range(len(A[p])):
#                 if A[p][i] == 1 and d[i] == -1:
#                     print('reserve:', str(i))
#                     has_node = True
#                     s.append(i)
#                     break
#             if not has_node:
#                 t += 1
#                 f[p] = t
#         # print('H_complete:', str(p), str(t))
            


for i in range(n):
    if d[i] == -1:
        # print('start from:', str(i))
        dfs(i)


for i in range(n):
    print(str(i+1), str(d[i]), str(f[i]))

Submission status: Wrong Answer

Solution code:
n = int(input())
A = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    u, k, *v = list(map(int, input().split()))
    for j in v:
        A[int(u)-1][int(j)-1] = 1
        # A[int(j)-1][int(u)-1] = 1

for row in A:
    msg = ' '.join(map(str, row))
    # print(msg)

d = [-1] * n
f = [-1] * n

t = 0

# # recursive
# def dfs(u):
#     global t
#     # print('visit:', str(u), str(t))
#     t += 1
#     d[u] = t
#     for i in range(len(A[u])):
#         if A[u][i] == 1 and d[i] == -1:
#             dfs(i)
#     t += 1
#     f[u] = t
            

def get_next(u):
    for i in range(len(A[u])):
        if A[u][i] == 1 and d[i] == -1:
            return i
    return None

def dfs(u):
    global t
    s = []
    s.append(u)
    d[u] = t
    while len(s) > 0:
        p = s[-1]
        v = get_next(p)
        # print(p, 'next:', v)
        # t += 1
        # d[p] = t
        # print('poped:', p)
        
        if v is not None:
            
            if d[v] == -1:
                t += 1
                d[v] = t
                s.append(v)
                # print('[append:', v, 'at', t)
        else:
            t += 1
            # print('complete:', p, 'at', t)
            s.pop()
            f[p] = t


# def dfs(u):
#     s = []
#     t = 0
#     s.append(u)
    
#     while len(s) > 0:
#         p = s.pop()
#         print('init', str(p), d[p], t)
#         if d[p] > -1:
#             print('完了')
#             t += 1
#             f[p] = t
#         else:
#             t += 1
#             d[p] = t
#             print('---visit:', str(p), str(t), 'at', t)
#             has_node = False
#             for i in range(len(A[p])):
#                 if A[p][i] == 1 and d[i] == -1:
#                     print('reserve:', str(i))
#                     has_node = True
#                     s.append(i)
#                     break
#             if not has_node:
#                 t += 1
#                 f[p] = t
#         # print('H_complete:', str(p), str(t))
            


t = 0
for i in range(n):
    if d[i] == -1:
        t += 1
        # print('start from:', str(i))
        dfs(i)


for i in range(n):
    print(str(i), str(d[i]), str(f[i]))

Submission status: Wrong Answer

Solution code:
n = int(input())
G = [[] for _ in range(n)]
u1 = 0
for _ in range(n):
    u, k, *v = [int(i) for i in input().split()]
    G[u - 1] = v
    if k != 0 and u1 == 0:
        u1 = u

time = 1
u = u1
D = []
out = [[i+1, 0, 0] for i in range(n)]
T = []
while True:
    if u not in D:
        out[u - 1][1] = time
        D.append(u)
    if G[u - 1] == [] or out[G[u - 1][0] - 1][2] != 0:
        if out[u - 1][2] == 0:
            out[u - 1][2] = time + 1
        if T == []:
            break
        else:
            u = T.pop()
    else:
        T.append(u)
        u = G[u - 1].pop(0)

    time += 1
for ni in range(n):
    print(*out[ni])

Submission status: Wrong Answer

Solution code:
n = int(input())
G = [[] for _ in range(n)]
u1 = 0
for _ in range(n):
    u, k, *v = [int(i) for i in input().split()]
    G[u - 1] = v
    if k != 0 and u1 == 0:
        u1 = u

time = 1
u = u1
D = []
F = []
out = [[i+1, 0, 0] for i in range(n)]
T = []
while True:
    if u not in D:
        out[u - 1][1] = time
        D.append(u)
        T.append(u)
    if G[u - 1] == [] or G[u - 1][0] in F:
        time += 1
        out[T.pop() - 1][2] = time
        F.append(u)
        if T == []:
            if len(D) == n:
                break
            else:
                for ni in range(n):
                    if ni + 1 not in D:
                        u = ni + 1
                        break
        else:
            u = T[-1]
    else:
        u = G[u - 1].pop(0)
        time += 1

for ni in range(n):
    print(*out[ni])

Submission status: Wrong Answer

Solution code:
n = int(input())
G = [[] for _ in range(n)]
u1 = 0
for _ in range(n):
    u, k, *v = [int(i) for i in input().split()]
    G[u - 1] = v
    if k != 0 and u1 == 0:
        u1 = u

time = 1
u = u1
D = []
F = []
out = [[i+1, 0, 0] for i in range(n)]
T = []
while True:
    if u not in D:
        out[u - 1][1] = time
        D.append(u)
        T.append(u)

    for f in F:
        if f in G[u - 1]:
            idx = G[u - 1].index(f)
            del G[u - 1][idx]

    if G[u - 1] == []:
        time += 1
        out[T.pop() - 1][2] = time
        F.append(u)
        if T == []:
            if len(D) == n:
                break
            else:
                for ni in range(n):
                    if ni + 1 not in D:
                        u = ni + 1
                        break
        else:
            u = T[-1]
    else:
        u = G[u - 1].pop(0)
        time += 1

for ni in range(n):
    print(*out[ni])

Submission status: Wrong Answer

Solution code:
n = int(input())
G = [[] for _ in range(n)]
u1 = 0
for _ in range(n):
    u, k, *v = [int(i) for i in input().split()]
    G[u - 1] = v
    if k != 0 and u1 == 0:
        u1 = u

time = 1
u = u1
D = []
F = []
out = [[i+1, 0, 0] for i in range(n)]
T = []
while True:
    if u not in D:
        out[u - 1][1] = time
        D.append(u)
        T.append(u)

    for f in F:
        if f in G[u - 1]:
            idx = G[u - 1].index(f)
            del G[u - 1][idx]

    if G[u - 1] == []:
        time += 1
        out[T.pop() - 1][2] = time
        F.append(u)
        if T == []:
            if len(D) == n:
                break
            else:
                for ni in range(n):
                    if ni + 1 not in D:
                        u = ni + 1
                        break
                time += 1
                continue
        else:
            u = T[-1]
    else:
        if G[u - 1][0] != u:
            time += 1
        u = G[u - 1].pop(0)

for ni in range(n):
    print(*out[ni])

Submission status: Wrong Answer

Solution code:
n = int(input())
G = [[] for _ in range(n)]
u1 = 0
for _ in range(n):
    u, k, *v = [int(i) for i in input().split()]
    G[u - 1] = v
    if k != 0 and u1 == 0:
        u1 = u

time = 1
u = u1
D = []
F = []
out = [[i+1, 0, 0] for i in range(n)]
T = []
while True:
    if u not in D:
        out[u - 1][1] = time
        D.append(u)
        T.append(u)

    for f in F:
        if f in G[u - 1]:
            idx = G[u - 1].index(f)
            del G[u - 1][idx]

    if G[u - 1] == []:
        time += 1
        out[T.pop() - 1][2] = time
        F.append(u)
        if T == []:
            if len(D) == n:
                break
            else:
                for ni in range(n):
                    if ni + 1 not in D:
                        u = ni + 1
                        break
                time += 1
                continue
        else:
            u = T[-1]
    else:
        if G[u - 1][0] not in D:
            time += 1
        u = G[u - 1].pop(0)

for ni in range(n):
    print(*out[ni])

Submission status: Wrong Answer

Solution code:
def depth_search(i, adj, d, f, t):
    if d[i - 1]:
        return t
    d[i - 1] = t
    t += 1
    for v in adj[i - 1]:
        t = depth_search(v, adj, d, f, t)
    f[i - 1] = t
    t += 1
    return t
n = int(input())
adj = [list(map(int, input().split()))[2:] for _ in range(n)]

d = [0] * n
f = [0] * n

depth_search(1, adj, d, f, 1)

for i, df in enumerate(zip(d, f)):
    print(i, *df)

Submission status: Wrong Answer

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_11_B
# Depth First Search
# Result:
import sys

class Graph(object):
    def __init__(self, size):
        super(Graph, self).__init__()
        self.__size = size
        self.__vertices = [None] * size

    def add_vertex(self, vertex):
        self.__vertices[vertex.id_ - 1] = vertex

    def get_vertex(self, vid):
        return self.__vertices[vid - 1]

    def depth_first_search(self):
        d = [0] * self.__size
        f = [0] * self.__size
        timer = 1
        stack = [self.get_vertex(1)]
        d[0] = 1
        self.get_vertex(1).visited = True
        while len(stack) > 0:
            top = stack[-1]
            avid = top.get_next_adjacnt()
            if avid == -1:
                timer += 1
                f[top.id_ - 1] = timer
                stack.pop()
            else:
                av = self.get_vertex(avid)
                if not av.visited:
                    timer += 1
                    stack.append(av)
                    d[av.id_ - 1] = timer
                    av.visited = True

        for vtx in self.__vertices:
            print '%d %d %d' % (vtx.id_, d[vtx.id_ - 1], f[vtx.id_ - 1])

    def __str__(self):
        str_ = ''
        for e in self.__vertices:
            str_ += '%s\n' % e
        return str_

class Vertex(object):
    def __init__(self, id_):
        super(Vertex, self).__init__()
        self.id_ = id_
        self.adjacents = []
        self.next_idx = 0
        self.visited = False

    def add_adjacent(self, avid):
        self.adjacents.append(avid)

    def get_next_adjacnt(self):
        if len(self.adjacents) == 0: return -1
        if self.next_idx < len(self.adjacents):
            val = self.adjacents[self.next_idx]
            self.next_idx += 1
            return val
        else:
            return -1

    def __str__(self):
        str_ = '%d ' % self.id_
        if len(self.adjacents) == 0:
            str_ += '0'
        else:
            str_ += '%d' % len(self.adjacents)
            for e in self.adjacents:
                str_ += ' %d' % e
        return str_



s = int(sys.stdin.readline().strip())
graph = Graph(s)
for _ in range(0, s):
    vals = [int(x) for x in sys.stdin.readline().strip().split(' ')]
    v = Vertex(vals[0])
    graph.add_vertex(v)
    if vals[1] == 0: continue
    for i in range(0, vals[1]):
        v.add_adjacent(vals[2 + i])

graph.depth_first_search()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

WHITE = 0
GRAY = 1
BLACK = 2


def dbg_record(records):
    for index, record in enumerate(records):
        print("???????????????: %d" % index)
        if isinstance(record, dict):
            print("??\??????: %d" % record.get("visit", -1))
            print("?????????: %d" % record.get("leave", -1))
        else:
            print("?????????")
        print("")


def dfs(matrix):
    def internal_dfs(node_id, current_time):
        if state[node_id] == WHITE:
            # ?¨??????????
            state[node_id] = GRAY
            stack.append(node_id)
            records[node_id] = {"visit": current_time}  # ?¨??????????????¨????

            # ?¬?????¨????????????¨?????§????????????????????¢???
            next_id = None
            for index in range(len(matrix)):
                if matrix[node_id][index] == 1 and state[index] == WHITE:
                    next_id = index
                    break

            if next_id is not None:
                internal_dfs(next_id, current_time + 1)
            elif 0 < len(stack):
                # ?¬?????¨????????????¨?????§?????????????????????????????????????????°?????????
                internal_dfs(stack.pop(), current_time + 1)
        elif state[node_id] == GRAY:
            # ????????????
            state[node_id] = BLACK
            records[node_id]["leave"] = current_time  # ????????????????¨????

            # ?¬?????¨????????????¨?????§????????????????????¢???
            next_id = None
            for index in range(len(matrix)):
                if matrix[node_id][index] == 1 and state[index] == WHITE:
                    next_id = index
                    break

            if next_id is not None:
                internal_dfs(next_id, current_time + 1)
            elif 0 < len(stack):
                # ?¬?????¨????????????¨?????§?????????????????????????????????????????°?????????
                internal_dfs(stack.pop(), current_time + 1)

    state = [WHITE] * len(matrix)  # White, Gray, Black
    records = [None] * len(matrix)  # Save time when the node is processed
    stack = []

    internal_dfs(0, 1)
    # dbg_record(records)
    return records


if __name__ == "__main__":
    # ??????????????????
    lines = [
        "6",
        "1 2 2 3",
        "2 2 3 4",
        "3 1 5",
        "4 1 6",
        "5 1 6",
        "6 0",
    ]
    # lines = sys.stdin.readlines()

    # Create n * n matrix
    dimension = int(lines[0])
    matrix = []
    for x in range(dimension):
        matrix.append([0] * dimension)

    # Set edge info
    for index, line in enumerate(lines[1:]):
        for edge in [int(x) for x in line.strip().split(" ")[2:]]:
            matrix[index][edge - 1] = 1

    result = dfs(matrix)
    for index, line in enumerate(result):
        print("%d %d %d" % (index + 1, line["visit"], line["leave"]))