algorithm codes/baekjoon online judge
1916번: 최소비용 구하기
mimizzang
2019. 4. 21. 17:47
문제 풀이
최소 비용일때마다 fee 배열에 저장된 최소비용을 갱신해줍니다. fee[finish]에 start node에서 finish node로 가는 최소 비용이 저장됩니다.
코드
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
int n, m, finish;
int fee[1001];
vector <pair<int,int>> graph[1001];
int go(int start) {
queue<int> q;
q.push(start);
fee[start] = 0;
while (!q.empty()) {
int x = q.front();
q.pop();
for (int i = 0; i < graph[x].size(); i++) {
int nx, cost;
nx = graph[x][i].first;
cost = graph[x][i].second;
if (fee[nx] == -1 || fee[x] + cost < fee[nx]) {
fee[nx] = fee[x] + cost;
if (nx != finish) {
q.push(nx);
}
}
}
}
return fee[finish];
}
int main() {
memset(fee, -1, sizeof(fee));
cin >> n >> m;
while (m--) {
int b, e, c; cin >> b >> e >> c;
graph[b].push_back(make_pair(e, c));
}
int start; cin >> start >> finish;
cout << go(start) << '\n';
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5; text-decoration:none">Colored by Color Scripter
|
제출 결과
문제 출처
https://www.acmicpc.net/problem/1916
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스의 출발 도시의 번호가 주어진다. 그리고 그 다음에는 도착지의 도시 번호가 주어지고 또 그 버스 비용이 주어진다. 버스 비용은 0보다 크거나 같고, 100,000보다 작은 정수이다. 그리고 M+3째 줄에는 우리가 구하고자 하는 구간
www.acmicpc.net