알고리즘
백준 1240번 노드사이의 거리 C++
영춘권의달인
2023. 1. 29. 12:05
https://www.acmicpc.net/problem/1240
1240번: 노드사이의 거리
N(2≤N≤1,000)개의 노드로 이루어진 트리가 주어지고 M(M≤1,000)개의 두 노드 쌍을 입력받을 때 두 노드 사이의 거리를 출력하라.
www.acmicpc.net
dfs
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int n, m;
int ans;
vector<vector<pair<int, int>>> graph;
vector<bool> visited;
void dfs(int curr, int target, int dist) {
if (curr == target) {
ans = dist;
return;
}
visited[curr] = true;
for (auto next : graph[curr]) {
if (visited[next.first]) continue;
dfs(next.first, target, dist + next.second);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
graph = vector<vector<pair<int, int>>>(n + 1, vector<pair<int, int>>());
visited = vector<bool>(n + 1, false);
for (int i = 0; i < n - 1; i++) {
int s, e, d;
cin >> s >> e >> d;
graph[s].push_back({ e,d });
graph[e].push_back({ s,d });
}
for (int i = 0; i < m; i++) {
for (auto a : visited) a = false;
int s, e;
cin >> s >> e;
dfs(s, e, 0);
cout << ans << "\n";
}
}