티스토리 뷰
문제 출처: https://www.acmicpc.net/problem/2644
2644번: 촌수계산
사람들은 1, 2, 3, …, n (1 ≤ n ≤ 100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어
www.acmicpc.net
BFS로 촌수를 계산할 수 있다.
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<cstring>
#include<math.h>
#include<queue>
#include<vector>
using namespace std;
vector<int>adj[101];
int visited[101];
int main(void)
{
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int n; cin >> n;
int find1, find2;
cin >> find1 >> find2;
int m;
cin >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
queue<int> q;
q.push(find1);
visited[find1] = 1;
while (!q.empty()) {
int curr = q.front(); q.pop();
if (curr == find2) {
cout << visited[find2] - 1;
return 0;
}
for (auto next : adj[curr]) {
if (visited[next])continue;
visited[next] = visited[curr] + 1;
q.push(next);
}
}
cout << "-1";
}'PS' 카테고리의 다른 글
| [백준] 1182번 부분수열의 합 C++ (0) | 2022.07.18 |
|---|---|
| [백준] 13565번 침투 C++ (0) | 2022.07.15 |
| [백준] 9322번 철벽 보안 알고리즘 C++ (0) | 2022.07.13 |
| [백준] 14402번 야근 C++ (0) | 2022.07.12 |
| [백준] 4386번 별자리 만들기 C++ (0) | 2022.07.11 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 1004
- 6539
- tea time
- 골목길
- 1918
- 골목길C++
- 벨만-포드
- 1738
- 어린왕자 C++
- 벨만포드
- 타임머신
- 11657
- 후위 표기식
- 소셜네트워킹어플리케이션
- 7511
- 6018
- 중위 표기식 후위 표기식으로 변환
- C++
- 스택
- 상범빌딩
- 백준
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 | 31 |
글 보관함
