aoj

ALDS1_11_B Depth First Search

ALDS1_11_B Depth First Search
Feb. 2, 2020, 1:52 p.m.

目次

解答

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#define INTMAX (1 << 21)


void dfs(vector<Int> vs[], Int n) {
    Int t = 0;
    bool visited[n];
    Int ds[n];
    Int fs[n];

    loop(i,0,n) {
        visited[i] = false;
        ds[i] = fs[i] = 0;
    }

    stack<Int> S;
    loop(i,0,n) {
        if (visited[i]) continue;

        S.push(i);
        visited[i] = true;
        ds[i] = ++t;

loop:
        while (!S.empty()) {
            Int i = S.top();
            for (auto c: vs[i]) {
                if (visited[c]) continue;
                S.push(c);
                visited[c] = true;
                ds[c] = ++t;
                goto loop;
            }

            S.pop();
            fs[i] = ++t;
        }
    }

    loop(i,0,n) cout << i+1 << " " << ds[i] << " " << fs[i] << endl;
}


int main(void){
    Int n, x, cc, c;
    cin >> n;
    vector<Int> vs[n];
    loop(i,0,n) {
        cin >> x >> cc;
        loop(j,0,cc) {
            cin >> c;
            vs[x-1].push_back(c-1);
        }

    }
    dfs(vs, n);
}