티스토리 뷰

알고리즘/BOJ

[백준] 4803 트리

세진짱 2018. 5. 12. 20:25


Cycle찾는 함수 만들어서 풀다가 계속 틀렸다 ㅎㅎ

얼마전 코포 Div3 E번과 거의 똑같은 문제다 

푸는 방법은


1. 각 정점의 deg배열을만들고 그래프를 입력받을 때 계산해준다

2. check안된 곳에서 dfs를 돌린다

3. (정점 == (간선/2)+1) 이라면 우리가 원하는 트리다



소스코드

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
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
vector<vector<int>> Graph;
vector<int> vt;
int deg[505];
bool check[505];
int n, m, v, e;
 
void dfs(int x) {
    v += 1;
    check[x] = true;
    vt.push_back(x);
    for (int i = 0; i < Graph[x].size(); i++) {
        int next = Graph[x][i];
        if (!check[next])     dfs(next);
    }
}
int main() {
    int c = 1;
    while (scanf(" %d %d"&n, &m) != -1) {
        if (n == 0 && m == 0return 0;
        memset(check, 0sizeof(check));
        memset(deg, 0sizeof(deg));
        Graph.resize(n);
        for (int i = 0; i < m; i++) {
            int a, b; scanf(" %d %d"&a, &b);
            a--; b--;
            Graph[a].push_back(b);
            Graph[b].push_back(a);
            deg[a]++; deg[b]++;
        }
 
        int ans = 0;
        for (int i = 0; i < n; i++) {
            if (check[i]) continue;
            v = 0, e = 0;
            vt.clear();
            dfs(i);
            for (int i = 0; i < vt.size(); i++) e += deg[vt[i]];
            e /= 2;
            if (v == (e + 1)) ans += 1;
        }
        
        printf("Case %d: ", c++);
        if (ans == 0) puts("No trees.");
        else if (ans == 1) puts("There is one tree.");
        else printf("A forest of %d trees.\n",ans);
        Graph.clear();
    }
}
 
cs

'알고리즘 > BOJ' 카테고리의 다른 글

[백준] 13333 Q-인덱스  (0) 2018.05.14
[백준] 1535 안녕  (0) 2018.05.13
[백준] 1874 스택수열  (0) 2018.05.13
[백준] 1269 대칭차집합  (0) 2018.05.13
[백준] 1967 트리의 지름  (0) 2018.05.12
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
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
글 보관함