[C++] 백준 16940 : BFS 스페셜 저지
Updated:
백준 16940번 문제를 풀어보았다.

1. 문제 설명

BFS를 사용하여 푸는 문제.- 입력으로 주어진 BFS 방문 순서가 올바른 순서면 1, 아니면 0을 출력하는 문제
2. 문제 풀이
2.1 사용 변수
vector<vector<int> > list(N + 1);
unordered_set<int> us;
list- list[a]에는 a와 이어져있는 모든 node가 들어있음.
us- 다음으로 방문할 수 있는 후보 노드들을 저장
- 만약 이 후보들 중 answer[다음값]이 없다면 틀린 순서
2.2 Solution
- unordered_set으로 선언된
us에 후보를 저장하고 후보 중 다음순서로 지목된 노드가 존재하는지 확인
2.3 전체 코드
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_set>
#include <cstring>
using namespace std;
int main() {
int N; //the numbers of node & edge, index of start vertex
int n1, n2;
cin >> N;
vector<vector<int> > list(N + 1);
queue<int> q;
int * answer = new int[N];
bool* visited = new bool[N + 1];
memset(visited, 0, (N + 1) * sizeof(bool));
for (int i = 0; i < N - 1; i++) { //save information of edge
cin >> n1 >> n2;
list[n1].push_back(n2);
list[n2].push_back(n1);
}
for (int i = 0; i < N; i++)
cin >> answer[i];
if (answer[0] != 1) { //if first node isn't 1
cout << "0";
return 0;
}
q.push(1);
visited[1] = true;
int idx = 1;
while(!q.empty()){
int current = q.front();
q.pop();
unordered_set<int> us;
for (int j = 0; j < list[current].size(); j++) {
if (!visited[list[current][j]]) { //check if current child node has been visited
us.insert(list[current][j]);
visited[list[current][j]] = true;
}
}
for (int t = idx; t < idx+us.size(); t++)
{
if (us.count(answer[t]) == 0) {
cout << "0";
return 0;
}
q.push(answer[t]);
}
idx += us.size();
}
cout << "1";
return 0;
}
3. Review
기억 안남.
4. 실패한 접근 방법
- 없음.
Leave a comment