aoj

ALDS1_11_C Breadth First Search

ALDS1_11_C Breadth 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
#define INTMAX (1 << 21)


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

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

    queue<Int> Q;
    Int depth = 0;

    Q.push(0);
    visited[0] = true;
    ds[0] = 0;

    while (!Q.empty()) {
        Int parent = Q.front(); Q.pop();
        for (auto child: vs[parent]) {
            if (visited[child]) continue;
            Q.push(child);
            visited[child] = true;
            ds[child] = ds[parent] + 1;
        }
    }

    loop(i,0,n) cout << i+1 << " " << ds[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);
        }

    }
    bfs(vs, n);
}