티스토리 뷰

문제 링크입니다 : https://www.acmicpc.net/problem/15681

 

15681번: 트리와 쿼리

트리의 정점의 수 N과 루트의 번호 R, 쿼리의 수 Q가 주어진다. (2 ≤ N ≤ 105, 1 ≤ R ≤ N, 1 ≤ Q ≤ 105) 이어 N-1줄에 걸쳐, U V의 형태로 트리에 속한 간선의 정보가 주어진다. (1 ≤ U, V ≤ N, U ≠ V) ��

www.acmicpc.net

트리 + 동적계획법 문제이다.

 

트리 자체가 재귀적 속성이 있으므로 dfs를 사용하면 트리를 만들 수 있다.

 

 

 

 

트리 구현 코드

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

struct Node {
    int data;
    // int numChildren = 0;
    vector<Node*> children;
};

vector<int> numChildren;

vector<vector<int>> adj;
vector<bool> visited;

Node* root;

int N, R, Q;

Node* dfs(int cur) {
    Node* ret = new Node();
    ret->data = cur;
    visited[cur] = true;

    for(int i = 0; i < adj[cur].size(); i++) {
        int next = adj[cur][i];
        if(visited[next]) continue;
        ret->children.push_back(dfs(adj[cur][i]));
    }

    for(int i = 0; i < ret->children.size(); i++) {
        numChildren[cur] += numChildren[ret->children[i]->data] + 1;
    }

    return ret;
}

int main() {
    ios_base :: sync_with_stdio(false); 
    cin.tie(NULL); cout.tie(NULL);
    
    cin >> N >> R >> Q;
    adj.assign(N + 1, vector<int>());
    numChildren.assign(N + 1, 0);
    visited.assign(N + 1, false);

    int u, v;
    for(int i = 0; i < N - 1; i++) {
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    int target;
    root = dfs(R);

    for(int i = 0; i < Q; i++) {
        cin >> target;
        cout << numChildren[target] + 1 << '\n';
    }


    return 0;
}

 

 

단순 dfs 활용

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

vector<vector<int>> adj;
vector<int> cache;
vector<bool> visited;

int N, R, Q;

int dfs(int node) {
    visited[node] = true;

    int& ret = cache[node];
    
    for(int i = 0; i < adj[node].size(); i++) {
        int next = adj[node][i];
        if(visited[next]) continue;
        ret += dfs(next);
    }

    return ++ret;
}

int main() {
    ios_base :: sync_with_stdio(false); 
    cin.tie(NULL); cout.tie(NULL);
    
    cin >> N >> R >> Q;

    adj.assign(N + 1, vector<int>());
    cache.assign(N + 1, 0);
    visited.assign(N + 1, false);

    
    int u, v;
    for(int i = 0; i < N - 1; i++) {
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    dfs(R);

    
    int target;
    for(int i = 0; i < Q; i++) {
        cin >> target;
        cout << cache[target] << '\n';
    }

    return 0;
}

 

개발 환경 : vscode

지적, 조언, 질문 환영입니다! 댓글 남겨주세요~

 

'알고리즘 > 백준(BOJ)' 카테고리의 다른 글

백준 - 16932 모양 만들기  (0) 2020.07.18
백준 - 2213 트리의 독립집합  (0) 2020.07.16
백준 - 19236 청소년 상어  (0) 2020.07.12
백준 - 17086 아기 상어 2  (0) 2020.07.12
백준 - 16236 아기 상어  (0) 2020.07.12
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/04   »
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
글 보관함