백준 2644번 촌수계산
문제
우리 나라는 가족 혹은 친척들 사이의 관계를 촌수라는 단위로 표현하는 독특한 문화를 가지고 있다. 이러한 촌수는 다음과 같은 방식으로 계산된다. 기본적으로 부모와 자식 사이를 1촌으로 정의하고 이로부터 사람들 간의 촌수를 계산한다. 예를 들면 나와 아버지, 아버지와 할아버지는 각각 1촌으로 나와 할아버지는 2촌이 되고, 아버지 형제들과 할아버지는 1촌, 나와 아버지 형제들과는 3촌이 된다.
여러 사람들에 대한 부모 자식들 간의 관계가 주어졌을 때, 주어진 두 사람의 촌수를 계산하는 프로그램을 작성하시오.
문제풀이
사용한 알고리즘: BFS(1) 코드 11~38
pair< 노드, 거리 > 를 저장하는 queue를 사용하여 BFS로 촌수를 탐색합니다.
This file contains 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 <bits/stdc++.h> | |
using namespace std; | |
#define pii pair<int, int> | |
int n, a, b, m; | |
vector<int> tree[101]; | |
bool visited[101]; | |
// pair < 노드 , 거리 > | |
queue<pii> Q; | |
void BFS(int start) { | |
// < 시작점 , 거리=0 > | |
Q.push(pii(start, 0)); | |
// BFS 는 넣을때마다 visited 체크! | |
visited[start] = true; | |
while (!Q.empty()) { | |
int now = Q.front().first; | |
int dist = Q.front().second; | |
Q.pop(); | |
// b 도착하면 외치고 return | |
if (now == b) { | |
cout << dist << '\n'; | |
return; | |
} | |
// 연결된 노드들 탐색 | |
for (auto child : tree[now]) { | |
// visited 안한 점이면 ㄱㄱ | |
if (!visited[child]) { | |
// BFS는 넣을때 마다 visited 체크 | |
Q.push(pii(child, dist + 1)); | |
visited[child] = true; | |
} | |
} | |
} | |
// Q 빌때까지 돌려서 정답 없으면 친척관계없는거 | |
cout << -1 << '\n'; | |
} | |
int main() {ios_base::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); | |
cin >> n >> a >> b; | |
cin >> m; | |
for (int i = 0; i < m; ++i) { | |
int x, y; | |
cin >> x >> y; | |
tree[x].push_back(y); | |
tree[y].push_back(x); | |
} | |
BFS(a); | |
return 0; | |
} |
댓글
댓글 쓰기
긴 글 읽어주셔서 감사합니다.
궁금한게 있으시다면 댓글 달아주세요!