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: Accepted

Solution code:
n = int(input())
graph = [[] for _ in range(n)]

global time
global visited 
global f_time 
global e_time 

time = 1
visited = [0 for _ in range(n)]
f_time = [0 for _ in range(n)]
e_time = [0 for _ in range(n)]

def input_graph(n):
  for _ in range(n):
    node_id, num, *v = list(map(int, input().split()))
    for i in range(num):
      graph[node_id-1].append(v[i]-1)

def dfs(node_id):
  global time
  f_time[node_id] = time
  time += 1

  for ad_node in graph[node_id]:
    if visited[ad_node] == 1:
      continue
    visited[ad_node] = 1
    dfs(ad_node)

  e_time[node_id] = time
  time += 1



if __name__ == "__main__":
  input_graph(n)
  for i in range(n):
    if visited[i] == 1:
      continue
    visited[i] = 1
    dfs(i)

  for i, (f, e) in enumerate(zip(f_time, e_time)):
    print(i+1, f, e)

Submission status: Accepted

Solution code:
def d(r):
    global n
    if t[r]:return
    n+=1
    t[r]=[r+1,n]
    for i in c[r]:d(i-1)
    n+=1
    t[r][2:]=[n]
m=input()
c=[0]*m
for _ in range(m):
    l=map(int,raw_input().split())
    c[l[0]-1]=l[2:]
n=0
t=[0]*m
for i in range(m):
    d(i)
    print " ".join(map(str,t[i]))

Submission status: Accepted

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

t = 1
for i in range(n):
    if d[i] == 0:
        t = depth_search(i + 1, adj, d, f, t)

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

Submission status: Accepted

Solution code:
from sys import stdin

X = [ 0 for i in range(100) ]
d = [ 0 for i in range(100) ]
f = [ 0 for i in range(100) ]
G = [[ 0 for i in range(100) ] for i in range(100)]

t = 0

def DFS(i) :
	global t
	t += 1
	d[i] = t
	for j in range(n) :
		if G[i][j] != 0 and d[j] == 0 : DFS(j)
	t += 1
	f[i] = t


n = int(input())
for i in range(n) :
	X[i] = stdin.readline().strip().split()


for i in range(n) :
	for j in range(int(X[i][1])) :
		G[int(X[i][0])-1][int(X[i][j+2])-1] = 1

for i in range(n) :
	if d[i] == 0 : DFS(i)

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

Submission status: Accepted

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
        for j in range(1, self.__size + 1):
            vtx = self.get_vertex(j)
            if not vtx.visited:
                stack = [vtx]
                d[vtx.id_ - 1] = timer
                vtx.visited = True
                timer = self.__depth_first_search(stack, timer, d, f) + 1

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

    def __depth_first_search(self, stack, timer, d, f):
        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
        return timer

    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: Accepted

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:
                return internal_dfs(next_id, current_time + 1)
            elif 0 < len(stack):
                # ?¬?????¨????????????¨?????§?????????????????????????????????????????°?????????
                return internal_dfs(stack.pop(), current_time + 1)
        elif state[node_id] == GRAY:
            # ????????????

            # ?¬?????¨????????????¨?????§????????????????????¢???
            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:
                stack.append(node_id)
                return internal_dfs(next_id, current_time)
            elif 0 < len(stack):
                # ?¬?????¨????????????¨?????§?????????????????????????????????????????°?????????
                state[node_id] = BLACK
                records[node_id]["leave"] = current_time  # ????????????????¨????
                return internal_dfs(stack.pop(), current_time + 1)
            else:  # ??????????§????????????£???????????¨??? (node_id should be 0)
                state[node_id] = BLACK
                records[node_id]["leave"] = current_time
                return current_time
        elif state[node_id] == BLACK:
            print("Black!!")

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

    while True:
        node_id = None
        for index, record in enumerate(records):
            if record is None:
                node_id = index
                break

        if node_id is None:
            break
        else:
            current_time = internal_dfs(node_id, current_time + 1)

    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

    records = dfs(matrix)
    for index, line in enumerate(records):
        if line is not None:
            print("%d %d %d" % (index + 1, line.get("visit", -1), line.get("leave", -1)))
        else:
            print("%d None None" % (index + 1))

Submission status: Accepted

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

