Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 컴공
- OS
- cs
- c++
- Computer science
- 스택
- 문제풀이
- 정석학술정보관
- 구현
- 컴퓨터공학과
- 자료구조
- 백준
- 정석
- 컴공과
- 브루트포스
- Stack
- 너비우선탐색
- vector
- bfs
- 코테
- 개발
- 오퍼레이팅시스템
- Operating System
- 코딩
- coding
- 알고리즘
- 그래프
- 북리뷰
- 오에스
- DP
Archives
- Today
- Total
Little Jay
[C++] 백준 11725번 - 트리의 부모 찾기 본문
트리를 활용한 문제이다.
사실 트리 문제가 나오면 DFS를 활용하는 것이 정배라고는 하지만 이 문제는 단순히 BFS를 통해서 문제를 풀 수 있었다.
1번 Node는 고려하지 않으므로, 1번 Node에서 출반하여 BFS 탐색을 수행하면 문제가 풀린다.
문제는 항상 root node가 1이 아니기 때문에 입력에서 양방향 인접리스트로 받았는데,
이제 visited한 것을 잘 처리해주면 된다.
#include <bits/stdc++.h>
#define endl '\n'
#define pii pair<int, int>
using namespace std;
int n;
vector<int> tree[100001];
bool visited[100001];
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n;
for (int i = 1; i < n; i++) {
int a, b; cin >> a >> b;
tree[a].push_back(b);
tree[b].push_back(a);
}
queue<int> q;
vector<pii> v;
q.push(1);
visited[1] = true;
while (!q.empty()) {
auto cur = q.front(); q.pop();
if (!tree[cur].empty()) {
for (int i = 0; i < tree[cur].size(); i++) {
if (!visited[tree[cur][i]]) {
q.push(tree[cur][i]);
v.push_back({ tree[cur][i], cur });
visited[tree[cur][i]] = true;
}
}
}
}
sort(v.begin(), v.end());
for (auto& item : v) {
cout << item.second << endl;
}
return 0;
}
'알고리즘 > BOJ' 카테고리의 다른 글
[C++] 백준 20291번 - 파일 정리 (0) | 2022.09.27 |
---|---|
[C++] 백준 14938번 - 서강그라운드 (0) | 2022.09.24 |
[C++] 백준 14675번 - 단절점과 단절선 (1) | 2022.09.19 |
[C++] 백준 13164번 - 행복한 유치원 (0) | 2022.09.03 |
[C++] 백준 10026번 - 적녹색약 (0) | 2022.08.31 |
Comments