알고리즘/BOJ

[백준] 11581 구호물자

세진짱 2018. 5. 15. 01:10


Cycle이 있는지 없는지 판단하는 문제다!

간단하게 Cycle찾는 함수를 구현하면 풀수있다...!


소스코드

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
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
int n, m;
int cycle[111];
vector<vector<int>> Graph;
 
bool isCycle(int x) {
    if (cycle[x]) {
        if (cycle[x] == -1return true;
        return false;
    }
    cycle[x] = -1;
    for (int i = 0; i < Graph[x].size(); i++) {
        int next = Graph[x][i];
        if (isCycle(next)) return true;
    }
    cycle[x] = 1;
    return false;
}
 
int main() {
    scanf(" %d"&n);
    Graph.resize(n);
    for (int i = 0; i < n - 1; i++) {
        scanf(" %d"&m);
        for (int j = 0; j < m; j++) {
            int x; scanf(" %d"&x);
            x--;
            Graph[i].push_back(x);
        }
    }
 
    if (isCycle(0)) puts("CYCLE");
    else puts("NO CYCLE");
    
}
cs