※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 6059번 문제인 Pasture Walking이다.
문제는 아래 링크를 확인하자.

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

 

6059번: Pasture Walking

The N cows (2 <= N <= 1,000) conveniently numbered 1..N are grazing among the N pastures also conveniently numbered 1..N. Most conveniently of all, cow i is grazing in pasture i. Some pairs of pastures are connected by one of N-1 bidirectional walkways tha

www.acmicpc.net

주어진 목초지들을 트리로 나타내고, 각 쿼리에 대해 p1에서 p2까지의 거리를 매번 구하는 것으로 문제를 해결할 수 있다.

 

p1에서 p2까지의 거리를 구하는 것은 p1에서 시작하는 dfs 또는 bfs를 이용해 O(N)의 시간복잡도로 해낼 수 있다.

 

위와 같이 거리를 구할 경우 최종 시간복잡도는 O(QN)으로, 이는 문제를 해결하기에 충분한 속도이다.

 

아래는 제출한 소스코드이다.

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

int N, Q;
vector<pair<int, int>> G[1001];

void dfs(int cur, int par, int dist, int target) {
	if (cur == target) cout << dist << '\n';
	for (auto& p : G[cur]) {
		if (p.first == par) continue;
		dfs(p.first, cur, dist + p.second, target);
	}
}

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

	cin >> N >> Q;
	for (int i = 1; i < N; i++) {
		int x, y, w; cin >> x >> y >> w;
		G[x].emplace_back(make_pair(y, w));
		G[y].emplace_back(make_pair(x, w));
	}

	while (Q--) {
		int x, y; cin >> x >> y;
		dfs(x, -1, 0, y);
	}
}
728x90

'BOJ' 카테고리의 다른 글

[BOJ 1233 // C++] 주사위  (0) 2022.09.28
[BOJ 6060 // C++] Wheel Rotation  (0) 2022.09.27
[BOJ 18003 // C++] Checkerboard  (0) 2022.09.25
[BOJ 1368 // C++] 물대기  (1) 2022.09.24
[BOJ 6057 // C++] Building A Fence  (0) 2022.09.23

+ Recent posts