본문 바로가기

Algorithm/BAEKJOON

[BOJ] 1240번 노드사이의 거리 (C++)

728x90
반응형

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

 

1240번: 노드사이의 거리

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

www.acmicpc.net

 

#include <iostream>
#include <algorithm>
#define INF 987654321;
using namespace std;

int graph[1001][1001];

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	int n, m;
	cin >> n >> m;
	
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= n; j++){
			if(i == j) graph[i][j] = 0;
			else graph[i][j] = INF;
		}
	}
	
	for(int i = 0; i < n - 1; i++){
		int from, to, dis;
		cin >> from >> to >> dis;
		graph[from][to] = dis;
		graph[to][from] = dis;
	}
	
	for(int k = 1; k <= n; k++){
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= n; j++){
				graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]);
			}
		}
	}
	
	for(int i = 0; i < m; i++){
		int a, b;
		cin >> a >> b;
		cout << graph[a][b] << endl;
	}
	
	return 0;
}

플로이드 와샬 알고리즘을 이용하여 풀었다.

728x90
반응형

'Algorithm > BAEKJOON' 카테고리의 다른 글

[BOJ] 9251번 LCS (C++)  (0) 2022.05.06
[BOJ] 1916번 최소비용 구하기 (C++)  (0) 2022.05.06
[BOJ] 1719번 택배 (C++)  (0) 2022.05.05
[BOJ] 11404번 플로이드 (C++)  (0) 2022.05.04
[BOJ] 14938번 서강그라운드 (C++)  (0) 2022.05.04