문제 링크입니다: https://www.acmicpc.net/problem/25516
25516번: 거리가 k이하인 트리 노드에서 사과 수확하기
n개의 정점과 n - 1개의 간선으로 구성된 트리 T가 있다. 정점 번호는 0부터 n - 1까지이고 0번 정점이 루트이다. 모든 간선의 길이는 1이다. 트리 T의 각 정점에는 사과가 0개 또는 1개 놓여있다. 루
www.acmicpc.net
간단한 DFS 문제였습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
using namespace std; | |
const int MAX = 100000; | |
int result; | |
int n, k; | |
int apples[MAX]; | |
vector<int> graph[MAX]; | |
void func(int node, int dist) | |
{ | |
if (dist > k) | |
{ | |
return; | |
} | |
result += apples[node]; | |
for (int next : graph[node]) | |
{ | |
func(next, dist + 1); | |
} | |
} | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
cin >> n >> k; | |
for (int i = 0; i < n - 1; i++) | |
{ | |
int p, c; | |
cin >> p >> c; | |
graph[p].push_back(c); | |
} | |
for (int i = 0; i < n; i++) | |
{ | |
cin >> apples[i]; | |
} | |
func(0, 0); | |
cout << result << "\n"; | |
return 0; | |
} |

개발환경:Visual Studio 2022
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 4659번 비밀번호 발음하기 (0) | 2024.03.13 |
---|---|
백준 25596번 마트료시카 박스 II (0) | 2022.09.22 |
백준 25513번 빠른 오름차순 숫자 탐색 (0) | 2022.09.04 |
백준 25527번 Counting Peaks of Infection (0) | 2022.08.31 |
백준 25501번 재귀의 귀재 (0) | 2022.08.28 |