結果

問題 No.160 最短経路のうち辞書順最小
ユーザー snrnsidy
提出日時 2021-06-03 04:55:03
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 1,724 bytes
コンパイル時間 2,323 ms
コンパイル使用メモリ 202,200 KB
最終ジャッジ日時 2025-01-21 21:17:20
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3 WA * 1
other AC * 8 WA * 18
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h> 

using namespace std;

int dp[201][201];
int history[201][201];
vector <pair<int, int>> adj[201];

int main(void)
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    int N, M, S, G;
    int a, b, c;
    
    cin >> N >> M >> S >> G;
    for (int i = 0; i < M; i++)
    {
        cin >> a >> b >> c;
        adj[a].push_back(make_pair(b, c));
        adj[b].push_back(make_pair(a, c));
    }

    for (int i = 0; i <= N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            dp[i][j] = 1e9;
        }
    }

    dp[0][S] = 0;
    memset(history, -1, sizeof(history));

    for (int i = 1; i <= N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            for (auto it : adj[j])
            {
                int cost = it.second;
                int k = it.first;
                if (dp[i][j] > dp[i - 1][k] + cost)
                {
                    dp[i][j] = dp[i - 1][k] + cost;
                    history[i][j] = k;
                }
                else if (dp[i][j] == dp[i - 1][k] + cost)
                {
                    history[i][j] = min(history[i][j], k);
                }
            }
        }
    }

    long long int MIN = 1e9;
    int len = 0;
    int pos = 0;

    for (int i = 0; i <= N; i++)
    {
        if (MIN > dp[i][G])
        {
            MIN = dp[i][G];
            len = i;
            pos = G;
        }
    }

    stack <int> path;

    while (1)
    {
        path.push(pos);
        if (pos == S)
        {
            break;
        }
        pos = history[len][pos];
        len--;
    }

    while (!path.empty())
    {
        cout << path.top() << ' ';
        path.pop();
    }
    cout << '\n';

    return 0;
}
0