Notice
Recent Posts
Recent Comments
Link
250x250
«   2025/05   »
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
Archives
Today
Total
관리 메뉴

피너클의 it공부방

백준 1240 노드사이의 거리 (c++) : 피너클 본문

백준

백준 1240 노드사이의 거리 (c++) : 피너클

피너클 2022. 5. 8. 00:39
728x90
반응형

https://www.acmicpc.net/problem/1240

 

1240번: 노드사이의 거리

N(2≤N≤1,000)개의 노드로 이루어진 트리가 주어지고 M(M≤1,000)개의 두 노드 쌍을 입력받을 때 두 노드 사이의 거리를 출력하라.

www.acmicpc.net

dfs를 이용한 문제다.

cin >> n >> m;
for (int i = 0; i < n - 1; i++) {
	int a, b, c;
	cin >> a >> b >> c;
	graph[a].push_back({ b, c });
	graph[b].push_back({ a, c });
}

값을 입력받은뒤 그래프를 양방향으로 연결해준다.

for (int i = 0; i < m; i++) {
	memset(visited, false, sizeof(visited));
	int a, b;
	cin >> a >> b;
	cout << dfs(a, b) << endl;
}

m번 반복하는 동안 계속 visited를 초기화 해주고 dfs를 통해 답을 출력한다.

int dfs(int now, int end) {
	if (now == end) return 0;
	visited[now] = true;
	int ans = 987654321;
	for (int i = 0; i < graph[now].size(); i++) {
		if (!visited[graph[now][i].first]) {
			ans = min(ans, graph[now][i].second + dfs(graph[now][i].first, end));
		}
	}
	return ans;
}

dfs함수는 현재 위치와 최종 목적지를 입력받는다.

만약 현재 위치가 최종 목적지라면 0을 리턴한다.

visited[now]를 true로 바꾼뒤 int ans를 선언한다. 만약 목적지로 가는 방법이 여러가지일때를 대비해 설정했다.

graph[now]에 연결된 모든 정점을 돌아보며 만약 아직 방문하지 않은 정점이라면

그 정점에 dfs를 해주고 ans를 업데이트한다.

그후 ans를 리턴한다.

#include <iostream>
#include <vector>
#include <algorithm>
#include <string.h>

using namespace std;

int n, m;
vector<pair<int, int>> graph[1001];
bool visited[1001];

int dfs(int now, int end) {
	if (now == end) return 0;
	visited[now] = true;
	int ans = 987654321;
	for (int i = 0; i < graph[now].size(); i++) {
		if (!visited[graph[now][i].first]) {
			ans = min(ans, graph[now][i].second + dfs(graph[now][i].first, end));
		}
	}
	return ans;
}

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

	cin >> n >> m;
	for (int i = 0; i < n - 1; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		graph[a].push_back({ b, c });
		graph[b].push_back({ a, c });
	}
	for (int i = 0; i < m; i++) {
		memset(visited, false, sizeof(visited));
		int a, b;
		cin >> a >> b;
		cout << dfs(a, b) << endl;
	}
}

전체코드다.

728x90
반응형
Comments