BOJ 4485

녹색 옷 입은 애가 젤다지?

문제출처

문제 해석

  • (0,0)에서 (N-1,N-1)으로 이동할 때, 링크가 잃을 수 밖에 없는 최소 금액을 구하는 문제입니다.
  • 상하좌우로 이동이 가능하며, 이동할 칸의 숫자만큼 금액을 잃습니다.

설계(5)

  • 다익스트라 알고리즘을 이용하면 풀이가 가능합니다.
  • 시작점을 포함하여 잃는 금액을 최소로하는 우선순위 큐를 설정합니다.
  • dist배열에 최소값을 갱신하고, 모든 탐색이 완료되면 dist[N-1][N-1]을 리턴합니다.

구현(5)

코드
#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

#define MAXN 125

int N;
int map[MAXN][MAXN];
int dist[MAXN][MAXN];
struct node{
    int x,y,cost;
    bool operator < (const node& a) const{
        return a.cost < cost;
    }
};
int dx[] = {0,0,1,-1};
int dy[]= {1,-1,0,0};

priority_queue<node> pq;
int dijkstra(){
    pq.push({0,0,map[0][0]});
    dist[0][0] = map[0][0];
    while (!pq.empty()){
        int x = pq.top().x;
        int y = pq.top().y;
        int cur_cost = pq.top().cost;
        pq.pop();
        if (cur_cost != dist[x][y]) continue;
        for (int i = 0 ;i < 4; i++){
            int nx = x +dx[i];
            int ny = y + dy[i];
            if (nx < 0 || ny < 0|| nx>=N || ny>=N) continue;
            int next_cost = cur_cost + map[nx][ny];
            if (dist[nx][ny] == -1 || (dist[nx][ny]!= -1 && dist[nx][ny]> next_cost)){
                dist[nx][ny] = next_cost;
                pq.push({nx,ny,next_cost});
            }
        }
    }
    return dist[N-1][N-1];
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t = 0;
    while (1){
        t++;
        cin >> N;
        if (N ==0) break;
        memset(dist,-1,sizeof(dist));
        for (int i =0 ;i<N; i++){
            for (int j= 0;j<N;j++){
                cin >> map[i][j];
            }
        }
        printf("Problem %d: %d\n",t,dijkstra());
    }
    return 0;
}
디버깅
제출결과
  • 4 ms

마무리

  • 단순 다익스트라 알고리즘 문제였습니다. solved.ac 난이도 기준이 알고리즘에 따라서 높게 평가되는 경향이 있는 것 같습니다.