티스토리 뷰

 

문제는 길고 거창해보이지만 요약하면 각 칸마다 가중치가 있고 S부터 G까지 최소비용의 거리를 구하라는 얘기다

다익스트라 기본문제다!

 

크게 설명할 필요가 없는 문제같다..!

 

소스코드

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
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
 
int map[111][111];
int d[111][111];
int dx[4= {0,0,-1,1};
int dy[4= {1,-1,0,0};
int n;
 
bool inner(int x, int y){
    return (0<=&& x<&& 0<=&& y<n);
}
 
int dijk(){
    memset(d,-1,sizeof(d));
    priority_queue<pair<int,pair<int,int>>> pq;
    pq.push({0,{0,0}});
 
    while(!pq.empty()){
        int cost = -pq.top().first;
        int x = pq.top().second.first;
        int y = pq.top().second.second;
        pq.pop();
 
        if(d[x][y] == -1) d[x][y]=cost;
 
        for(int i=0;i<4;i++){
            int nx = x+dx[i];
            int ny = y+dy[i];
            if(!inner(nx,ny)) continue;
            int ncost = -cost-map[nx][ny];
            if(d[nx][ny]==-1pq.push({ncost,{nx,ny}});
        }
    }
    return d[n-1][n-1];
}
 
 
int main(){
    //freopen("input.txt","r",stdin);
    int tc; scanf(" %d",&tc); int c=1;
    while(tc--){
        scanf(" %d",&n);
 
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                scanf(" %1d",&map[i][j]);
            }
        }        
        printf("#%d %d\n",c++,dijk());
    }
 
 
 
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
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
글 보관함