728x90
반응형
https://www.acmicpc.net/problem/1240
1. Logic
BFS로 노드를 지날 때 마다 거리를 더해주며 BFS를 돌면 된다.
입력을 받을 때 양방향으로 받아주고 m개를 입력 받을 때 마다 vis배열만 초기화 잘 시켜주면 된다.
2. Code
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<pair<int, int>> graph[1001];
bool vis[1001];
int BFS(int start, int end) {
queue<pair<int, int>>q;
q.push({start, 0});
vis[start] = true;
while(!q.empty()) {
int cur = q.front().first;
int curCost = q.front().second;
if(cur == end) {
return curCost;
}
q.pop();
for(int i = 0; i < graph[cur].size(); i++) {
int next = graph[cur][i].first;
int nCost = graph[cur][i].second;
if(vis[next]) continue;
vis[next] = true;
q.push({next, curCost+nCost});
}
}
return 0;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> m;
for(int i = 0; i < n-1; i++) {
int start, end, cost;
cin >> start >> end >> cost;
graph[start].push_back({end, cost});
graph[end].push_back({start, cost});
}
for(int i = 0; i < m; i++) {
memset(vis, false, sizeof(vis));
int start, end;
cin >> start >> end;
cout << BFS(start, end) << "\n";
}
}
알고리즘 Solve 후 제가 생각한 Logic을 기록하는 개인 공부 블로그입니다.
내용 중 최적화가 가능한 부분등은 언제든지 댓글로 틀린 부분 및 피드백 주시면 공부 및 반영하겠습니다🧐
728x90
반응형
'Algorithm > Beakjoon' 카테고리의 다른 글
[백준/Baekjoon] 2234 성곽 C++ :: BFS & Bit masking (1) | 2023.12.07 |
---|---|
[백준/Baekjoon] 1245 농장 관리 C++ :: Graph & BFS (2) | 2023.12.07 |
[백준/Baekjoon] 9656 돌 게임 2 C++ :: Implementation (1) | 2023.12.06 |
[백준/Baekjoon] 2482 색상환 C++ :: Dynamic programming (1) | 2023.12.05 |
[백준/Baekjoon] 2578 빙고 C++ :: Implementation (1) | 2023.12.04 |