結果
| 問題 | No.34 砂漠の行商人 | 
| コンテスト | |
| ユーザー |  | 
| 提出日時 | 2014-10-06 00:33:02 | 
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 37 ms / 5,000 ms | 
| コード長 | 2,178 bytes | 
| コンパイル時間 | 810 ms | 
| コンパイル使用メモリ | 76,328 KB | 
| 実行使用メモリ | 10,624 KB | 
| 最終ジャッジ日時 | 2024-06-28 10:03:11 | 
| 合計ジャッジ時間 | 2,028 ms | 
| ジャッジサーバーID (参考情報) | judge2 / judge4 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| other | AC * 26 | 
ソースコード
// 想定解法: 格子点平面上の最短経路探索(Dijkstra, SPFA, etc.)
//           各位置での累計移動距離ごとの必要コスト最小化
//           もっといい解がありそうな気がするのでつよい人に期待
#include <cstdio>
#include <iostream>
#include <deque>
#include <map>
using namespace std;
#define REP(i, n)           for(int(i)=0;(i)<(n);++(i))
const int MAXN = 100;
int board[MAXN][MAXN];
map<int,int> cost[MAXN][MAXN];
const int INF = 1<<29;
const int dir[][2] = {{1,0},{0,1},{-1,0},{0,-1}};
int N, V, SX, SY, GX, GY;
// m[]が保持する stepを越えない最大のsから m[s]値 を返す
int getcost(map<int,int> &m, int step){
    auto it = m.lower_bound(step);
    return it != m.end() && it->first == step ? it->second : (--it)->second;
}
void solve(){
    REP(y,N) REP(x,N) cost[y][x][0] = INF;
    deque<pair<pair<int,int>,int> > q;
    q.push_back(make_pair(make_pair(SX,SY),0));
    cost[SY][SX][0] = 0;
    while(!q.empty()){
        auto &v = q.front();
        int x = v.first.first, y = v.first.second, s = v.second;
        q.pop_front();
        int nowcost = getcost(cost[y][x], s);
        for(int d = 0; d < 4; d++){
            int mx = x + dir[d][0];
            int my = y + dir[d][1];
            if(mx < 0 || my < 0 || mx >= N || my >= N) continue;
            int nextcost = nowcost + board[my][mx];
            if(getcost(cost[my][mx],s+1) > nextcost && nextcost < V){
                cost[my][mx][s+1] = nextcost;
                q.push_back(make_pair(make_pair(mx,my),s+1));
            }
        }
    }
    return;
}
int main(){
    cin >> N >> V >> SX >> SY >> GX >> GY;
    REP(y,N) REP(x,N) cin >> board[y][x];
    SX--,SY--,GX--,GY--;
    solve();
    int step = -1;
    auto gc = cost[GY][GX];
    for(auto it = gc.begin(); it != gc.end(); ++it){
        if(it->second < V){ step = it->first; break; }
    }
    cout << step << endl;
#if 0
    for(auto it = gc.begin(); it != gc.end(); ++it){
        fprintf(stderr, "step = %d, cost = %d\n", it->first, it->second);
    }
#endif
    return 0;
}
            
            
            
        