Machineboy空
1068 : 트리 - DFS, 트리 본문
https://www.acmicpc.net/problem/1068
1068번: 트리
첫째 줄에 트리의 노드의 개수 N이 주어진다. N은 50보다 작거나 같은 자연수이다. 둘째 줄에는 0번 노드부터 N-1번 노드까지, 각 노드의 부모가 주어진다. 만약 부모가 없다면 (루트) -1이 주어진다
www.acmicpc.net
문제요약
트리 구조에서 한 노드를 지웠을 때 리프노드의 개수를 구하라.
난이도
Gold 5
//내 코드
#include <bits/stdc++.h>
using namespace std;
int n, a[52], k, ret;
vector<int> adj[52];
bool b[52];
void cut(int node)
{
b[node] = false;
for (int s : adj[node])
{
cut(s);
}
}
int main()
{
// 입력 받기
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
if (a[i] != -1)
adj[a[i]].push_back(i);
b[i] = true;
}
cin >> k;
if (a[k] == -1)
{
ret = 0;
}
// 노드 삭제
else
{
cut(k);
for (int i = 0; i < n; i++)
{
if (b[i] == false)
continue;
if (adj[i].size() == 0)
ret++;
else
{
bool flag = 1;
for (int j : adj[i])
{
if (b[j] == true)
flag = 0;
}
if (flag)
ret++;
}
}
}
cout << ret;
}
#include <bits/stdc++.h>
using namespace std;
// there가 없고 here만 있는 경우
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 << "\n";
return 0;
}
cout << dfs(root) << "\n";
return 0;
}
'Computer > Coding Test' 카테고리의 다른 글
16235: 인구 이동 - DFS (0) | 2024.02.23 |
---|---|
2589 : 보물섬 - BFS (0) | 2024.02.22 |
15686 : 치킨 배달 - 조합(Combination), 브루트포스, 백트래킹 (0) | 2024.02.22 |
2636 : 치즈 - DFS, BFS (1) | 2024.02.20 |
14502 : 연구소 - DFS, deep copy (0) | 2024.02.20 |