티스토리 뷰

PS

[백준] 2644번 촌수계산

Eastplanet 2022. 7. 14. 12:11

문제 출처: 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
링크
«   2026/01   »
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
글 보관함