반응형
https://www.acmicpc.net/problem/22255
22255번: 호석사우루스
(1, 1) -> (2, 1) -> (2, 2) -> (2, 3) -> (3, 3) -> (3, 4) -> (4, 4) -> (5, 4) -> (5, 5) 8번 만에 갈 수 있고 이게 최소이다.
www.acmicpc.net
[ 문제풀이 ]
1. node struct를 만들어 x좌표, y좌표, n번째 이동, 충격량을 저장합니다.
2. visited [ 101 ][ 101 ][ 3 ] 배열을 만들어 x좌표, y좌표, 3K + n번째 이동일 경우 충격량을 저장합니다.
3. dijkstra를 이용하여 시작점에서부터 도착점까지 충격량을 출력합니다.
[ 소스코드 ]
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | #include<iostream> #include<queue> using namespace std; int N, M; int Sx, Sy, Ex, Ey; int arr[101][101]; int visited[101][101][3]; int dx[3][4] = { -1,1,0,0, -1,1,0,0, 0,0,0,0 }; int dy[3][4] = { 0,0,-1,1, 0,0,0,0, -1,1,0,0, }; struct node { int x; int y; int cnt; int dist; }; struct cmp { bool operator()(node right, node left) { return left.dist < right.dist; } }; int main() { scanf("%d %d", &N, &M); scanf("%d %d %d %d", &Sx, &Sy, &Ex, &Ey); for (int i = 0; i < 3; i++) { for (int j = 1; j <= N; j++) { for (int k = 1; k <= M; k++) { visited[j][k][i] = 987654321; } } } for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { scanf("%d", &arr[i][j]); } } priority_queue<node, vector<node>, cmp> pq; pq.push({ Sx,Sy,1,0 }); visited[Sx][Sy][1] = 0; while (!pq.empty()) { const int x = pq.top().x; const int y = pq.top().y; const int cnt = pq.top().cnt % 3; const int dist = pq.top().dist; pq.pop(); if (y == Ey && x == Ex) { printf("%d", dist); return 0; } if (cnt == 0) { for (int i = 0; i < 4; i++) { const int yy = y + dy[cnt][i]; const int xx = x + dx[cnt][i]; if (yy > 0 && xx <= N && xx > 0 && yy <= M) { if (visited[xx][yy][1] > dist + arr[xx][yy] && arr[xx][yy] != -1) { visited[xx][yy][1] = dist + arr[xx][yy]; pq.push({ xx,yy,1,dist + arr[xx][yy] }); } } } } else if (cnt == 1) { for (int i = 0; i < 2; i++) { const int yy = y + dy[cnt][i]; const int xx = x + dx[cnt][i]; if (yy > 0 && xx <= N && xx > 0 && yy <= M) { if (visited[xx][yy][2] > dist + arr[xx][yy] && arr[xx][yy] != -1) { visited[xx][yy][2] = dist + arr[xx][yy]; pq.push({ xx,yy,2,dist + arr[xx][yy] }); } } } } else { for (int i = 0; i < 2; i++) { const int yy = y + dy[cnt][i]; const int xx = x + dx[cnt][i]; if (yy > 0 && xx <= N && xx > 0 && yy <= M) { if (visited[xx][yy][0] > dist + arr[xx][yy] && arr[xx][yy] != -1) { visited[xx][yy][0] = dist + arr[xx][yy]; pq.push({ xx,yy,0,dist + arr[xx][yy] }); } } } } } printf("-1"); } | cs |
반응형
'백준' 카테고리의 다른 글
[ 백준 ] 12738번 - 가장 긴 증가하는 부분 수열 3 (C++) (0) | 2022.12.21 |
---|---|
[ 백준 ] 1818번 - 책정리 (C++) (0) | 2022.12.20 |
[ 백준 ] 6593번 - 상범 빌딩 (C++) (0) | 2022.12.18 |
[ 백준 ] 12014번 - 주식 (C++) (0) | 2022.12.17 |
[ 백준 ] 1365번 - 꼬인 전깃줄 (C++) (0) | 2022.12.16 |