백준 1068 트리 ❌

CJB_ny·2023년 1월 27일
0

백준

목록 보기
63/104
post-thumbnail

트리

내코드

트리 문제는 root부터 탐색을 하자.

그리고 dfs, bfs 이런거는 "그래프"를 탐색하는 알고리즘이다.

근데 왜 트리도 그래프의 한 종류인데 왜 트리를 dfs로 탐색할 생각을 못했던 부분.

그리고 dfs의 반환형이 void말고 int형인 부분도 구현을 할 줄 알아야한다.

here로 부터 시작을 해서 leaf노드의 수를 구하는 dfs를 만들면된다.


int DFS(int here)
{
    int ret = 0;
    int child = 0;
    for (int there : adj[here])
    {
        if (there == r) continue;
        ret += DFS(there);
        ++child;
    }
    if (child == 0) return 1;
    return ret;
}

int를 반환하는 DFS를 보면은, adj[here]의 there수만큼 ++child를 하거나 없다면은

child == 0일 경우 1을 반환을 하는데 이게 무슨말이냐하면은

자식이 없는 경우 1을 반환을 하는데 ret += DFS(there) 이기 때문에 ret는 2가 된다.

DFS안에 continue로 삭제? 한 부분은 건너뛴다.

cpp코드

#include <iostream>
#include <vector>
using namespace std;
#define endl "\n"

int n, r, temp, root;
vector<int> adj[54];

int DFS(int here)
{
    int ret = 0;
    int child = 0;
    for (int there : adj[here])
    {
        if (there == r) continue;
        ret += DFS(there);
        ++child;
    }
    if (child == 0) return 1;
    return ret;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin >> n;
    for (int i = 0; i < n; ++i)
    {
        cin >> temp;
        if (temp == -1) root = i;
        else adj[temp].push_back(i);
    }
    cin >> r;
    if (r == root)
    {
        cout << 0 << endl; 
        return 0;
    }
    cout << DFS(root) << endl;
    return 0;
}
profile
https://cjbworld.tistory.com/ <- 이사중

0개의 댓글