結果

問題 No.2328 Build Walls
ユーザー KKT89
提出日時 2023-05-28 14:02:28
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 395 ms / 3,000 ms
コード長 2,322 bytes
コンパイル時間 2,910 ms
コンパイル使用メモリ 227,628 KB
最終ジャッジ日時 2025-02-13 10:40:04
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 34
権限があれば一括ダウンロードができます

ソースコード

diff #

#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<long double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

template<typename T>
struct Dijkstra{
    const T inf=numeric_limits<T>::max();
    using P=pair<T,int>;
    int n;
    vector<vector<pair<int,T>>> g;
    vector<T> d;
    Dijkstra(int n):n(n),g(n),d(n){}
    void add_edge(int u,int v,T w){
        g[u].emplace_back(v,w);
    }
    vector<T> build(int s){
        for(int i=0;i<n;i++){
            d[i]=inf;
        }
        d[s]=0;
        priority_queue<P,vector<P>,greater<P>> pq;
        pq.emplace(d[s],s);
        while(pq.size()){
            P p=pq.top(); pq.pop();
            int v=p.second;
            if(d[v]<p.first)continue;
            for(auto &e:g[v]){
                int u=e.first; T c=e.second;
                if(d[u]>d[v]+c){
                    d[u]=d[v]+c;
                    pq.emplace(d[u],u);
                }
            }
        }
        return d;
    }
};

int dx[] = {1,-1,0,0,1,1,-1,-1};
int dy[] = {0,0,1,-1,1,-1,1,-1};

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int h,w; cin >> h >> w;
    vector<vector<ll>> a(h-2,vector<ll>(w));
    for (int i = 0; i < h - 2; ++i) {
        for (int j = 0; j < w; ++j) {
            cin >> a[i][j];
        }
    }
    h -= 2;
    Dijkstra<ll> g(h*w+2);
    int S = h*w, T = h*w+1;
    for (int i = 0; i < h; ++i) {
        if (a[i][0] != -1) g.add_edge(S, i*w+0, a[i][0]);
        if (a[i][w-1] != -1) g.add_edge(i*w+w-1, T, 0);
    }
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            if (a[i][j] == -1) continue;
            for (int k = 0; k < 8; ++k) {
                int nx = i+dx[k], ny = j+dy[k];
                if (0 <= nx and nx < h and 0 <= ny and ny < w and a[nx][ny] != -1) {
                    g.add_edge(i*w+j, nx*w+ny, a[nx][ny]);
                }
            }
        }
    }

    ll res = g.build(S)[T];
    if (res == numeric_limits<ll>::max()) res = -1;
    cout << res << endl;
}
0