[BOJ/C++] 2644 촌수계산

햅쌀이·2023년 6월 4일
1

✍🏻 Algorithm

목록 보기
19/22
post-thumbnail

문제 링크 https://www.acmicpc.net/problem/2644

📝 문제

문제 설명
우리 나라는 가족 혹은 친척들 사이의 관계를 촌수라는 단위로 표현하는 독특한 문화를 가지고 있다. 이러한 촌수는 다음과 같은 방식으로 계산된다. 기본적으로 부모와 자식 사이를 1촌으로 정의하고 이로부터 사람들 간의 촌수를 계산한다. 예를 들면 나와 아버지, 아버지와 할아버지는 각각 1촌으로 나와 할아버지는 2촌이 되고, 아버지 형제들과 할아버지는 1촌, 나와 아버지 형제들과는 3촌이 된다.

여러 사람들에 대한 부모 자식들 간의 관계가 주어졌을 때, 주어진 두 사람의 촌수를 계산하는 프로그램을 작성하시오.

💻 코드

- 인접 행렬 저장

#include <iostream>
#include <vector>
using namespace std;

int N, M, A, B;
int result;
int arr[101][101] = { 0, };
int visited[101] = { 0, };

void dfs(int now, int cnt)
{
	visited[now] = 1;

	if (now == B) 
		result = cnt;

	for (int next = 1; next <= N; next++) {
		if (arr[now][next] == 0 || visited[next] == 1) continue;

		dfs(next, cnt + 1);
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> N;
	cin >> A >> B;
	cin >> M;
	for (int i = 0; i < M; i++) {
		int parent, child;
		cin >> parent >> child;
		arr[parent][child] = 1;
		arr[child][parent] = 1;
	}

	dfs(A, 0);

	if (result == 0)
		cout << -1;
	else
		cout << result;

	return 0;
}

- 인접 리스트 저장

#include <iostream>
#include <vector>
using namespace std;

int N, M, A, B;
int result;
vector<int> arr[101];
int visited[101] = { 0, };

void dfs(int now, int cnt)
{
	visited[now] = 1;

	if (now == B) 
		result = cnt;

	for (int i = 0; i < arr[now].size(); i++) {
		int next = arr[now][i];

		if (visited[next] == 1) continue;
		dfs(next, cnt + 1);
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> N;
	cin >> A >> B;
	cin >> M;
	for (int i = 0; i < M; i++) {
		int parent, child;
		cin >> parent >> child;
		arr[parent].push_back(child);
		arr[child].push_back(parent);
	}

	dfs(A, 0);

	if (result == 0)
		cout << -1;
	else
		cout << result;

	return 0;
}

📌 해결방법

  1. 촌수를 계산할 때는 parent에서도 child도 에서도 갈 수 있기 때문에 양방향 그래프로 구현
  2. now → next로 가면서 cnt를 하나씩 늘려준다!

✔ 느낀 점

인접리스트 방식이 메모리를 조금 덜 차지한다고 해서 두 개 다 하는 연습 중

profile
C++과 파이썬 공부중

2개의 댓글

comment-user-thumbnail
2023년 6월 5일

그... 실례지만 어데 이씹니까?

1개의 답글