-
반응형
https://www.acmicpc.net/problem/1916
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
풀이
다익스트라를 이용해서 풀어주면 되겠다! 하고 풀었는데, 맞왜틀이라 왜지,,,,왜 시간초과가 나오지 하고 생각을 하다가 문제 조건에 시간제한이 0.5초라는것을 보았다. 그래서 우선순위큐를 이용한 다익스트라 알고리즘을 사용하여 풀었더니 바로 통과를 했다.
코드
#include<iostream> #include<vector> #include<algorithm> #include<queue> #include<cstring> #define MAX 987654321 using namespace std; vector<pair<int,int>> maze[1001]; int cost[1001]; bool visited[1001] = { 0 }; int n, m,st,en; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 1; i <= n; i++) { cost[i] = MAX; } for (int i = 0; i < m; i++) { int to, from, cost; cin >> to >> from >> cost; maze[to].push_back({ from,cost }); } cin >> st >> en; priority_queue<pair<int,int>> pq; cost[st] = 0; pq.push({ 0,st }); while (!pq.empty()) { int now = pq.top().second; int dist = -pq.top().first; pq.pop(); if (cost[now] < dist) continue; for (auto next : maze[now]) { int next_node = next.first; int next_cost = next.second; if (cost[next_node] > next_cost + dist) { cost[next_node] = next_cost + dist; pq.push({ -(next_cost + dist),next_node }); } } } cout << cost[en]; return 0; }
반응형'문제풀이 > 백준oj' 카테고리의 다른 글
[백준OJ] 9935번 문자열 폭발 (0) 2021.08.18 [백준OJ] 11779번 최소비용 구하기 2 (0) 2021.08.17 [백준OJ] 1275번 커피숍2 (0) 2021.08.16 [백준OJ] 1306번 달려라 홍준 (0) 2021.08.16 [백준OJ] 20114번 미아 노트 (0) 2021.08.15 댓글