2 min read

λ°±μ€€ 25953번 ν…œν¬λŸ΄ κ·Έλž˜ν”„

문제 링크

λ¬Έμ œμ— μ ν˜€μžˆλŠ” λŒ€λ‘œ, 각 TTλ§ˆλ‹€ κ°„μ„  μ™„ν™”λ₯Ό λ”± ν•œ 번 ν•  수 μžˆλ‹€.

λ•Œλ¬Έμ— dist배열을 ν•˜λ‚˜λ§Œ 놓고 μ“°λ©΄ μ•ˆλ˜κ³ , 각 TTλ§ˆλ‹€ λ”°λ‘œ 놓고 μ¨μ•Όν•œλ‹€.

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

int n, t, m, s, e;
int dist[10000];
vector<vector<pair<int, int>>> adj[1000];

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> n >> t >> m >> s >> e;
    for (int i = 0; i < t; i++) {
        adj[i].resize(n);
        for (int j = 0; j < m; j++) {
            int a, b, c;
            cin >> a >> b >> c;
            adj[i][a].emplace_back(b, c);
            adj[i][b].emplace_back(a, c);
        }
    }

    fill(dist, dist+10000, 1e9);
    dist[s] = 0;
    for (int i = 0; i < t; i++) {
        int tmp[10000];
        copy(dist, dist+10000, tmp);
        for (int j = 0; j < n; j++) {
            if (dist[j] == 1e9) continue;
            for (auto [next, cost] : adj[i][j]) {
                if (dist[next] > dist[j] + cost) {
                    tmp[next] = dist[j] + cost;
                }
            }
        }
        copy(tmp, tmp+10000, dist);
    }

    if (dist[e] == 1e9) cout << -1;
    else cout << dist[e];

    return 0;
}

μ•½κ°„ 벨만 ν¬λ“œ λŠλ‚Œμ΄λ‹€. κ·Έλž˜ν”„ μ΅œλ‹¨κ²½λ‘œ μ•Œκ³ λ¦¬μ¦˜ μ •λ¦¬μ—μ„œ μ•Œμ•„λ³΄λ„λ‘ ν•˜μž. μ΄λ ‡κ²Œ 인접 리슀트둜 μž…λ ₯λ°›λŠ” 방식 말고, κ°„μ„ λ§Œ λ”°λ‘œ μž…λ ₯받아도 상관 X.