# ??????: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_11_B

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:
                return internal_dfs(next_id, current_time + 1)
            elif 0 < len(stack):
                # ?¬?????¨????????????¨?????§?????????????????????????????????????????°?????????
                return internal_dfs(stack.pop(), current_time + 1)
        elif state[node_id] == GRAY:
            # ????????????

            # ?¬?????¨????????????¨?????§????????????????????¢???
            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:
                stack.append(node_id)
                return internal_dfs(next_id, current_time)
            elif 0 < len(stack):
                # ?¬?????¨????????????¨?????§?????????????????????????????????????????°?????????
                state[node_id] = BLACK
                records[node_id]["leave"] = current_time  # ????????????????¨????
                return internal_dfs(stack.pop(), current_time + 1)
            else:  # ??????????§????????????£???????????¨??? (node_id should be 0)
                state[node_id] = BLACK
                records[node_id]["leave"] = current_time
                return current_time
        elif state[node_id] == BLACK:
            print("Black!!")

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

    while True:
        node_id = None
        for index, record in enumerate(records):
            if record is None:
                node_id = index
                break

        if node_id is None:
            break
        else:
            current_time = internal_dfs(node_id, current_time + 1)

    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 = [[0 for col in range(dimension)] for row in range(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

    records = dfs(matrix)
    for index, line in enumerate(records):
        if line is not None:
            print("%d %d %d" % (index + 1, line.get("visit", -1), line.get("leave", -1)))
        else:
            print("%d None None" % (index + 1))

Submission status: Accepted

Solution code:
n = int(raw_input())

def dfs(u,t):
    global graph
    global found
    global timestamp

    if u in found: return t
    found.add(u)
    timestamp[u] = [-1,-1]
    timestamp[u][0] = t
    t += 1
    for v in graph[u]:
        t = dfs(v,t)
    timestamp[u][1] = t
    t += 1
    return t

graph = [[] for i in range(n)]
found = set()
timestamp = {}

for i in range(n):
    entry = map(int,raw_input().strip().split(' '))
    u = entry[0]
    u -= 1
    for v in entry[2:]:
        v -= 1
        graph[u].append(v)


t = 1
for i in range(n):
    t = dfs(i,t)

for i in timestamp:
    print i+1,timestamp[i][0],timestamp[i][1]

Submission status: Accepted

Solution code:
#!/usr/bin/python3

def find(A, id, V, time):
    i = id - 1
    A[i][0] = True
    A[i][1] = time
    time += 1
    for v in V[i]:
        if A[v - 1][0] == False:
            time = find(A, v, V, time)
    A[i][2] = time
    time += 1
    return time

n = int(input())
# [isFind, d, f]
A = [[False, 0, 0] for i in range(n)]
U = []
V = []
for i in range(n):
    l = list(map(int, input().split()))
    U.append(l[0])
    V.append(l[2:])

time = 1
for u in U:
    if A[u - 1][0] == False:
        time = find(A, u, V, time)

for u in U:
    l = [u]
    l.extend(A[u - 1][1:])
    print(' '.join(map(str, l)))

Submission status: Accepted

Solution code:

def DFS(n = 1, A = [0], i = 0, d = [0], f = [0], time = 1):
    for j in range(n):
        if A[i][j] == 1 and d[j] == 0:
            time = time + 1
            d[j] = time
            time = DFS(n, A, j, d, f, time)
    time = time + 1
    f[i] = time
    return time

n = int(raw_input())
A = [0] * n
for i in range(n):
    A[i] = [0] * n

for i in range(n):
    value = map(int, raw_input().split())
    u = value[0] - 1
    k = value[1]
    nodes = value[2:]
    for j in range(k):
        v = nodes[j] - 1
        A[u][v] = 1

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

time = 0
for i in range(n):
    if d[i] == 0:
        time = time + 1
        d[i] = time
        time = DFS(n, A, i, d, f, time)

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

Submission status: Accepted

Solution code:

def DFS(A = [0], i = 0, d = [0], f = [0], time = 1):
    for j in range(len(d)):
        if A[i][j] == 1 and d[j] == 0:
            time = time + 1
            d[j] = time
            time = DFS(A, j, d, f, time)
    time = time + 1
    f[i] = time
    return time

n = int(raw_input())
A = [0] * n
for i in range(n):
    A[i] = [0] * n

for i in range(n):
    value = map(int, raw_input().split())
    u = value[0] - 1
    k = value[1]
    nodes = value[2:]
    for j in range(k):
        v = nodes[j] - 1
        A[u][v] = 1

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

time = 0
for i in range(n):
    if d[i] == 0:
        time = time + 1
        d[i] = time
        time = DFS(A, i, d, f, time)

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

Submission status: Accepted

Solution code:

def DFS(n = 1, i = 0, time = 1):
    for j in range(n):
        if A[i][j] == 1 and d[j] == 0:
            time = time + 1
            d[j] = time
            time = DFS(n, j, time)
    time = time + 1
    f[i] = time
    return time

n = int(raw_input())
A = [0] * n
for i in range(n):
    A[i] = [0] * n

for i in range(n):
    value = map(int, raw_input().split())
    u = value[0] - 1
    k = value[1]
    nodes = value[2:]
    for j in range(k):
        v = nodes[j] - 1
        A[u][v] = 1

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

time = 0
for i in range(n):
    if d[i] == 0:
        time = time + 1
        d[i] = time
        time = DFS(n, i, time)

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

Submission status: Accepted

Solution code:
def DFS(s, t):
    t += 1
    flag[s] = 1
    d[s] = t
    for i in range(1, n+1):
        if G[s][i] == 1:
            if flag[i] == 0:
                DFS(i, t)
                t = f[i]
    f[s] = t + 1

n = int(raw_input())
G = [[0 for i in range(n+1)] for j in range(n+1)]
d = [0 for i in range(n+1)]
f = [0 for i in range(n+1)]

for i in range(n):
    v = map(int, raw_input().split())
    for j in range(v[1]):
        G[v[0]][v[2+j]] = 1

flag = [0 for i in range(n+1)]
for i in range(1, n+1):
    if flag[i] == 0:
        DFS(i, max(f))

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

Submission status: Accepted

Solution code:
class node:
    def __init__(self):
        self.number = 0
        self.in_time    = 0
        self.out_time   = 0
        self.link_node  = []
        self.is_serched = False

def dfs_visit(node, timer):
    node.in_time    = timer
    node.is_serched = True
    temp            = timer + 1

    for item in node.link_node:
        if item.is_serched == False:
            temp = dfs_visit(item, temp)
    node.out_time = temp
    return node.out_time + 1

n = input()
node_list = [None] * (n + 1)

for i in xrange(1, n + 1):
    node_list[i] = node()
    node_list[i].number = int(i)

for i in xrange(1, n + 1):
    line = raw_input().split()
    for node_num in line[2 : ]:
        node_list[i].link_node.append(node_list[int(node_num)])

temp = 1
for item in node_list[1 : ]:
    if item.is_serched == False:
        temp = dfs_visit(item, temp)

for item in node_list[1 : ]:
    print '%s %s %s' % (str(item.number), str(item.in_time), str(item.out_time))

Submission status: Accepted

Solution code:
n = int(raw_input())

d = [0 for i in range(n)]
f = [0 for i in range(n)]
G = [0 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]
st = [0 for i in range(n)]
t = [0]

def DFS_visit(s):
    st[s] = 1
    t[0] += 1
    d[s] = t[0]
    for e in range(n):
        if M[s][e] == 1 and st[e] == 0:
            DFS_visit(e)
    st[s] == 2
    t[0] += 1
    f[s] = t[0]

def DFS():
    for s in range(n):
        if st[s] == 0:
            DFS_visit(s)
    for s in range(n):
        print'{0} {1} {2}'.format(s+1, d[s], f[s])
    
for i in range(n):
    G = map(int, raw_input().split())
    for j in range(G[1]):
        M[G[0]-1][G[2+j]-1] = 1

DFS()

Submission status: Accepted

Solution code:
import sys

global stamp, counter
stamp = {}
counter = 0

def dfs(key, GRAPH):
    global stamp, counter
    if stamp[key][0] == 0:
        counter += 1
        stamp[key][0] = counter
    elif stamp[key][1] != 0:
        return

    for e in GRAPH[key]:
        try:
            if stamp[e][0] == 0:
                dfs(e, GRAPH)
        except:
            pass
    counter += 1
    stamp[key][1] = counter
    return

n = int(raw_input())
x = {}
for i in range(n):
    seq = map(int, raw_input().split())
    key = seq[0]
    if key != 0:
        x[key] = seq[2:]
    else:
        x[key] = []  
    stamp[key] = [0, 0]

for e in x.keys():
    dfs(e, x)

for e in x.keys():
    print e, stamp[e][0], stamp[e][1]

Submission status: Accepted

Solution code:
n = int(input())
g = [None] * n
visited = [0] * n
root = set(range(n))
ts = [[0, 0] for _ in range(n)]
t = 0

while n:
    l = list(map(int, input().split()))
    connected = [i - 1 for i in l[2:]]
    g[l[0] - 1] = [i - 1 for i in l[2:]]
    root -= set(connected)
    n -= 1


def dfs(i):
    global g, t, ts, visited
    lts = ts[i]
    t += 1
    lts[0] = t
    visited[i] = 1
    for c in g[i]:
        if not visited[c]:
            dfs(c)
    t += 1
    lts[1] = t

if root:
    for r in sorted(root):
        dfs(r)
else:
    dfs(0)

for i, v in enumerate(ts):
    print(i + 1, *v)

Submission status: Accepted

Solution code:
import sys

def DFS(index, tm, l, a, b):
 tm += 1
 a[index] = tm
 for i in l[index]:
  if not a[i-1]:
   tm = DFS(i-1, tm, l, a, b)
 tm += 1
 b[index] = tm
 return tm


n = input()
l=[]
for i in xrange(n):
 l.append([int(s) for s in sys.stdin.readline().split()[2:]])
a = [0] * n
b = [0] * n
tm = 0
for i in xrange(n):
 if not a[i]:
    tm = DFS(i, tm, l, a, b)

for i in xrange(n):
   print i+1, a[i], b[i]

Submission status: Accepted

Solution code:
n = int(raw_input())
 
d = [0 for i in range(n)]
f = [0 for i in range(n)]
G = [0 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]
st = [0 for i in range(n)]
t = [0]
 
def DFS_visit(s):
    st[s] = 1
    t[0] += 1
    d[s] = t[0]
    for e in range(n):
        if M[s][e] == 1 and st[e] == 0:
            DFS_visit(e)
    st[s] == 2
    t[0] += 1
    f[s] = t[0]
 
def DFS():
    for s in range(n):
        if st[s] == 0:
            DFS_visit(s)
    for s in range(n):
        print'{0} {1} {2}'.format(s+1, d[s], f[s])
     
for i in range(n):
    G = map(int, raw_input().split())
    for j in range(G[1]):
        M[G[0]-1][G[2+j]-1] = 1
 
DFS()

Submission status: Accepted

Solution code:
n = int(raw_input())
 
d = [0 for i in range(n)]
f = [0 for i in range(n)]
G = [0 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]
col = [0 for i in range(n)]
t = [0]
 
def DFS_visit(u):
    col[u] = 1
    t[0] += 1
    d[u] = t[0]
    for v in range(n):
        if M[u][v] == 1 and col[v] == 0:
            DFS_visit(v)
    col[u] = 2
    t[0] += 1
    f[u] = t[0]
 
def DFS():
    for u in range(n):
        if col[u] == 0:
            DFS_visit(u)
    for u in range(n):
        print'{0} {1} {2}'.format(u+1, d[u], f[u])
     
for i in range(n):
    X = map(int, raw_input().split())
    for j in range(X[1]):
        M[X[0]-1][X[2+j]-1] = 1
 
DFS()

Submission status: Accepted

Solution code:
import sys
  
def dfs(i, t, l, a, b):
   t += 1
   a[i] = t
   for j in l[i]:
      if not a[j-1]:
         t = dfs(j-1, t, l, a, b)
   t += 1
   b[i] = t
   return t
  
  
n = input()
l=[]
for i in range(n):
   l.append([int(s) for s in sys.stdin.readline().split()[2:]])
a = [0] * n
b = [0] * n
t = 0
for i in xrange(n):
   if not a[i]:
      t = dfs(i, t, l, a, b)
  
for i in xrange(n):
   print i+1, a[i], b[i]

Submission status: Accepted

Solution code:
n = int(raw_input())
  
d = [0 for i in range(n)]
f = [0 for i in range(n)]
G = [0 for i in range(n)]
v = [[0 for i in range(n)] for j in range(n)]
st = [0 for i in range(n)]
tm = [0]
  
def DFS_visit(s):
  st[s] = 1
  tm[0] += 1
  d[s] = tm[0]
  for e in range(n):
    if v[s][e] == 1 and st[e] == 0:
      DFS_visit(e)
  st[s] == 2
  tm[0] += 1
  f[s] = tm[0]
  
def DFS():
  for s in range(n):
    if st[s] == 0:
      DFS_visit(s)
  for s in range(n):
     print'{0} {1} {2}'.format(s+1, d[s], f[s])
      
for i in range(n):
  G = map(int, raw_input().split())
  for j in range(G[1]):
    v[G[0]-1][G[2+j]-1] = 1
  
DFS()

Submission status: Accepted

Solution code:
n = int(raw_input())

d = [0 for i in range(n)]
f = [0 for i in range(n)]
a = [[0 for i in range(n)] for j in range(n)]
st = [0 for i in range(n)]
time = [0]
G = [0 for i in range(n)]


def dfs_visit(s):
    st[s] = 1
    time[0] += 1
    d[s] = time[0]
    
    for k in range(n):  
      if a[s][k] == 1 and st[k] == 0:
          dfs_visit(k)
    st[s] ==2
    time[0] += 1
    f[s] = time[0]

def main():
    for s in range(n):
        if st[s] == 0:
            dfs_visit(s)
    for s in range(n):
        print'{0} {1} {2}'.format(s+1, d[s], f[s])

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

main()

Submission status: Accepted

Solution code:
n = int(raw_input())
 
d = [0 for i in range(n)]
f = [0 for i in range(n)]
a = [[0 for i in range(n)] for j in range(n)]
st = [0 for i in range(n)]
time = [0]
g = [0 for i in range(n)]
 
 
def dfs_visit(s):
    st[s] = 1
    time[0] += 1
    d[s] = time[0]
     
    for k in range(n):  
      if a[s][k] == 1 and st[k] == 0:
          dfs_visit(k)
    st[s] ==2
    time[0] += 1
    f[s] = time[0]
 
def main():
    for s in range(n):
        if st[s] == 0:
            dfs_visit(s)
    for s in range(n):
        print'{0} {1} {2}'.format(s+1, d[s], f[s])
 
for i in range(n):
    g = map(int, raw_input().split())
    for j in range(g[1]):
        a[g[0]-1][g[2+j]-1] = 1
 
main()

Submission status: Accepted

Solution code:
n = int(raw_input())
  
d = [0 for i in range(n)]
f = [0 for i in range(n)]
G = [0 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]
st = [0 for i in range(n)]
t = [0]
  
def DFS_visit(s):
    st[s] = 1
    t[0] += 1
    d[s] = t[0]
    for e in range(n):
        if M[s][e] == 1 and st[e] == 0:
            DFS_visit(e)
    st[s] == 2
    t[0] += 1
    f[s] = t[0]
  
def DFS():
    for s in range(n):
        if st[s] == 0:
            DFS_visit(s)
    for s in range(n):
        print'{0} {1} {2}'.format(s+1, d[s], f[s])
      
for i in range(n):
    G = map(int, raw_input().split())
    for j in range(G[1]):
        M[G[0]-1][G[2+j]-1] = 1
  
DFS()

Submission status: Accepted

Solution code:
n = int(raw_input())
t = [0]
d = [0 for i in range(n)]
f = [0 for i in range(n)]
G = [0 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]
st = [0 for i in range(n)]
 
def DFS_visit(s):
	st[s] = 1
	d[s] = t[0] = t[0] + 1
	for e in range(n):
		if M[s][e] == 1 and st[e] == 0:
			DFS_visit(e)
	f[s] = t[0] = t[0] + 1
 
def DFS():
	for s in range(n):
		if st[s] == 0:
			DFS_visit(s)
	for s in range(n):
		print s+1, d[s], f[s]

for i in range(n):
	G = map(int, raw_input().split())
	for j in range(G[1]):
		M[G[0]-1][G[j+2]-1] = 1
DFS()

Submission status: Accepted

Solution code:


import sys
   
def dfs(i, t, l, a, b):
   t += 1
   a[i] = t
   for j in l[i]:
      if not a[j-1]:
         t = dfs(j-1, t, l, a, b)
   t += 1
   b[i] = t
   return t
   
   
n = input()
l=[]
for i in range(n):
   l.append([int(s) for s in sys.stdin.readline().split()[2:]])
a = [0] * n
b = [0] * n
t = 0
for i in xrange(n):
   if not a[i]:
      t = dfs(i, t, l, a, b)
   
for i in xrange(n):
   print i+1, a[i], b[i]

Submission status: Accepted

Solution code:
def depth(s, time):
    time += 1
    flag[s] = 1
    d[s] = time
    for i in range(1, n+1):
        if G[s][i] == 1:
            if flag[i] == 0:
                depth(i, time)
                time = f[i]
    f[s] = time + 1
 
n = int(raw_input())
G = [[0 for i in range(n+1)] for j in range(n+1)]
d = [0 for i in range(n+1)]
f = [0 for i in range(n+1)]
 
for i in range(n):
    v = map(int, raw_input().split())
    for j in range(v[1]):
        G[v[0]][v[2+j]] = 1
 
flag = [0 for i in range(n+1)]
for i in range(1, n+1):
    if flag[i] == 0:
        depth(i, max(f))
 
for i in range(1, n+1):
    print(str(i) + " " + str(d[i]) + " " + str(f[i]))

Submission status: Accepted

Solution code:
from __future__ import division,print_function
import time
import sys
import io
import re
import math
start = time.clock()
i = 0
def walk(index,tm,L,d,f):
    tm+=1
    d[index]=tm
    for i in L[index]:
        if not d[i-1]:
            tm=walk(i-1,tm,L,d,f)
    tm+=1
    f[index]=tm
    return tm
 
def main():
    num=int(sys.stdin.readline())
    L=[]
    for _ in range(num):
        L.append([int(s) for s in sys.stdin.readline().split()[2:]])
    d=[0]*num
    f=[0]*num
    tm=0
    for i in range(num):
        if not d[i]:
            tm=walk(i,tm,L,d,f)
    for i in range(num):
        print(i+1,d[i],f[i])
 
main()

Submission status: Accepted

Solution code:
n = input()

time = []
time.append(0)

d = [0 for i in xrange(n + 1)]
f = [0 for i in xrange(n + 1)]
color = ['WHITE' for i in xrange(n + 1)]

graph_map = [[0 for j in xrange(n + 1)] for i in xrange(n + 1)]

for i in xrange(1, n + 1):
    tmp = map(int, raw_input().split())
    for j in xrange(tmp[1]):
        graph_map[i][tmp[j + 2]] = 1

def dfs(u):
    color[u] = 'GRAY'
    time[0] += 1
    d[u] = time[0]
    for v in xrange(1, n + 1):
        if graph_map[u][v] == 1 and color[v] == 'WHITE':
            dfs(v)
    color[u] = 'BLACK'
    time[0] += 1
    f[u] = time[0]

for i in xrange(1, n + 1):
    if color[i] == 'WHITE':
        dfs(i)

for i in xrange(1, n + 1):
    print "%d %d %d" % (i, d[i], f[i])

Submission status: Accepted

Solution code:
n=0
m=input()
c=[0 for i in xrange(m)]
t=[0 for i in xrange(m)]


def d(u):
    global n
    if t[u]:return
    n = n + 1
    t[u]=[u+1,n]
    for i in c[u]:d(i-1)
    n = n + 1
    t[u][2:]=[n]

def dfs():
    for i in range(m):
     l=map(int,raw_input().split())
     c[l[0]-1]=l[2:]
    for i in range(m):
     d(i)
     print " ".join(map(str,t[i]))

dfs()

Submission status: Accepted

Solution code:
n=0
m=input()
c=[0 for i in xrange(m)]
ts=[0 for i in xrange(m)]


def d(u):
    global n
    if ts[u]:return
    n = n + 1
    ts[u]=[u+1,n]
    for i in c[u]:d(i-1)
    n = n + 1
    ts[u][2:]=[n]

def dfs():
    for i in range(m):
     l=map(int,raw_input().split())
     c[l[0]-1]=l[2:]
    for i in range(m):
     d(i)
     print " ".join(map(str,ts[i]))

dfs()